diff --git a/types/angular-desktop-notification/index.d.ts b/types/angular-desktop-notification/index.d.ts index a20d67cd21..6281396b66 100644 --- a/types/angular-desktop-notification/index.d.ts +++ b/types/angular-desktop-notification/index.d.ts @@ -101,7 +101,7 @@ declare module 'angular' { * Note: This property is not currently supported in any browser. * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/vibrate */ - vibrate?: boolean; + vibrate?: any; /** * The onclick property of the Notification interface specifies an event listener to receive click events. diff --git a/types/angular-gettext/index.d.ts b/types/angular-gettext/index.d.ts index 107d9e10e2..5b6eb1d90f 100644 --- a/types/angular-gettext/index.d.ts +++ b/types/angular-gettext/index.d.ts @@ -9,6 +9,7 @@ import * as angular from 'angular'; +export type gettextCatalog = angular.gettext.gettextCatalog; declare module 'angular' { export namespace gettext { diff --git a/types/angular-local-storage/index.d.ts b/types/angular-local-storage/index.d.ts index 76ab65b1b5..6e8c64416a 100644 --- a/types/angular-local-storage/index.d.ts +++ b/types/angular-local-storage/index.d.ts @@ -8,6 +8,10 @@ import * as angular from 'angular'; +export type ILocalStorageServiceProvider = angular.local.storage.ILocalStorageServiceProvider; +export type ILocalStorageService = angular.local.storage.ILocalStorageService; +export type ICookie = angular.local.storage.ICookie; + declare module 'angular' { export namespace local.storage { interface ILocalStorageServiceProvider extends angular.IServiceProvider { diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index ac9e6cece3..051539e2ac 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -97,7 +97,7 @@ declare module 'angular' { interface IControllerService { // Although the documentation doesn't state this, locals are optional (controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T; - (controllerConstructor: Function, locals?: any, bindings?: any): T; + (controllerConstructor: (...args: any[]) => T, locals?: any, bindings?: any): T; (controllerName: string, locals?: any, bindings?: any): T; } diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 719fcb5d5c..f35fb57570 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) 2.15 +// Type definitions for Angular Translate (pascalprecht.translate module) 2.16 // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,8 +47,8 @@ declare module 'angular' { } interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise<{ [key: string]: string }>; + (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 6dccefc926..6b82a2bcb4 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -4,6 +4,7 @@ // Georgii Dolzhykov // Caleb St-Denis // Leonard Thieu +// Steffen Kowalski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -484,6 +485,76 @@ declare namespace angular { $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; + + /** + * Suspend watchers of this scope subtree so that they will not be invoked during digest. + * + * This can be used to optimize your application when you know that running those watchers + * is redundant. + * + * **Warning** + * + * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. + * Only use this approach if you are confident that you know what you are doing and have + * ample tests to ensure that bindings get updated as you expect. + * + * Some of the things to consider are: + * + * * Any external event on a directive/component will not trigger a digest while the hosting + * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. + * * Transcluded content exists on a scope that inherits from outside a directive but exists + * as a child of the directive's containing scope. If the containing scope is suspended the + * transcluded scope will also be suspended, even if the scope from which the transcluded + * scope inherits is not suspended. + * * Multiple directives trying to manage the suspended status of a scope can confuse each other: + * * A call to `$suspend()` on an already suspended scope is a no-op. + * * A call to `$resume()` on a non-suspended scope is a no-op. + * * If two directives suspend a scope, then one of them resumes the scope, the scope will no + * longer be suspended. This could result in the other directive believing a scope to be + * suspended when it is not. + * * If a parent scope is suspended then all its descendants will be also excluded from future + * digests whether or not they have been suspended themselves. Note that this also applies to + * isolate child scopes. + * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers + * for that scope and its descendants. When digesting we only check whether the current scope is + * locally suspended, rather than checking whether it has a suspended ancestor. + * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be + * included in future digests until all its ancestors have been resumed. + * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` + * against the `$rootScope` and so will still trigger a global digest even if the promise was + * initiated by a component that lives on a suspended scope. + */ + $suspend(): void; + + /** + * Call this method to determine if this scope has been explicitly suspended. It will not + * tell you whether an ancestor has been suspended. + * To determine if this scope will be excluded from a digest triggered at the $rootScope, + * for example, you must check all its ancestors: + * + * ``` + * function isExcludedFromDigest(scope) { + * while(scope) { + * if (scope.$isSuspended()) return true; + * scope = scope.$parent; + * } + * return false; + * ``` + * + * Be aware that a scope may not be included in digests if it has a suspended ancestor, + * even if `$isSuspended()` returns false. + * + * @returns true if the current scope has been suspended. + */ + $isSuspended(): boolean; + + /** + * Resume watchers of this scope subtree in case it was suspended. + * + * See {$rootScope.Scope#$suspend} for information about the dangers of using this approach. + */ + $resume(): void; + /** * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. * @@ -1390,10 +1461,9 @@ declare namespace angular { interface IControllerService { // Although the documentation doesn't state this, locals are optional - (controllerConstructor: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; - (controllerConstructor: Function, locals?: IControllerLocals, later?: boolean, ident?: string): T; - (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; - (controllerName: string, locals?: any, later?: boolean, ident?: string): T; + (controllerConstructor: new (...args: any[]) => T, locals?: any): T; + (controllerConstructor: (...args: any[]) => T, locals?: any): T; + (controllerName: string, locals?: any): T; } interface IControllerProvider extends IServiceProvider { diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0c64fd361b..fc070f62df 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -39,7 +39,10 @@ const showOptions : Auth0LockShowOptions = { type: "error", text: "an error has occurred" }, - rememberLastLogin: false + rememberLastLogin: false, + languageDictionary: { + title: "test" + } }; lock.show(showOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 27639834db..7dc20ae176 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -161,6 +161,7 @@ interface Auth0LockShowOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; flashMessage?: Auth0LockFlashMessageOptions; rememberLastLogin?: boolean; + languageDictionary?: any; } interface AuthResult { diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index aa82e908e5..be87ceed2c 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -350,6 +350,7 @@ export interface Identity { user_id: string; provider: string; isSocial: boolean; + access_token?: string; profileData?: { email?: string; email_verified?: boolean; @@ -882,4 +883,4 @@ export class UsersManager { impersonate(userId: string, settings: ImpersonateSettingOptions): Promise; impersonate(userId: string, settings: ImpersonateSettingOptions, cb: (err: Error, data: any) => void): void; -} \ No newline at end of file +} diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index de09b2a91f..3a6da1b49d 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; export { t as types }; diff --git a/types/babel-generator/index.d.ts b/types/babel-generator/index.d.ts index 2e34d158fc..8afeca4cd1 100644 --- a/types/babel-generator/index.d.ts +++ b/types/babel-generator/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Johnny Estilles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 467b0193e7..50b759c3f5 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { BabylonOptions } from 'babylon'; import * as t from 'babel-types'; diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index df420c17bd..5c18c3ff29 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -2,15 +2,17 @@ // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien // Marvin Hagemeister +// Ryan Petrich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; export type Node = t.Node; -export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; +export default function traverse(parent: Node | Node[], opts: TraverseOptions, scope: Scope, state: S, parentPath?: NodePath): void; +export default function traverse(parent: Node | Node[], opts: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; -export interface TraverseOptions extends Visitor { +export interface TraverseOptions extends Visitor { scope?: Scope; noScope?: boolean; } @@ -25,6 +27,7 @@ export class Scope { bindings: { [name: string]: Binding; }; /** Traverse node with current scope and path. */ + traverse(node: Node | Node[], opts: TraverseOptions, state: S): void; traverse(node: Node | Node[], opts?: TraverseOptions, state?: any): void; /** Generate a unique identifier and add it to the current scope. */ @@ -339,10 +342,10 @@ export class NodePath { listKey: string; inList: boolean; parentKey: string; - key: string; + key: string | number; node: T; scope: Scope; - type: string; + type: T extends undefined | null ? string | null : string; typeAnnotation: object; getScope(scope: Scope): Scope; @@ -353,7 +356,8 @@ export class NodePath { buildCodeFrameError(msg: string, Error?: new (msg: string) => TError): TError; - traverse(visitor: Visitor, state?: any): void; + traverse(visitor: Visitor, state: T): void; + traverse(visitor: Visitor): void; set(key: string, node: Node): void; @@ -372,10 +376,10 @@ export class NodePath { find(callback: (path: NodePath) => boolean): NodePath; /** Get the parent function of the current path. */ - getFunctionParent(): NodePath; + getFunctionParent(): NodePath; /** Walk up the tree until we hit a parent node path in a list. */ - getStatementParent(): NodePath; + getStatementParent(): NodePath; /** * Get the deepest common ancestor and then from it, get the earliest relationship path @@ -537,6 +541,9 @@ export class NodePath { /** Get the source code associated with this node. */ getSource(): string; + /** Check if the current path will maybe execute before another path */ + willIMaybeExecuteBefore(path: NodePath): boolean; + // ------------------------- context ------------------------- call(key: string): boolean; @@ -582,9 +589,15 @@ export class NodePath { getCompletionRecords(): NodePath[]; - getSibling(key: string): NodePath; + getSibling(key: string | number): NodePath; + getAllPrevSiblings(): NodePath[]; + getAllNextSiblings(): NodePath[]; - get(key: string, context?: boolean | TraversalContext): NodePath; + get(key: K, context?: boolean | TraversalContext): + T[K] extends Array ? Array> : + T[K] extends Node | null | undefined ? NodePath : + never; + get(key: string, context?: boolean | TraversalContext): NodePath | NodePath[]; getBindingIdentifiers(duplicates?: boolean): Node[]; diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 8c892a3ca0..47068c3481 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -5,7 +5,7 @@ // Marvin Hagemeister // Boris Cherny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 export interface Comment { value: string; diff --git a/types/babel-webpack-plugin/index.d.ts b/types/babel-webpack-plugin/index.d.ts index 3f16d154ac..6f85bae2cc 100644 --- a/types/babel-webpack-plugin/index.d.ts +++ b/types/babel-webpack-plugin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/simlrh/babel-webpack-plugin // Definitions by: Jed Fox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { Plugin } from 'webpack'; import { TransformOptions } from 'babel-core'; diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index f394d2ba44..ca90ae9d4c 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: TeamworkGuy2 // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/babylon-walk/index.d.ts b/types/babylon-walk/index.d.ts index 02c3f39d10..43c9c1bf3a 100644 --- a/types/babylon-walk/index.d.ts +++ b/types/babylon-walk/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pugjs/babylon-walk // Definitions by: Marek Buchar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as babelTypes from 'babel-types'; diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb22f30c13..07eb74bb32 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { File, Expression } from 'babel-types'; diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index c63cb0c862..1c7e7e5996 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -1,4 +1,5 @@ import browserSync = require("browser-sync"); +import { EventEmitter } from "events"; (() => { //make sure that the interfaces are correctly exposed @@ -391,6 +392,57 @@ bs.init({ bs.reload(); +browserSync.use( + { + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(opts); + }, + "plugin:name": "test" + }, + { files: "*.css" } +); + +browserSync.use({ + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(bs.name); + } +}); + +browserSync( + { + server: { + baseDir: "test/fixtures" + }, + logLevel: "silent", + open: false + } +); + +var instanceName = "TestInstance"; +var namedInstance = browserSync.create(instanceName); +namedInstance.init({ + server: { index: "./app" }, + https: true +}); + +console.log(namedInstance.getOption("https")); // Should output true. + +var existingInstance = browserSync.get(instanceName); + +browserSync.create("InstanceWithEventEmitter", new EventEmitter()); + +// Should output something greater than 0. +console.log(browserSync.instances.length); + +browserSync.reset(); + +// Should output 0. +console.log(browserSync.instances.length); + +var cleanupTestInstance = browserSync.create("CleanupTest"); +cleanupTestInstance.cleanup(); +console.log(cleanupTestInstance.active); // Should output false. + function browserSyncInit(): browserSync.BrowserSyncInstance { var browser = browserSync.create(); browser.init(); diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index de0a457266..bcf0aa966e 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -456,11 +456,15 @@ declare namespace browserSync { * depending on your use-case. */ (config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * + */ + instances: Array; /** * Create a Browsersync instance * @param name an identifier that can used for retrieval later */ - create(name?: string): BrowserSyncInstance; + create(name?: string, emitter?: NodeJS.EventEmitter): BrowserSyncInstance; /** * Get a single instance by name. This is useful if you have your build scripts in separate files * @param name the identifier used for retrieval @@ -471,6 +475,11 @@ declare namespace browserSync { * @param name the name of the instance */ has(name: string): boolean; + /** + * Reset the state of the module. + * (should only be needed for test environments) + */ + reset(): void; } interface BrowserSyncInstance { @@ -481,6 +490,24 @@ declare namespace browserSync { * depending on your use-case. */ init(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; /** * Reload the browser * The reload method will inform all browsers about changed files and will either cause the browser @@ -510,28 +537,30 @@ declare namespace browserSync { */ stream(opts?: StreamOptions): NodeJS.ReadWriteStream; /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 + * Instance Cleanup. */ - notify(message: string, timeout?: number): void; + cleanup(fn?: (error: NodeJS.ErrnoException, bs: BrowserSyncInstance) => void): void; /** - * This method will close any running server, stop file watching & exit the current process. + * Register a plugin. + * Must implement at least a 'plugin' property that returns + * callable function. + * + * @method use + * @param {object} module The object to be `required`. + * @param {object} options The + * @param {any} cb A callback function that will return any errors. */ - exit(): void; + use(module: { "plugin:name"?: string, plugin: (opts: object, bs: BrowserSyncInstance) => any }, options?: object, cb?: any): void; + /** + * Callback helper to examine what options have been set. + * @param {string} name The key to search options map for. + */ + getOption(name: string): any; /** * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system */ watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; /** * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use * this to emit your own events, such as changed files, logging etc. diff --git a/types/buffer-reader/buffer-reader-tests.ts b/types/buffer-reader/buffer-reader-tests.ts new file mode 100644 index 0000000000..9868131c93 --- /dev/null +++ b/types/buffer-reader/buffer-reader-tests.ts @@ -0,0 +1,28 @@ +import BufferReader from 'buffer-reader'; + +const buffer = new Buffer(1000); +const reader = new BufferReader(buffer); +reader.append(new Buffer(1)); +reader.tell(); +reader.seek(1); +reader.move(2); +reader.restAll(); +reader.nextBuffer(2); +reader.nextString(5); +reader.nextString(5, 'utf8'); +reader.nextStringZero(); +reader.nextStringZero('utf8'); +reader.nextInt8(); +reader.nextUInt8(); +reader.nextInt16LE(); +reader.nextUInt16LE(); +reader.nextInt16BE(); +reader.nextUInt16BE(); +reader.nextInt32LE(); +reader.nextUInt32LE(); +reader.nextInt32BE(); +reader.nextUInt32BE(); +reader.nextFloatLE(); +reader.nextFloatBE(); +reader.nextDouble32LE(); +reader.nextDouble32BE(); diff --git a/types/buffer-reader/index.d.ts b/types/buffer-reader/index.d.ts new file mode 100644 index 0000000000..e83f081e69 --- /dev/null +++ b/types/buffer-reader/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for buffer-reader 0.1 +// Project: https://github.com/villadora/node-buffer-reader +// Definitions by: nrlquaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +export = BufferReader; + +declare class BufferReader { + /** + * Create a new reader, if no buffer provided, a empty buffer will be used. + */ + constructor(buffer?: Buffer) + /** + * Append new buffer to the end of current reader. + * @param buffer buffer to append + */ + append(buffer: Buffer): void; + /** + * Return current position of the reader. + */ + tell(): number; + /** + * Set new position of the reader, if the pos is invalid, an exception will be raised. + * @param position new position + */ + seek(position: number): void; + /** + * Move the position of reader by offset, offset can be negative; it can be used to skip some bytes. + * @param offset offset to move by + */ + move(offset: number): void; + /** + * Get all the remaining bytes as a Buffer. + */ + restAll(): Buffer; + /** + * Read a buffer with specified length. + * @param length specified length + */ + nextBuffer(length: number): Buffer; + /** + * Read next length of bytes as String, encoding default is 'utf8'. + * @param length length of the string to read + * @param encoding encoding of the string + */ + nextString(length: number, encoding?: string): string; + /** + * Read next bytes till the end of buffer as null-terminated string, encoding default is 'utf8'. + * @param encoding encoding of the string + */ + nextStringZero(encoding?: string): string; + /** + * Read next bytes as Int8, the value is just as the same format Buffer in nodejs doc. + */ + nextInt8(): number; + /** + * Read next bytes as UInt8, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt8(): number; + /** + * Read next bytes as Int16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16LE(): number; + /** + * Read next bytes as UInt16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16LE(): number; + /** + * Read next bytes as Int16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16BE(): number; + /** + * Read next bytes as UInt16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16BE(): number; + /** + * Read next bytes as Int32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32LE(): number; + /** + * Read next bytes as UInt32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32LE(): number; + /** + * Read next bytes as Int32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32BE(): number; + /** + * Read next bytes as UInt32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32BE(): number; + /** + * Read next bytes as FloatLE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatLE(): number; + /** + * Read next bytes as FloatBE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatBE(): number; + /** + * Read next bytes as Double32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32LE(): number; + /** + * Read next bytes as Double32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32BE(): number; +} diff --git a/types/buffer-reader/tsconfig.json b/types/buffer-reader/tsconfig.json new file mode 100644 index 0000000000..da70d80fe1 --- /dev/null +++ b/types/buffer-reader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-reader-tests.ts" + ] +} diff --git a/types/buffer-reader/tslint.json b/types/buffer-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buffer-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index f19514fe71..2c81c42aeb 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1361,6 +1361,39 @@ suite('assert', () => { assert.notDeepEqual(circularObject, secondCircularObject); }); + test('deepStrictEqual', () => { + assert.deepStrictEqual({tea: 'chai'}, {tea: 'chai'}); + assert.throws(() => assert.deepStrictEqual({tea: 'chai'}, {tea: 'black'})); + + const obja = Object.create({tea: 'chai'}); + const objb = Object.create({tea: 'chai'}); + + assert.deepStrictEqual(obja, objb); + + const obj1 = Object.create({tea: 'chai'}); + const obj2 = Object.create({tea: 'black'}); + + assert.throws(() => assert.deepStrictEqual(obj1, obj2)); + }); + + test('deepStrictEqual (ordering)', () => { + const a = {a: 'b', c: 'd'}; + const b = {c: 'd', a: 'b'}; + assert.deepStrictEqual(a, b); + }); + + test('deepStrictEqual (circular)', () => { + const circularObject: any = {}; + const secondCircularObject: any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepStrictEqual(circularObject, secondCircularObject); + + secondCircularObject.field2 = secondCircularObject; + assert.deepStrictEqual(circularObject, secondCircularObject); + }); + test('isNull', () => { assert.isNull(null); assert.isNull(undefined); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index d0f5ab099c..d260973b71 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -353,7 +353,7 @@ declare namespace Chai { notStrictEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is deeply equal to expected. + * Asserts that actual is deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -363,7 +363,7 @@ declare namespace Chai { deepEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is not deeply equal to expected. + * Asserts that actual is not deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -372,6 +372,16 @@ declare namespace Chai { */ notDeepEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts that actual is deeply strict equal (===) to expected. + * + * @type T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + /** * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index cb3db72855..8063cf2629 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -506,6 +506,7 @@ declare namespace Chart { } interface CommonAxe { + bounds?: string; type?: ScaleType | string; display?: boolean; id?: string; diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 0c69727a05..03b70ca459 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -367,9 +367,15 @@ declare namespace cast.framework.events { total?: number, whenSkippable?: number, endedReason?: EndedReason, - breakClipId?: string + breakClipId?: string, + breakId?: string ); + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + /** * The break clip's id. Refer to BreakClip.id */ diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index a75834b0a8..08ce57cf86 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -8,7 +8,8 @@ import { } from "chromecast-caf-receiver/cast.framework.system"; import { RequestEvent, - Event + Event, + BreaksEvent } from "chromecast-caf-receiver/cast.framework.events"; import { QueueBase, @@ -29,12 +30,16 @@ import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; +const breaksEvent = new BreaksEvent('BREAK_STARTED'); +breaksEvent.breakId = 'some-break-id'; +breaksEvent.breakClipId = 'some-break-clip-id'; + const track = new Track(1, "TEXT"); const breakClip = new BreakClip("id"); const adBreak = new Break("id", ["id"], 1); const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); const pManager = new PlayerManager(); -pManager.addEventListener("STALLED", () => {}); +pManager.addEventListener("STALLED", () => { }); const ttManager = new TextTracksManager(); const qManager = new QueueManager(); const qBase = new QueueBase(); @@ -47,10 +52,10 @@ const breakManager: BreakManager = { getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => {}, - setBreakSeekInterceptor: () => {}, - setPlayWatchedBreak: () => {}, - setVastTrackingInterceptor: () => {} + setBreakClipLoadInterceptor: () => { }, + setBreakSeekInterceptor: () => { }, + setPlayWatchedBreak: () => { }, + setVastTrackingInterceptor: () => { } }; const lrd: LoadRequestData = { @@ -103,4 +108,4 @@ const pData: PlayerData = { whenSkippable: 321 }; const binder = new PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => {}); +binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/cosmiconfig/cosmiconfig-tests.ts b/types/cosmiconfig/cosmiconfig-tests.ts index 508ad00aa0..c477eedb3e 100644 --- a/types/cosmiconfig/cosmiconfig-tests.ts +++ b/types/cosmiconfig/cosmiconfig-tests.ts @@ -22,6 +22,13 @@ Promise.all([ explorer.loadSync(path.join(__dirname, "sample-config.json")), ]).then(result => result); +const result = explorer.searchSync(); +if (result) { + const config = result.config; + const filepath = result.filepath; + const isEmpty = result.isEmpty; +} + explorer.clearLoadCache(); explorer.clearSearchCache(); explorer.clearCaches(); diff --git a/types/cosmiconfig/index.d.ts b/types/cosmiconfig/index.d.ts index eb876b6ef2..16ba1967f3 100644 --- a/types/cosmiconfig/index.d.ts +++ b/types/cosmiconfig/index.d.ts @@ -14,7 +14,7 @@ export interface Config { export type CosmiconfigResult = { config: Config; - filePath: string; + filepath: string; isEmpty?: boolean; } | null; diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 25d6151259..39be1cd0e7 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -1,6 +1,26 @@ 'use strict'; -import cytoscape = require('cytoscape'); +// TODO: document all aliases as aliases, not as duplicates! + +const assert = (tag: boolean) => { if (!tag) throw new Error(); }; +const aliases = (...obj: Array<{}>) => { if (obj.slice(1).some((alias) => alias !== obj[0])) throw new Error(); }; +const events = (obj: any) => { + aliases(obj.on, obj.bind, obj.listen, obj.addListener); + aliases(obj.promiseOn, obj.pon); + aliases(obj.off, obj.unbind, obj.unlisten, obj.removeListener); + aliases(obj.emit, obj.trigger); +}; + +// definitions +function oneOf(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E; +function oneOf(a: A, b: B, c: C, d: D): A | B | C | D; +function oneOf(a: A, b: B, c: C): A | B | C; +function oneOf(a: A, b: B): A | B; +function oneOf(...array: T[]): T { + return array[0]; +} + +import cytoscape = require('cytoscape'); const parentCSS = { 'padding-top': '10px', 'padding-left': '10px', @@ -69,6 +89,34 @@ const cy = cytoscape({ ] }, + // initial viewport state: + zoom: 1, + pan: { x: 0, y: 0 }, + + // interaction options: + minZoom: 1e-50, + maxZoom: 1e50, + zoomingEnabled: true, + userZoomingEnabled: true, + panningEnabled: true, + userPanningEnabled: true, + selectionType: 'single', + touchTapThreshold: 8, + desktopTapThreshold: 4, + autolock: false, + autoungrabify: false, + + // rendering options: + headless: false, + styleEnabled: true, + hideEdgesOnViewport: false, + hideLabelsOnViewport: false, + textureOnViewport: false, + motionBlur: false, + motionBlurOpacity: 0.2, + wheelSensitivity: 1, + pixelRatio: 'auto', + layout: { name: 'preset', padding: 5 @@ -80,6 +128,42 @@ cy.on('zoom', (event) => { cy.nodes('$node > node').style('opacity', 0); } }); +cy.off('zoom'); +events(cy); + +cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); +cy.add([ + { data: { id: 'h' }, position: {x: 250, y: 100} } +]); +const nodesBeforeDelete = cy.nodes(); +const edgesBeforeDelete = cy.edges(); + +const removed = cy.remove('#g #h'); +cy.add(removed); +const diffNodes = nodesBeforeDelete.diff(cy.nodes()); +const diffEdges = edgesBeforeDelete.diff(cy.edges()); +assert(diffNodes.left.size() === 0 && diffNodes.right.size() === 0 && diffNodes.both.size() === cy.nodes().size()); +assert(nodesBeforeDelete.same(cy.nodes())); +assert(edgesBeforeDelete.same(cy.edges())); + +const gh = cy.collection().add(cy.$id('g')).union(cy.getElementById('h')); +const gh2 = cy.$('#g #h'); +const gh3 = cy.nodes('#g #h'); +assert(gh2.same(gh)); +assert(gh3.same(gh)); +assert(gh.same(removed)); + +assert(cy.container() === null); // headless mode! + +cy.center(); +cy.center(gh); +aliases(cy.center, cy.centre); + +cy.fit(cy.$('#a #b #h')); + +const {x1, y1, x2, y2, w, h} = cy.extent(); + +aliases(cy.resize, cy.invalidateDimensions); cy.animate({ fit: { @@ -89,8 +173,323 @@ cy.animate({ duration: 500 }); -const node = cy.nodes()[0]; cy.animate({ - center: {eles: node}, + center: {eles: cy.nodes()[0]}, duration: 500 }); + +const anim = cy.animation({ + zoom: { + level: 1, + position: {x: 0, y: 0} + }, + pan: {x: 100, y: 100}, + duration: 100, + easing: 'ease' +}); +cy.stop(true, true); +anim.play(); +assert(anim.playing()); +anim.progress(anim.progress() + 50); +anim.time(anim.time() - 50); +anim.stop(); + +aliases(cy.layout, cy.createLayout, cy.makeLayout); + +// Preconfigured data for layouts (as it could be passed) +const boundingBox = oneOf({x1: 0, x2: 100, y1: 0, y2: 100}, {x1: 0, w: 100, y1: 0, h: 100}); +const positions = oneOf({a: {x: 100, y: 100}}, (node: cytoscape.NodeCollection): cytoscape.Position => ({x: 100, y: 100})); + +// TODO: uncomment after we have the way to add layout options properties from extensions +// const layouts = [ +// cy.layout({ +// name: 'null', +// ready: () => {}, +// stop: () => {} +// }), +// cy.layout({ +// name: 'random', +// fit: true, +// padding: 30, +// boundingBox, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'preset', +// positions, +// zoom: 1, +// pan: {x: 100, y: 100}, +// fit: false, +// padding: 30, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'grid', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// avoidOverlapPadding: 10, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// condense: false, +// rows: oneOf(10, undefined), +// cols: oneOf(10, undefined), +// position: (node) => ({ row: 1, col: 1 }), +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'circle', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// radius: oneOf(1, undefined), +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'concentric', +// fit: true, +// padding: 30, +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// equidistant: false, +// minNodeSpacing: 10, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// height: oneOf(500, undefined), +// width: oneOf(500, undefined), +// spacingFactor: oneOf(1, undefined), +// concentric: (node) => 1, +// levelWidth: (nodes) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'breadthfirst', +// fit: true, +// directed: false, +// padding: 30, +// circle: false, +// spacingFactor: 1.75, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// maximalAdjustments: 0, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'cose', +// ready: () => {}, +// stop: () => {}, +// animate: oneOf(true, false, 'end'), +// animationEasing: oneOf('ease-in-quad', undefined), +// animationDuration: oneOf(500, undefined), +// animateFilter: function ( node, i ){ return true; }, +// animationThreshold: 250, +// refresh: 20, +// fit: true, +// padding: 30, +// boundingBox: undefined, +// nodeDimensionsIncludeLabels: false, +// randomize: false, +// componentSpacing: 40, +// nodeRepulsion: (node) => 2048, +// nodeOverlap: 4, +// idealEdgeLength: (edge) => 32, +// edgeElasticity: (edge) => 32, +// nestingFactor: 1.2, +// gravity: 1, +// numIter: 1000, +// initialTemp: 1000, +// coolingFactor: 0.99, +// minTemp: 1.0, +// weaver: false +// }) +// ]; +// const lay = layouts[0]; +// aliases(lay.run, lay.start); +// events(lay); +// layouts.map(layout => { +// layout.run(); +// layout.stop(); +// }); + +// TODO: cy.style + +cy.png({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100 +}); +aliases(cy.jpg, cy.jpeg); +cy.jpg({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100, + quality: 0.5 +}); +cy.json(cy.json()); + +// Types possible to call methods +const ele = oneOf(cy.nodes()[0], cy.edges()[0]); +const eles = cy.elements(); +const node = cy.nodes()[0]; +const nodes = cy.nodes(); +const edge = cy.edges()[0]; +const edges = cy.edges(); + +assert(ele.cy() === cy); +eles.remove(); +assert(eles.removed()); +assert(!eles.inside()); +eles.restore(); + +([ele, eles, node, nodes, edge, edges] as cytoscape.CollectionReturnValue[]).forEach((elem) => { + aliases(elem.clone, elem.copy); + events(elem); + aliases(elem.data, elem.attr); + aliases(elem.removeData, elem.removeAttr); +}); +// TODO: tests for data flow + +const loops = oneOf(true, false); +node.degree(loops); node.indegree(loops); node.outdegree(loops); +nodes.totalDegree(loops); nodes.minDegree(loops); nodes.maxDegree(loops); +nodes.minIndegree(loops); nodes.maxIndegree(loops); nodes.minOutdegree(loops); nodes.maxOutdegree(loops); + +// tslint:disable-next-line:ban-types +const getsetPos = (func: T): T => { + func('x', func('x')); + func(func()); + func({x: 100, y: 100}); + return func; +}; + +aliases(node.modelPosition, node.point, node.position); +getsetPos(node.position); + +nodes.shift('x', 100); +nodes.shift({x: -100, y: 0}); + +aliases(nodes.modelPositions, nodes.positions, nodes.points); +nodes.positions((node, i) => Object.assign(node.position(), {x: node.position('x') + i})); + +aliases(node.renderedPosition, node.renderedPoint); +getsetPos(node.renderedPoint); + +// TODO: tests for compound nodes (relativePosition, in particular) + +const sizes: number[] = [ + ele.width(), ele.outerWidth(), ele.renderedWidth(), ele.renderedOuterWidth(), + ele.height(), ele.outerHeight(), ele.renderedHeight(), ele.renderedOuterHeight() +]; + +aliases(eles.boundingBox, eles.boundingbox); +aliases(eles.renderedBoundingBox, eles.renderedBoundingbox); + +const flags: boolean[] = [ + node.grabbed(), node.grabbable(), node.locked(), ele.active(), +]; + +const edgePoints: cytoscape.Position[] = [ + ...edge.controlPoints(), ...edge.segmentPoints(), edge.sourceEndpoint(), edge.targetEndpoint(), edge.midpoint() +]; + +aliases(eles.layout, eles.createLayout, eles.makeLayout); +const layout = eles.layout({name: 'random'}).run(); + +eles.select(); +assert(ele.selected()); // as we selected all, and this too +aliases(eles.unselect, eles.deselect); +eles.selectify(); +assert(ele.selectable()); +eles.unselectify(); + +eles.addClass('test'); +eles.toggleClass('test', oneOf(true, false, undefined)); +eles.removeClass('test'); +eles.classes(oneOf('test', undefined)); +eles.flashClass('test flash', oneOf(1000, undefined)); +assert(ele.hasClass('test')); + +eles.style('background-color', 'green'); +Object.keys(eles.style()).map(key => eles.style(key)); +eles.style(eles.style()); +aliases(eles.style, eles.css); +aliases(ele.renderedCss, ele.renderedStyle); + +eles.anySame(nodes); +aliases(eles.contains, eles.has); +aliases(eles.allAreNeighbors, eles.allAreNeighbours); +eles.is('#g'); +eles.allAre('#g'); +eles.some((el, i, els) => true); +eles.every((el, i, els) => true); + +aliases(eles.forEach, eles.each); +const selected: cytoscape.SingularElementArgument[] = [eles.eq(0), eles.first(), eles.last()]; +const collSel = cy.collection(selected); +const selectedNodes: cytoscape.NodeSingular[] = [nodes.eq(0), nodes.first(), nodes.last()]; +const collNodes = cy.collection(selectedNodes); +const selectedEdges: cytoscape.EdgeSingular[] = [edges.eq(0), edges.first(), edges.last()]; +eles.slice(0, -1); +eles.toArray(); + +aliases(eles.getElementById, eles.$id); +aliases(eles.union, eles.add, eles.or, eles.u, eles['+'], eles['|']); +aliases(eles.difference, eles.not, eles.subtract, eles.relativeComplement, eles['\\'], eles['!'], eles['-']); +aliases(eles.absoluteComplement, eles.abscomp, eles.complement); +aliases(eles.intersection, eles.intersect, eles.and, eles.n, eles['&'], eles['.']); +aliases(eles.symmetricDifference, eles.symdiff, eles.xor, eles['^'], eles['(+)'], eles['(-)']); +cy.collection([nodes[0]]).union(nodes[1]).union(eles.$id('g')); +eles.difference(collNodes).abscomp().intersection(collSel).symdiff(collNodes); +const diff = collSel.diff(collNodes); +cy.collection().merge(diff.left).merge(diff.right).merge(diff.both).unmerge(collSel).filter((ele, i, eles) => true); + +eles.sort((a, b) => 1).map((ele, i, eles) => [i, ele]); +eles.reduce((prev, ele, i, eles) => [...prev, [ele, i]], []).concat(['finish']); +const min = eles.min((ele, i, eles) => ele.id.length + i); min.ele.scratch('min', min.value); +const max = eles.max((ele, i, eles) => ele.id.length + i); max.ele.scratch('max', max.value); + +// TODO: traversing (need to actively check the nodes/edeges distinction) +// TODO: algorithms +// TODO: compound nodes (there aren't any in current test case) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index e85041861a..a3226defd2 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.1 +// Type definitions for Cytoscape.js 3.2 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -9,7 +9,7 @@ // // Translation from Objects in help to Typescript interface. // http://js.cytoscape.org/#notation/functions -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /** * cy --> Cy.Core @@ -361,7 +361,7 @@ declare namespace cytoscape { * * The default value is 1. */ - pixelRatio?: number; + pixelRatio?: number | 'auto'; } /** @@ -386,35 +386,42 @@ declare namespace cytoscape { /** * Add elements to the graph and return them. */ - add(eles: ElementDefinition | ElementDefinition[] | Collection): CollectionElements; + add(eles: ElementDefinition | ElementDefinition[] | CollectionArgument): CollectionReturnValue; /** * Remove elements in collecion or match the selector from the graph and return them. */ - remove(eles: Collection | Selector): CollectionElements; + remove(eles: CollectionArgument | Selector): CollectionReturnValue; /** * Get a collection from elements in the graph matching the specified selector or from an array of elements. * If no parameter specified, an empty collection will be returned */ - collection(eles?: Selector | CollectionElements[]): CollectionElements; + collection(eles?: Selector | CollectionArgument[]): CollectionReturnValue; /** * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById */ - getElementById(id: string): CollectionElements; + getElementById(id: string): CollectionReturnValue; + + /** + * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById + */ + $id(id: string): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - $(selector: Selector): CollectionElements; + $(selector: Selector): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - elements(selector?: Selector): CollectionElements; + elements(selector?: Selector): CollectionReturnValue; /** * Get nodes in the graph matching the specified selector. @@ -428,7 +435,7 @@ declare namespace cytoscape { /** * Get elements in the graph matching the specified selector or filter function. */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. @@ -599,14 +606,20 @@ declare namespace cytoscape { ready(fn: EventHandler): void; } - interface ZoomOptions { - /** The zoom level to set. */ - level: number; + interface ZoomOptionsModel { /** The position about which to zoom. */ position: Position; + } + interface ZoomOptionsRendered { /** The rendered position about which to zoom. */ renderedPosition: Position; } + interface ZoomOptionsLevel { + /** The zoom level to set. */ + level: number; + } + type ZoomOptions = ZoomOptionsLevel & (ZoomOptionsModel | ZoomOptionsRendered); + /** * http://js.cytoscape.org/#core/viewport-manipulation */ @@ -615,14 +628,21 @@ declare namespace cytoscape { * Get the HTML DOM element in which the graph is visualised. * A null value is returned if the Core is headless. */ - container(): any; + container(): Element | null; /** * Pan the graph to the centre of a collection. * * @param eles The collection to centre upon. */ - center(eles?: Collection): CollectionElements; + center(eles?: CollectionArgument): this; + + /** + * Pan the graph to the centre of a collection. + * + * @param eles The collection to centre upon. + */ + centre(eles?: CollectionArgument): this; /** * Pan and zooms the graph to fit to a collection. @@ -631,13 +651,13 @@ declare namespace cytoscape { * @param eles [optional] The collection to fit to. * @param padding [optional] An amount of padding (in pixels) to have around the graph */ - fit(eles?: Collection, padding?: number): CollectionElements; + fit(eles?: CollectionArgument, padding?: number): this; /** * Reset the graph to the default zoom level and panning position. * http://js.cytoscape.org/#cy.reset */ - reset(): CollectionElements; + reset(): this; /** * Get the panning position of the graph. @@ -651,7 +671,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position to pan the graph to. */ - pan(renderedPosition?: Position): void; + pan(renderedPosition?: Position): this; /** * Relatively pan the graph by a specified rendered position vector. @@ -659,7 +679,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position vector to pan the graph by. */ - panBy(renderedPosition: Position): void; + panBy(renderedPosition: Position): this; /** * Get whether panning is enabled. @@ -867,7 +887,8 @@ declare namespace cytoscape { * there is no resize or style event for arbitrary DOM elements. * http://js.cytoscape.org/#cy.resize */ - resize(): CollectionElements; + resize(): this; + invalidateDimensions(): this; } /** @@ -875,15 +896,15 @@ declare namespace cytoscape { * */ interface AnimationFitOptions { - eles: CollectionElements | Selector; // to which the viewport will be fitted. + eles: CollectionArgument | Selector; // to which the viewport will be fitted. padding: number; // Padding to use with the fitting. } interface CenterOptions { - eles: CollectionElements | Selector; // to which the viewport will be selected. + eles: CollectionArgument | Selector; // to which the viewport will be selected. } - interface AnimateOptionsCommon { + interface AnimationOptions { /** A zoom level to which the graph will be animated. */ - zoom?: number; + zoom?: ZoomOptions; /** A panning position to which the graph will be animated. */ pan?: Position; /** A relative panning position to which the graph will be animated. */ @@ -892,11 +913,13 @@ declare namespace cytoscape { fit?: AnimationFitOptions; /** An object containing centring options from which the graph will be animated. */ center?: CenterOptions; + /** easing - A transition-timing-function easing style string that shapes the animation progress curve. */ + easing?: string; // TODO: explicit type /** duration - The duration of the animation in milliseconds. */ duration?: number; } - interface AnimateOptions extends AnimateOptionsCommon { + interface AnimateOptions extends AnimationOptions { /** queue - A boolean indicating whether to queue the animation. */ queue?: boolean; /** complete - A function to call when the animation is done. */ @@ -904,14 +927,6 @@ declare namespace cytoscape { /** step - A function to call each time the animation steps. */ step?(): void; } - interface AnimationOptions extends AnimateOptionsCommon { - /** queue - A transition-timing-function easing style string that shapes the animation progress curve. */ - easing?: boolean; - /** complete - A function to call when the animation is done. */ - complete?(): void; - /** step - A function to call each time the animation steps. */ - step?(): void; - } interface CoreAnimation { /** @@ -993,6 +1008,7 @@ declare namespace cytoscape { * An analogue to make a layout on a subset of the graph exists as eles.makeLayout(). */ makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1080,17 +1096,18 @@ declare namespace cytoscape { /** * Export the current graph view as a JPG image in Base64 representation. */ - jpg(options?: ExportOptions): string; + jpg(options?: ExportJpgOptions): string; /** * Export the current graph view as a JPG image in Base64 representation. */ - jpeg(options?: ExportOptions): string; + jpeg(options?: ExportJpgOptions): string; /** * Export the graph as JSON, the same format used at initialisation. */ - json(): string; + json(): object; + json(json: object): this; } /** @@ -1100,13 +1117,14 @@ declare namespace cytoscape { * The input can be any element (node and edge) collection. * http://js.cytoscape.org/#collection */ - interface Collection extends Singular, + interface Collection + extends Singular, CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, CollectionSelection, CollectionStyle, CollectionAnimation, - CollectionComparision, CollectionIteration, - CollectionBuildingUnion, CollectionAlgorithms { } + CollectionComparision, CollectionIteration, + CollectionBuildingFiltering, CollectionAlgorithms { } /** * ele --> Cy.Singular @@ -1127,7 +1145,8 @@ declare namespace cytoscape { /** * The output is a collection of node and edge elements OR single element. */ - type CollectionElements = EdgeCollection | NodeCollection | SingularElement; + type CollectionArgument = EdgeCollection | NodeCollection | SingularElementArgument; + type CollectionReturnValue = EdgeCollection & NodeCollection & SingularElementReturnValue; /** * edges -> Cy.EdgeCollection @@ -1135,7 +1154,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends Collection, EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1143,19 +1162,18 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends Collection, NodeSingular, NodeCollectionMetadata, NodeCollectionPosition, NodeCollectionTraversing, NodeCollectionCompound { } - interface SingularElement extends EdgeSingular, NodeSingular { - // Intentionally empty. - } + type SingularElementArgument = EdgeSingular | NodeSingular; + type SingularElementReturnValue = EdgeSingular & NodeSingular; /** * edge --> Cy.EdgeSingular * a collection of a single edge */ interface EdgeSingular extends Singular, - EdgeSingularData, EdgeSingularTraversing { } + EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular @@ -1172,24 +1190,24 @@ declare namespace cytoscape { * Remove the elements from the graph. * http://js.cytoscape.org/#eles.remove */ - remove(): CollectionElements; + remove(): CollectionReturnValue; /** * Put removed elements back into the graph. * http://js.cytoscape.org/#eles.restore */ - restore(): CollectionElements; + restore(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - clone(): CollectionElements; + clone(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - copy(): CollectionElements; + copy(): CollectionReturnValue; /** * Effectively move edges to different nodes. The modified (actually new) elements are returned. @@ -1207,6 +1225,10 @@ declare namespace cytoscape { * http://js.cytoscape.org/#collection/graph-manipulation */ interface SingularGraphManipulation { + /** + * Get the core instance that owns the element. + */ + cy(): Core; /** * Get whether the element has been removed from the graph. * http://js.cytoscape.org/#ele.removed @@ -1279,8 +1301,8 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.removeData * @param names A space-separated list of fields to delete. */ - removeData(names?: string): CollectionElements; - removeAttr(names?: string): CollectionElements; + removeData(names?: string): CollectionReturnValue; + removeAttr(names?: string): CollectionReturnValue; /** * Get an array of the plain JavaScript object @@ -1313,6 +1335,22 @@ declare namespace cytoscape { * @param obj The object containing name- value pairs to update data fields. */ data(obj: any): void; + /** + * Get a particular data field for the element. + * @param name The name of the field to get. + */ + attr(name?: string): any; + /** + * Set a particular data field for the element. + * @param name The name of the field to set. + * @param value The value to set for the field. + */ + attr(name: string, value: any): void; + /** + * Update multiple data fields at once via an object. + * @param obj The object containing name- value pairs to update data fields. + */ + attr(obj: any): void; /** * Get or set the scratchpad at a particular namespace, @@ -1461,17 +1499,77 @@ declare namespace cytoscape { * Get the (model) position of a node. */ position(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + position(dimension: PositionDimension): number; /** * Set the value of a specified position dimension. * @param dimension The position dimension to set. * @param value The value to set to the dimension. */ - position(dimension: PositionDimension, value?: Position): void; + position(dimension: PositionDimension, value: number): this; /** * Set the position using name-value pairs in the specified object. * @param pos An object specifying name-value pairs representing dimensions to set. */ - position(pos: Position): void; + position(pos: Position): this; + /** + * Get the (model) position of a node. + */ + modelPosition(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + modelPosition(pos: Position): this; + /** + * Get the (model) position of a node. + */ + point(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + point(pos: Position): this; + + /** + * Shift the positions of the nodes by a given model position vector. + * @param dimension The position dimension to shift. + * @param value The value to shift the dimension. + */ + shift(dimension: PositionDimension, value?: number): this; + /** + * Shift the positions of the nodes by a given model position vector. + * @param pos An object specifying name-value pairs representing dimensions to shift. + */ + shift(pos: Position): this; /** * Get or set the rendered (on-screen) position of a node. @@ -1542,8 +1640,8 @@ declare namespace cytoscape { * @param ele The element being iterated over for which the function should return a position to set. * @param ix The index of the element when iterating over the elements in the collection. */ - type ElementPositionFunction = (ele: CollectionElements, ix: number) => void; - type ElementCollectionFunction = (ele: CollectionElements, ix: number, eles: CollectionElements) => void; + type ElementPositionFunction = (ele: NodeSingular, ix: number) => void; + type ElementCollectionFunction = (ele: NodeSingular, ix: number, eles: CollectionArgument) => void; /** * http://js.cytoscape.org/#collection/position--dimensions @@ -1556,9 +1654,7 @@ declare namespace cytoscape { * http://js.cytoscape.org/#nodes.positions */ positions(handler: ElementPositionFunction | Position): void; - modelPositions(handler: ElementPositionFunction | Position): void; - points(handler: ElementPositionFunction | Position): void; /** @@ -1647,11 +1743,13 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.boundingBox */ boundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + boundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; /** * Get the bounding box of the elements in rendered coordinates. * @param options An object containing options for the function. */ renderedBoundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + renderedBoundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; } /** @@ -1668,9 +1766,9 @@ declare namespace cytoscape { * * @param options The layout options. */ - layout(options: LayoutOptions): CollectionElements; - makeLayout(options: LayoutOptions): CoreLayout; - createLayout(options: LayoutOptions): CoreLayout; + layout(options: LayoutOptions): LayoutManipulation; + makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1684,7 +1782,7 @@ declare namespace cytoscape { // easing of animation, if enabled animationEasing?: number; // collection of elements involved in the layout; set by cy.layout() or eles.layout() - eles: CollectionElements; + eles: CollectionArgument; // whether to fit the viewport to the graph fit?: boolean; // padding to leave between graph and viewport @@ -1811,11 +1909,50 @@ declare namespace cytoscape { flashClass(classes: ClassNames, duration?: number): void; /** - * Get or set a particular style property value. - * @param name The name of the visual style property to get. + * Set a particular style property value. + * @param name The name of the visual style property to set. * @param value The value to which the property is set. */ - style(name?: string, value?: any): any; + style(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + style(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + style(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + style(): {[index: string]: any}; + /** + * Set a particular style property value. + * @param name The name of the visual style property to set. + * @param value The value to which the property is set. + */ + css(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + css(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + css(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + css(): {[index: string]: any}; + /** + * Remove all or specific style overrides. + * @param names A space-separated list of property names to remove overrides + */ + removeStyle(names?: string): this; } /** @@ -1977,27 +2114,36 @@ declare namespace cytoscape { * * @param eles The other elements to compare to. */ - same(eles: Collection): boolean; + same(eles: CollectionArgument): boolean; /** * Determine whether this collection contains any of the same elements as another collection. * * @param eles The other elements to compare to. */ - anySame(eles: Collection): boolean; + anySame(eles: CollectionArgument): boolean; + + /** + * Determine whether this collection contains all of the elements of another collection. + */ + contains(eles: CollectionArgument): boolean; + /** + * Determine whether this collection contains all of the elements of another collection. + */ + has(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbors(eles: Collection): boolean; + allAreNeighbors(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbours(eles: Collection): boolean; + allAreNeighbours(eles: CollectionArgument): boolean; /** * Determine whether any element in this collection matches a selector. @@ -2021,7 +2167,7 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - some(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + some(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; /** * Determine whether all elements in this collection satisfy the specified test function. @@ -2032,13 +2178,13 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - every(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + every(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; } /** * http://js.cytoscape.org/#collection/iteration */ - interface CollectionIteration { + interface CollectionIteration { /** * Get the number of elements in the collection. */ @@ -2070,8 +2216,8 @@ declare namespace cytoscape { * eles - The collection of elements being iterated. * @param thisArg [optional] The value for this within the iterating function. */ - each(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; - forEach(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; + each(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; + forEach(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; /** * Get an element at a particular index in the collection. @@ -2080,21 +2226,21 @@ declare namespace cytoscape { * * @param index The index of the element to get. */ - eq(index: number): CollectionElements; + eq(index: number): TOut; /** * Get an element at a particular index in the collection. * * @param index The index of the element to get. */ - [index: number]: CollectionElements; + [index: number]: TOut; /** * Get the first element in the collection. */ - first(): CollectionElements; + first(): TOut; /** * Get the last element in the collection. */ - last(): CollectionElements; + last(): TOut; /** * Get a subset of the elements in the collection based on specified indices. @@ -2106,7 +2252,12 @@ declare namespace cytoscape { * If omitted, all elements from the start position and to the end of the array will be selected. * Use negative numbers to select from the end of an array. */ - slice(start?: number, end?: number): CollectionElements; + slice(start?: number, end?: number): this; + + /** + * Get the collection as an array, maintaining the order of the elements. + */ + toArray(): SingularElementReturnValue[]; } /** @@ -2118,7 +2269,7 @@ declare namespace cytoscape { * @param eles The elements or array of elements to add or elements in the graph matching the selector. * http://js.cytoscape.org/#eles.union */ - type CollectionBuildingUnionFunc = (eles: Collection | Collection[] | Selector) => CollectionElements; + type CollectionBuildingUnionFunc = (eles: CollectionArgument | CollectionArgument[] | Selector) => CollectionReturnValue; /** * Get a new collection, resulting from the collection without some specified elements. @@ -2126,7 +2277,7 @@ declare namespace cytoscape { * @param eles The elements that will not be in the resultant collection. * Elements from the calling collection matching this selector will not be in the resultant collection. */ - type CollectionBuildingDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2135,7 +2286,7 @@ declare namespace cytoscape { * A selector representing the elements to intersect with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionBuildingIntersectionFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingIntersectionFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements that are in the calling collection or the passed collection but not in both. @@ -2144,40 +2295,52 @@ declare namespace cytoscape { * A selector representing the elements to apply the symmetric difference with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionSymmetricDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionSymmetricDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * http://js.cytoscape.org/#collection/building--filtering */ - interface CollectionBuildingUnion { + interface CollectionBuildingFiltering { + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + getElementById(id: string): TOut; + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + $id(id: string): TOut; + /** * Get a new collection, resulting from adding the collection with another one * http://js.cytoscape.org/#eles.union */ union: CollectionBuildingUnionFunc; - // [index: "u"]: CollectionBuildingUnionFunc; + u: CollectionBuildingUnionFunc; add: CollectionBuildingUnionFunc; - // [index: "+"]: CollectionBuildingUnionFunc; + '+': CollectionBuildingUnionFunc; or: CollectionBuildingUnionFunc; - // [index: "|"]: CollectionBuildingUnionFunc; + '|': CollectionBuildingUnionFunc; /** * Get a new collection, resulting from the collection without some specified elements. * http://js.cytoscape.org/#eles.difference */ difference: CollectionBuildingDifferenceFunc; - // [index: "\\"]: CollectionBuildingDifferenceFunc; + subtract: CollectionBuildingDifferenceFunc; + '\\': CollectionBuildingDifferenceFunc; not: CollectionBuildingDifferenceFunc; - // [index: "!"]: CollectionBuildingDifferenceFunc; + '!': CollectionBuildingDifferenceFunc; relativeComplement: CollectionBuildingDifferenceFunc; - // [index: "-"]: CollectionBuildingDifferenceFunc; + '-': CollectionBuildingDifferenceFunc; /** * Get all elements in the graph that are not in the calling collection. * http://js.cytoscape.org/#eles.absoluteComplement */ - absoluteComplement(): CollectionElements; - abscomp(): CollectionElements; - complement(): CollectionElements; + absoluteComplement(): CollectionReturnValue; + abscomp(): CollectionReturnValue; + complement(): CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2186,9 +2349,9 @@ declare namespace cytoscape { intersection: CollectionSymmetricDifferenceFunc; intersect: CollectionSymmetricDifferenceFunc; and: CollectionSymmetricDifferenceFunc; - // [index: "n"]: CollectionSymmetricDifferenceFunc; - // [index: "&"]: CollectionSymmetricDifferenceFunc; - // [index: "."]: CollectionSymmetricDifferenceFunc; + n: CollectionSymmetricDifferenceFunc; + '&': CollectionSymmetricDifferenceFunc; + '.': CollectionSymmetricDifferenceFunc; /** * Get the elements that are in the calling collection @@ -2198,11 +2361,9 @@ declare namespace cytoscape { symmetricDifference: CollectionSymmetricDifferenceFunc; symdiff: CollectionSymmetricDifferenceFunc; xor: CollectionSymmetricDifferenceFunc; - // [index: "^"]: CollectionSymmetricDifferenceFunc; - // [index: "(+)"]: CollectionSymmetricDifferenceFunc; - // [index: "(-)"]: CollectionSymmetricDifferenceFunc; - - // [index: string]: CollectionBuildingDifferenceFunc |CollectionBuildingUnionFunc | CollectionBuildingDifferenceFunc | CollectionSymmetricDifferenceFunc; + '^': CollectionSymmetricDifferenceFunc; + '(+)': CollectionSymmetricDifferenceFunc; + '(-)': CollectionSymmetricDifferenceFunc; /** * Perform a traditional left/right diff on the two collections. @@ -2216,12 +2377,62 @@ declare namespace cytoscape { * both - is the set of elements in both collections. * http://js.cytoscape.org/#eles.diff */ - diff(selector: Selector | Collection): { - left: CollectionElements, - right: CollectionElements, - both: CollectionElements + diff(selector: Selector | CollectionArgument): { + left: CollectionReturnValue, + right: CollectionReturnValue, + both: CollectionReturnValue }; + /** + * Perform a in-place merge of the given elements into the calling collection. + * @param eles The elements to merge in-place or a selector representing the elements to merge. + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.union() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var j = cy.$('#j'); + * var e = cy.$('#e'); + * col.merge( j ).merge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge('#j').merge('#e'); + */ + merge(eles: CollectionArgument | string): this; + /** + * Perform an in-place operation on the calling collection to remove the given elements. + * @param eles The elements to remove in-place or a selector representing the elements to remove . + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.filter() or eles.remove() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var e = cy.$('#e'); + * col.merge( cy.nodes() ); + * col.unmerge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge( cy.nodes() ); + * col.unmerge('#e'); + */ + unmerge(eles: CollectionArgument | string): this; + /** * Get a new collection containing elements that are accepted by the specified filter. * @@ -2231,21 +2442,21 @@ declare namespace cytoscape { * ele - The element being considered. * http://js.cytoscape.org/#eles.filter */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: TOut, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Get the nodes that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - nodes(selector: Selector): NodeCollection; + nodes(selector?: Selector): NodeCollection; /** * Get the edges that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - edges(selector: Selector): EdgeCollection; + edges(selector?: Selector): EdgeCollection; /** * Get a new collection containing the elements sorted by the @@ -2257,7 +2468,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.sort */ - sort(sort: (ele1: CollectionElements, ele2: CollectionElements) => number): CollectionElements; + sort(sort: (ele1: CollectionArgument, ele2: CollectionArgument) => number): CollectionReturnValue; /** * Get an array containing values mapped from the collection. @@ -2270,7 +2481,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.map */ - map(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): any[]; + map(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): any[]; /** * Reduce a single value by applying a @@ -2282,11 +2493,13 @@ declare namespace cytoscape { * ele The current element. * ix The index of the current element. * eles The collection of elements being reduced. - * + * @param initialValue The initial value for reducing + * It is used also for type inference of output, but the type can be + * also stated explicitly as generic * http://js.cytoscape.org/#eles.reduce */ - reduce(fn: (prevVal: any, ele: CollectionElements, - ix: number, eles: CollectionElements) => any): number[]; + reduce(fn: (prevVal: T, ele: SingularElementReturnValue, + ix: number, eles: CollectionReturnValue) => T, initialValue: T): T; /** * Find a minimum value in a collection. @@ -2299,7 +2512,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.min */ - min(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + min(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The minimum value found. */ @@ -2307,7 +2520,7 @@ declare namespace cytoscape { /** * The element that corresponds to the minimum value. */ - ele: CollectionElements + ele: CollectionArgument }; /** @@ -2321,7 +2534,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.max */ - max(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + max(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The maximum value found. */ @@ -2329,7 +2542,7 @@ declare namespace cytoscape { /** * The element that corresponds to the maximum value. */ - ele: CollectionElements + ele: CollectionArgument }; } @@ -2351,7 +2564,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - neighborhood(selector?: Selector): CollectionElements; + neighborhood(selector?: Selector): CollectionReturnValue; /** * Get the open neighbourhood of the elements. @@ -2362,7 +2575,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - openNeighborhood(selector?: Selector): CollectionElements; + openNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the closed neighbourhood of the elements. * @@ -2372,13 +2585,54 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - closedNeighborhood(selector?: Selector): CollectionElements; + closedNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the connected components, considering only the elements in the calling collection. * An array of collections is returned, with each collection representing a component. */ - components(): Collection; + components(): CollectionReturnValue[]; + } + /** + * http://js.cytoscape.org/#collection/edge-points + */ + interface EdgeSingularPoints { + /** + * Get an array of control point model positions for a {@code curve-style: bezier) or {@code curve-style: unbundled-bezier} edge. + * + * While the control points may be specified relatively in the CSS, + * this function returns the absolute model positions of the control points. + * The points are specified in the order of source-to-target direction. + * This function works for bundled beziers, but it is not applicable to the middle, straight-line edge in the bundle. + */ + controlPoints(): Position[]; + /** + * Get an array of segment point model positions (i.e. bend points) for a {@code curve-style: segments} edge. + * + * While the segment points may be specified relatively in the stylesheet, + * this function returns the absolute model positions of the segment points. + * The points are specified in the order of source-to-target direction. + */ + segmentPoints(): Position[]; + /** + * Get the model position of where the edge ends, towards the source node. + */ + sourceEndpoint(): Position; + /** + * Get the model position of where the edge ends, towards the target node. + */ + targetEndpoint(): Position; + /** + * Get the model position of the midpoint of the edge. + * + * The midpoint is, by default, where the edge’s label is centred. It is also the position towards which mid arrows point. + * For curve-style: unbundled-bezier edges, the midpoint is the middle extremum if the number of control points is odd. + * For an even number of control points, the midpoint is where the two middle-most control points meet. + * This is the middle inflection point for bilaterally symmetric or skew symmetric edges, for example. + * For curve-style: segments edges, the midpoint is the middle segment point if the number of segment points is odd. + * For an even number of segment points, the overall midpoint is the midpoint of the middle-most line segment (i.e. the mean of the middle two segment points). + */ + midpoint(): Position; } interface EdgeSingularTraversing { /** @@ -2457,7 +2711,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesWith(eles: Collection | Selector): EdgeCollection; + edgesWith(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges coming from the collection (i.e. the source) going to another collection (i.e. the target). @@ -2465,7 +2719,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesTo(eles: Collection | Selector): EdgeCollection; + edgesTo(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges connected to the nodes in the collection. @@ -2537,7 +2791,7 @@ declare namespace cytoscape { /** * The root nodes (selector or collection) to start the search from. */ - roots: Selector | Collection; + roots: Selector | CollectionArgument; /** * A handler function that is called when a node is visited in the search. */ @@ -2552,7 +2806,7 @@ declare namespace cytoscape { * The path of the search. * - The path returned includes edges such that if path[i] is a node, then path[i - 1] is the edge used to get to that node. */ - path: CollectionElements; + path: CollectionArgument; /** * The node found by the search * - If no node was found, then found is empty. @@ -2568,7 +2822,7 @@ declare namespace cytoscape { /** * The root node (selector or collection) where the algorithm starts. */ - root: Selector | Collection; + root: Selector | CollectionArgument; /** * A function that returns the positive numeric weight for this edge. @@ -2596,14 +2850,14 @@ declare namespace cytoscape { * The path starts with the source node and includes the edges between the nodes in the path such that if pathTo(node)[i] is an edge, * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] is the next node in the path. */ - pathTo(node: NodeSingular): Collection; + pathTo(node: NodeSingular): CollectionReturnValue; } /** * http://js.cytoscape.org/#eles.aStar */ interface SearchAStarOptions { - root: Selector | Collection; - goal: Selector | Collection; + root: Selector | CollectionArgument; + goal: Selector | CollectionArgument; weight?: WeightFn; heuristic?(node: NodeCollection): number; directed?: boolean; @@ -2614,7 +2868,7 @@ declare namespace cytoscape { interface SearchAStarResult { found: boolean; distance: number; - path: Collection; + path: CollectionReturnValue; } /** @@ -2641,7 +2895,7 @@ declare namespace cytoscape { * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] * is the next node in the path. */ - path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): Collection; + path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): CollectionReturnValue; } /** @@ -2670,7 +2924,7 @@ declare namespace cytoscape { * function that computes the shortest path from root node to the argument node * (either objects or selector string) */ - pathTo(node: NodeSingular | Selector): Collection; + pathTo(node: NodeSingular | Selector): CollectionReturnValue; /** * function that computes the shortest distance from root node to argument node @@ -4368,13 +4622,13 @@ declare namespace cytoscape { * Start running the layout * http://js.cytoscape.org/#layout.run */ - run(): void; - start(): void; + run(): this; + start(): this; /** * Stop running the (asynchronous/discrete) layout * http://js.cytoscape.org/#layout.stop */ - stop(): void; + stop(): this; } interface LayoutEvents { /** diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 9a2f9ae34a..9f32212f6b 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -3277,7 +3277,7 @@ declare namespace d3 { round(round: boolean): Treemap; sticky(): boolean; - sticky(sticky: boolean): boolean; + sticky(sticky: boolean): Treemap; mode(): string; mode(mode: "squarify"): Treemap; diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 2fd3f3ae45..a8f63a999e 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1432,6 +1432,11 @@ declare namespace DataTables { */ tabIndex?: number; + /** + * Enable or disable datatables responsive. Since: 1.10 + */ + responsive?: boolean | object; + //#endregion "Options" //#region "Callbacks" diff --git a/types/decompress/decompress-tests.ts b/types/decompress/decompress-tests.ts old mode 100644 new mode 100755 index 9cb8949d99..5ed96c0b46 --- a/types/decompress/decompress-tests.ts +++ b/types/decompress/decompress-tests.ts @@ -19,3 +19,24 @@ decompress('unicorn.zip', 'dist', { }).then((files: decompress.File[]) => { console.log('done!'); }); + +// Test decompress with no output to filesystem +decompress('unicorn.zip') + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with no write to filesystem`); + } + ); + +// Test decompress with DecompressOptions as second argument +decompress( + 'unicorn.zip', + { + filter: file => path.extname(file.path) !== '.exe' + } +) + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with filter options`); + } + ); diff --git a/types/decompress/index.d.ts b/types/decompress/index.d.ts old mode 100644 new mode 100755 index 745bebcd2e..2c4f464558 --- a/types/decompress/index.d.ts +++ b/types/decompress/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for decompress 4.2 // Project: https://github.com/kevva/decompress#readme // Definitions by: York Yao +// Jesse Bethke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = decompress; -declare function decompress(input: string | Buffer, output: string, opts?: decompress.DecompressOptions): Promise; +declare function decompress(input: string | Buffer, output?: string | decompress.DecompressOptions, opts?: decompress.DecompressOptions): Promise; declare namespace decompress { interface File { diff --git a/types/ember-mocha/ember-mocha-tests.ts b/types/ember-mocha/ember-mocha-tests.ts index 3516932eec..75d1154a87 100644 --- a/types/ember-mocha/ember-mocha-tests.ts +++ b/types/ember-mocha/ember-mocha-tests.ts @@ -3,7 +3,7 @@ import { setResolver, setupAcceptanceTest, setupComponentTest, setupModelTest, setupTest } from 'ember-mocha'; -import { context, describe, it, beforeEach, afterEach, before, after } from 'mocha'; +import { describe, it, beforeEach, afterEach, before, after } from 'mocha'; import chai = require('chai'); import Ember from "ember"; import hbs from 'htmlbars-inline-precompile'; diff --git a/types/ember-mocha/index.d.ts b/types/ember-mocha/index.d.ts index 1d24564e31..84510eee38 100644 --- a/types/ember-mocha/index.d.ts +++ b/types/ember-mocha/index.d.ts @@ -60,6 +60,5 @@ declare module 'ember-mocha' { declare module 'mocha' { // augment test callback context - interface ITestCallbackContext extends TestContext {} - interface IHookCallbackContext extends TestContext {} + interface Context extends TestContext {} } diff --git a/types/ethereumjs-util/index.d.ts b/types/ethereumjs-util/index.d.ts index eb47d3a6a9..c5ae356f5b 100644 --- a/types/ethereumjs-util/index.d.ts +++ b/types/ethereumjs-util/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for ethereumjs-util 5.1 +// Type definitions for ethereumjs-util 5.2 // Project: https://github.com/ethereumjs/ethereumjs-util#readme // Definitions by: Juan J. Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -// TODO: import types for [`BN`](https://github.com/indutny/bn.js) -// TODO: MAX_INTEGER as type of BN // TODO: import types for [`rlp`](https://github.com/ethereumjs/rlp) // TODO: import types for [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) +import BN = require("bn.js"); + export const SHA3_NULL_S: string; export const SHA3_RLP_ARRAY_S: string; @@ -18,13 +18,11 @@ export const SHA3_RLP_S: string; export function addHexPrefix(str: string): string; -export function arrayContainsArray(superset: any, subset: any, some: any): any; - -export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[]; +export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[] | null; export function bufferToHex(buf: Buffer | Uint8Array): string; -export function bufferToInt(buf: Buffer | Uint8Array): string; +export function bufferToInt(buf: Buffer | Uint8Array): number; export function defineProperties(self: {[k: string]: any}, fields: string[], data: {[k: string]: any}): {[k: string]: any}; @@ -34,14 +32,16 @@ export function ecsign(msgHash: Buffer | Uint8Array, privateKey: Buffer | Uint8A export function fromRpcSig(sig: string): {[k: string]: any}; -export function fromSigned(num: Buffer | Uint8Array): any; +export function fromSigned(num: Buffer | Uint8Array): BN; export function generateAddress(from: Buffer | Uint8Array, nonce: Buffer | Uint8Array): Buffer | Uint8Array; -export function hashPersonalMessage(message: string): Buffer | Uint8Array; +export function hashPersonalMessage(message: Buffer | Uint8Array | any[]): Buffer | Uint8Array; export function importPublic(publicKey: Buffer | Uint8Array): Buffer | Uint8Array; +export function isPrecompiled(address: Buffer | Uint8Array): boolean; + export function isValidAddress(address: string): boolean; export function isValidChecksumAddress(address: Buffer | Uint8Array): boolean; @@ -52,11 +52,17 @@ export function isValidPublic(publicKey: Buffer | Uint8Array, sanitize?: boolean export function isValidSignature(v: Buffer | Uint8Array, r: Buffer | Uint8Array, s: Buffer | Uint8Array, homestead?: boolean): boolean; +export function isZeroAddress(address: string): boolean; + +export function keccak(a: Buffer | Uint8Array | any[] | string | number, bits?: number): Buffer | Uint8Array; + +export function keccak256(a: Buffer | Uint8Array | any[] | string | number): Buffer | Uint8Array; + export function privateToAddress(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; export function privateToPublic(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; -export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize: boolean): Buffer | Uint8Array; +export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize?: boolean): Buffer | Uint8Array; export function ripemd160(a: Buffer | Uint8Array | any[] | string | number, padded: boolean): Buffer | Uint8Array; @@ -76,8 +82,10 @@ export function toChecksumAddress(address: string): string; export function toRpcSig(v: number, r: Buffer | Uint8Array, s: Buffer | Uint8Array): string; -export function toUnsigned(num: any): Buffer | Uint8Array; +export function toUnsigned(num: BN): Buffer | Uint8Array; export function unpad(a: T): T; export function zeros(bytes: number): Buffer | Uint8Array; + +export function zeroAddress(): string; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e556e5255a..048d7b884d 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -7,6 +7,7 @@ // Fernando Helwanger // Umidbek Karimov // Moshe Feuchtwanger +// Michael Prokopchuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -1390,12 +1391,24 @@ export namespace Font { } // #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + /** - * GLView + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. */ export interface GLViewProps extends ViewProps { - onContextCreate(): void; - msaaSamples: number; + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; } export class GLView extends Component { } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts index 62d497eb4f..d879d30091 100644 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -82,6 +82,10 @@ declare namespace GoogleAppsScript { * Sets the URL to navigate to when the action is activated. */ setOpenLink(openLink: OpenLink): ActionResponseBuilder; + /** + * Sets a flag to indicate that this action changed the existing data state. + */ + setStateChanged(stateChanged: boolean): ActionResponseBuilder; } export interface AuthorizationAction { diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 3858cab780..6e67a5b592 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -32,6 +32,11 @@ export interface IFrameOptions { * CSS margin attribute, for example '8px 3em'. A number value is converted into px. */ bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; /** * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. * If your iFrame navigates between different domains, ports or protocols; then you will need to diff --git a/types/ion-rangeslider/index.d.ts b/types/ion-rangeslider/index.d.ts new file mode 100644 index 0000000000..9788741b77 --- /dev/null +++ b/types/ion-rangeslider/index.d.ts @@ -0,0 +1,81 @@ +// Type definitions for ion-rangeslider 2.2 +// Project: https://github.com/IonDen/ion.rangeSlider/ +// Definitions by: Karel van de Plassche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html +// Parsed using https://github.com/Karel-van-de-Plassche/ion-rangeslider-parser.git +// Based on global-modifying module template file + +declare global { + interface JQuery { + destroy(): void; + ionRangeSlider(options?: IonRangeSliderOptions): JQuery; + reset(): void; + update(option: IonRangeSliderOptions): void; + } +} + +export interface IonRangeSliderOptions { + type?: string; // Choose slider type, could be `single` - for one handle, or `double` for two handles [Default: single] + min?: number; // Set slider minimum value [Default: 10] + max?: number; // Set slider maximum value [Default: 100] + from?: number; // Set start position for left handle (or for single handle) [Default: min] + to?: number; // Set start position for right handle [Default: max] + step?: number; // Set sliders step. Always > 0. Could be fractional [Default: 1] + min_interval?: number; // Set minimum diapason between sliders. Only for **double** type [Default: -] + max_interval?: number; // Set minimum maximum between sliders. Only for **double** type [Default: -] + drag_interval?: boolean; // Allow user to drag whole range. Only for **double** type [Default: false] + values?: any[]; // Set up your own array of possible slider values. They could be numbers or strings. If the values array is set up, min, max and step param, can no longer be changed [Default: []] + from_fixed?: boolean; // Fix position of left (or single) handle [Default: false] + from_min?: number; // Set minimum limit for left (or single) handle [Default: min] + from_max?: number; // Set maximum limit for left (or single) handle [Default: max] + from_shadow?: boolean; // Highlight the limits for left handle [Default: false] + to_fixed?: boolean; // Fix position of right handle [Default: false] + to_min?: number; // Set minimum limit for right handle [Default: min] + to_max?: number; // Set maximum limit for right handle [Default: max] + to_shadow?: boolean; // Highlight the right handle [Default: false] + prettify_enabled?: boolean; // Improve readability of long numbers: 10000000 → 10 000 000 [Default: true] + prettify_separator?: string; // Set up your own separator for long numbers: 10000000 → 10,000,000 etc. [Default: ] + prettify?: (num: number) => string; // Set up your own prettify function. Can be anything. For example, you can set up unix time as slider values and than transform them to cool looking dates [Default: null] + force_edges?: boolean; // Sliders handles and tooltips will be always inside it's container [Default: false] + keyboard?: boolean; // Activates keyboard controls. Move left: ←, ↓, A, S. Move right: →, ↑, W, D. [Default: true] + grid?: boolean; // Enables grid of values above the slider [Default: true] + grid_margin?: boolean; // Set left and right grid gaps [Default: true] + grid_num?: number; // Number of grid units [Default: 4] + grid_snap?: boolean; // Snap grid to sliders step (step param). If activated, grid_num will not be used. Max steps = 50 [Default: false] + hide_min_max?: boolean; // Hides **min** and **max** labels [Default: false] + hide_from_to?: boolean; // Hides **from** and **to** labels [Default: false] + prefix?: string; // Set prefix for values. Will be set up right before the number: **$**100 [Default: ] + postfix?: string; // Set postfix for values. Will be set up right after the number: 100**k** [Default: ] + max_postfix?: string; // Special postfix, used only for maximum value. Will be showed after handle will reach maximum right position. For example **0 — 100+** [Default: ] + decorate_both?: boolean; // Used for **double** type and only if prefix or postfix was set up. Determine how to decorate close values. For example: **$10k — $100k** or **$10 — 100k** [Default: true] + values_separator?: string; // Set your own separator for close values. Used for **double** type. Default: **10 — 100**. Or you may set: **10 to 100, 10 + 100, 10 → 100** etc. [Default: - ] + input_values_separator?: string; // Separator for **double** values in input value property. ` [Default: ; ] + disable?: boolean; // Locks slider and makes it inactive. Input is disabled too. Invisible to forms [Default: false] + block?: boolean; // Locks slider and makes it inactive. Input is NOT disabled. Can be send with forms [Default: false] + extra_classes?: string; // Traverse extra CSS-classes to sliders container [Default: —] + scope?: any; // Scope for callbacks. Pass any object [Default: null] + onStart?: (obj: IonRangeSliderEvent) => void; // Callback. Is called on slider start. Gets all slider data as a 1st attribute [Default: null] + onChange?: (obj: IonRangeSliderEvent) => void; // Callback. IS called on each values change. Gets all slider data as a 1st attribute [Default: null] + onFinish?: (obj: IonRangeSliderEvent) => void; // Callback. Is called when user releases handle. Gets all slider data as a 1st attribute [Default: null] + onUpdate?: (obj: IonRangeSliderEvent) => void; // Callback. Is called when slider is modified by external methods `update` or `reset [Default: null] +} + +export interface IonRangeSliderEvent { + input: JQuery; // jQuery-link to input + slider: JQuery; // jQuery-link to sliders container + min: number; // MIN value + max: number; // MAX values + from: number; // FROM value + from_percent: number; // FROM value in percents + from_value: number; // FROM index in values array (if used) + to: number; // TO value + to_percent: number; // TO value in percents + to_value: number; // TO index in values array (if used) + min_pretty: string; // MIN prettified (if used) + max_pretty: string; // MAX prettified (if used) + from_pretty: string; // FROM prettified (if used) + to_pretty: string; // TO prettified (if used) +} diff --git a/types/ion.rangeslider/ion.rangeslider-tests.ts b/types/ion-rangeslider/ion-rangeslider-tests.ts similarity index 67% rename from types/ion.rangeslider/ion.rangeslider-tests.ts rename to types/ion-rangeslider/ion-rangeslider-tests.ts index e60287feb3..e3bffdd4b6 100644 --- a/types/ion.rangeslider/ion.rangeslider-tests.ts +++ b/types/ion-rangeslider/ion-rangeslider-tests.ts @@ -1,6 +1,5 @@ /// - -var sliderInputElement = $(''); +let sliderInputElement = $(''); sliderInputElement.ionRangeSlider({ decorate_both: true, disable: false, @@ -18,29 +17,18 @@ sliderInputElement.ionRangeSlider({ hide_from_to: false, hide_min_max: false, keyboard: true, - keyboard_step: 1, max: 100, max_interval: 5, max_postfix: "+", min: 10, min_interval: 5, - onChange: function (obj) { - console.log(obj); - }, - onFinish: function (obj) { - console.log(obj); - }, - onStart: function (obj) { - console.log(obj); - }, - onUpdate: function (obj) { - console.log(obj); - }, + onChange: obj => console.log(obj), + onFinish: obj => console.log(obj), + onStart: obj => console.log(obj), + onUpdate: obj => console.log(obj), postfix: ".00", prefix: "$", - prettify: function(num) { - return String(num); - }, + prettify: (num: number) => (String(num)), prettify_enabled: true, prettify_separator: ",", step: 10, @@ -48,8 +36,7 @@ sliderInputElement.ionRangeSlider({ to_fixed: false, to_max: 100, to_min: 60, - to_shadowed: false, - type: "double", + type: "double", values: ["a", "b", "c"], values_separator: "," }); diff --git a/types/ion-rangeslider/tsconfig.json b/types/ion-rangeslider/tsconfig.json new file mode 100644 index 0000000000..2c77a196bd --- /dev/null +++ b/types/ion-rangeslider/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ion-rangeslider-tests.ts" + ], + "exclude": [ + "util/**/*", + ".gitignore" + ] +} diff --git a/types/ion-rangeslider/tslint.json b/types/ion-rangeslider/tslint.json new file mode 100644 index 0000000000..64aace11d6 --- /dev/null +++ b/types/ion-rangeslider/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": false + } +} diff --git a/types/ion.rangeslider/v1/index.d.ts b/types/ion-rangeslider/v1/index.d.ts similarity index 91% rename from types/ion.rangeslider/v1/index.d.ts rename to types/ion-rangeslider/v1/index.d.ts index d819f46964..2ce88db6d4 100644 --- a/types/ion.rangeslider/v1/index.d.ts +++ b/types/ion-rangeslider/v1/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for for Ion.RangeSlider 1.9.1 +// Type definitions for ion-rangeslider 1.9 // Project: https://github.com/IonDen/ion.rangeSlider/ // Definitions by: Douglas Eichelberger +// Karel van de Plassche // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/ion.rangeslider/v1/ion.rangeslider-tests.ts b/types/ion-rangeslider/v1/ion-rangeslider-tests.ts similarity index 100% rename from types/ion.rangeslider/v1/ion.rangeslider-tests.ts rename to types/ion-rangeslider/v1/ion-rangeslider-tests.ts diff --git a/types/ion.rangeslider/v1/tsconfig.json b/types/ion-rangeslider/v1/tsconfig.json similarity index 83% rename from types/ion.rangeslider/v1/tsconfig.json rename to types/ion-rangeslider/v1/tsconfig.json index c63da8c0e1..32d3577e6f 100644 --- a/types/ion.rangeslider/v1/tsconfig.json +++ b/types/ion-rangeslider/v1/tsconfig.json @@ -15,8 +15,8 @@ ], "types": [], "paths": { - "ion.rangeslider": [ - "ion.rangeslider/v1" + "ion-rangeslider": [ + "ion-rangeslider/v1" ] }, "noEmit": true, @@ -24,6 +24,6 @@ }, "files": [ "index.d.ts", - "ion.rangeslider-tests.ts" + "ion-rangeslider-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/ion.rangeslider/tslint.json b/types/ion-rangeslider/v1/tslint.json similarity index 100% rename from types/ion.rangeslider/tslint.json rename to types/ion-rangeslider/v1/tslint.json diff --git a/types/ion.rangeslider/index.d.ts b/types/ion.rangeslider/index.d.ts deleted file mode 100644 index 21d99c5c6d..0000000000 --- a/types/ion.rangeslider/index.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Type definitions for for Ion.RangeSlider 2.0.2 -// Project: https://github.com/IonDen/ion.rangeSlider/ -// Definitions by: Sixin Li -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html - -interface JQuery { - destroy(): void; - ionRangeSlider(): JQuery; - ionRangeSlider(options: IonRangeSliderOptions): JQuery; - reset(): void; - update(option: IonRangeSliderOptions): void; -} - -interface IonRangeSliderOptions { - decorate_both?: boolean; - disable?: boolean; - drag_interval?: boolean; - force_edges?: boolean; - from?: number; - from_fixed?: boolean; - from_max?: number; - from_min?: number; - from_shadow?: boolean; - grid?: boolean; - grid_margin?: boolean; - grid_num?: number; - grid_snap?: boolean; - hide_from_to?: boolean; - hide_min_max?: boolean; - keyboard?: boolean; - keyboard_step?: number; - max?: number; - max_interval?: number; - max_postfix?: string; - min?: number; - min_interval?: number; - onChange?: (obj: IonRangeSliderEvent) => void; - onFinish?: (obj: IonRangeSliderEvent) => void; - onStart?: (obj: IonRangeSliderEvent) => void; - onUpdate?: (obj: IonRangeSliderEvent) => void; - postfix?: string; - prefix?: string; - prettify?: (num: number) => string; - prettify_enabled?: boolean; - prettify_separator?: string; - step?: number; - to?: number; - to_fixed?: boolean; - to_max?: number; - to_min?: number; - to_shadowed?: boolean; - type?: string; - values?: any[]; - values_separator?: string; -} - -interface IonRangeSliderEvent { - from: number; - from_precent: number; - from_value: any; - input: JQuery; - max: number; - min: number; - slider: JQuery; - to: number; - to_precent: number; - to_value: any; -} diff --git a/types/istanbul-lib-instrument/index.d.ts b/types/istanbul-lib-instrument/index.d.ts index e1d4e813f9..1b749a893c 100644 --- a/types/istanbul-lib-instrument/index.d.ts +++ b/types/istanbul-lib-instrument/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/istanbuljs/istanbuljs // Definitions by: Jason Cheatham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import { FileCoverage, FileCoverageData, Range } from 'istanbul-lib-coverage'; import { RawSourceMap } from 'source-map'; diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index fd602b18d9..4a2153b218 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 23.0 +// Type definitions for Jest 23.1 // Project: http://facebook.github.io/jest/ // Definitions by: Asana // Ivo Stratev @@ -10,10 +10,11 @@ // Waseem Dahman // Jamie Mason // Douglas Duteil -// Ahn +// Ahn // Josh Goldberg -// Bradley Ayers +// Jeff Lau // Andrew Makarov +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -358,10 +359,22 @@ declare namespace jest { } interface Matchers { + /** + * Ensures the last call to a mock function was provided specific args. + */ + lastCalledWith(...args: any[]): R; + /** + * Ensure that the last call to a mock function has returned a specified value. + */ + lastReturnedWith(value: any): R; /** * If you know how to test something, `.not` lets you test its opposite. */ not: Matchers; + /** + * Ensure that the nth call to a mock function has returned a specified value. + */ + nthReturnedWith(n: number, value: any): R; /** * Use resolves to unwrap the value of a fulfilled promise so any other * matcher can be chained. If the promise is rejected the assertion fails. @@ -372,7 +385,6 @@ declare namespace jest { * If the promise is fulfilled the assertion fails. */ rejects: Matchers>; - lastCalledWith(...args: any[]): R; /** * Checks that a value is what you expect. It uses `===` to check strict equality. * Don't use `toBe` with floating-point numbers. @@ -469,22 +481,46 @@ declare namespace jest { * Ensure that a mock function is called with specific arguments. */ toHaveBeenCalledWith(...params: any[]): R; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + */ + toHaveBeenNthCalledWith(nthCall: number, ...params: any[]): R; /** * If you have a mock function, you can use `.toHaveBeenLastCalledWith` * to test what arguments it was last called with. */ toHaveBeenLastCalledWith(...params: any[]): R; /** - * If you have a mock function, you can use `.toHaveBeenNthCalledWith` - * to test what arguments it was nth called with. + * Use to test the specific value that a mock function last returned. + * If the last call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. */ - toHaveBeenNthCalledWith(nthCall: number, ...params: any[]): R; + toHaveLastReturnedWith(expected: any): R; /** * Used to check that an object has a `.length` property * and it is set to a certain numeric value. */ toHaveLength(expected: number): R; + /** + * Use to test the specific value that a mock function returned for the nth call. + * If the nth call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + */ + toHaveNthReturnedWith(nthCall: number, expected: any): R; toHaveProperty(propertyPath: string | any[], value?: any): R; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + */ + toHaveReturned(): R; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + */ + toHaveReturnedTimes(expected: number): R; + /** + * Use to ensure that a mock function returned a specific value. + */ + toHaveReturnedWith(expected: any): R; /** * Check that a string matches a regular expression. */ @@ -498,6 +534,22 @@ declare namespace jest { * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ toMatchSnapshot(snapshotName?: string): R; + /** + * Ensure that a mock function has returned (as opposed to thrown) at least once. + */ + toReturn(): R; + /** + * Ensure that a mock function has returned (as opposed to thrown) a specified number of times. + */ + toReturnTimes(count: number): R; + /** + * Ensure that a mock function has returned a specified value at least once. + */ + toReturnWith(value: any): R; + /** + * Use to test that objects have the same types as well as structure. + */ + toStrictEqual(expected: {}): R; /** * Used to test that a function throws when it is called. */ @@ -556,9 +608,29 @@ declare namespace jest { mockRejectedValueOnce(value: any): Mock; } + /** + * Represents the result of a single call to a mock function. + */ + interface MockResult { + /** + * True if the function threw. + * False if the function returned. + */ + isThrow: boolean; + /** + * The value that was either thrown or returned by the function. + */ + value: any; + } + interface MockContext { calls: any[][]; instances: T[]; + invocationCallOrder: number[]; + /** + * List of results of calls to the mock function. + */ + results: MockResult[]; } } @@ -801,6 +873,164 @@ declare namespace jest { type SnapshotUpdateState = 'all' | 'new' | 'none'; + interface DefaultOptions { + automock: boolean; + bail: boolean; + browser: boolean; + cache: boolean; + cacheDirectory: Path; + changedFilesWithAncestor: boolean; + clearMocks: boolean; + collectCoverage: boolean; + collectCoverageFrom: Maybe; + coverageDirectory: Maybe; + coveragePathIgnorePatterns: string[]; + coverageReporters: string[]; + coverageThreshold: Maybe<{global: {[key: string]: number}}>; + errorOnDeprecated: boolean; + expand: boolean; + filter: Maybe; + forceCoverageMatch: Glob[]; + globals: ConfigGlobals; + globalSetup: Maybe; + globalTeardown: Maybe; + haste: HasteConfig; + detectLeaks: boolean; + detectOpenHandles: boolean; + moduleDirectories: string[]; + moduleFileExtensions: string[]; + moduleNameMapper: {[key: string]: string}; + modulePathIgnorePatterns: string[]; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + preset: Maybe; + projects: Maybe>; + resetMocks: boolean; + resetModules: boolean; + resolver: Maybe; + restoreMocks: boolean; + rootDir: Maybe; + roots: Maybe; + runner: string; + runTestsByPath: boolean; + setupFiles: Path[]; + setupTestFrameworkScriptFile: Maybe; + skipFilter: boolean; + snapshotSerializers: Path[]; + testEnvironment: string; + testEnvironmentOptions: object; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string; + testResultsProcessor: Maybe; + testRunner: Maybe; + testURL: string; + timers: 'real' | 'fake'; + transform: Maybe<{[key: string]: string}>; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; + useStderr: boolean; + verbose: Maybe; + watch: boolean; + watchman: boolean; + } + + interface InitialOptions { + automock?: boolean; + bail?: boolean; + browser?: boolean; + cache?: boolean; + cacheDirectory?: Path; + clearMocks?: boolean; + changedFilesWithAncestor?: boolean; + changedSince?: string; + collectCoverage?: boolean; + collectCoverageFrom?: Glob[]; + collectCoverageOnlyFrom?: {[key: string]: boolean}; + coverageDirectory?: string; + coveragePathIgnorePatterns?: string[]; + coverageReporters?: string[]; + coverageThreshold?: {global: {[key: string]: number}}; + detectLeaks?: boolean; + detectOpenHandles?: boolean; + displayName?: string; + expand?: boolean; + filter?: Path; + findRelatedTests?: boolean; + forceCoverageMatch?: Glob[]; + forceExit?: boolean; + json?: boolean; + globals?: ConfigGlobals; + globalSetup?: Maybe; + globalTeardown?: Maybe; + haste?: HasteConfig; + reporters?: Array; + logHeapUsage?: boolean; + lastCommit?: boolean; + listTests?: boolean; + mapCoverage?: boolean; + moduleDirectories?: string[]; + moduleFileExtensions?: string[]; + moduleLoader?: Path; + moduleNameMapper?: {[key: string]: string}; + modulePathIgnorePatterns?: string[]; + modulePaths?: string[]; + name?: string; + noStackTrace?: boolean; + notify?: boolean; + notifyMode?: string; + onlyChanged?: boolean; + outputFile?: Path; + passWithNoTests?: boolean; + preprocessorIgnorePatterns?: Glob[]; + preset?: Maybe; + projects?: Glob[]; + replname?: Maybe; + resetMocks?: boolean; + resetModules?: boolean; + resolver?: Maybe; + restoreMocks?: boolean; + rootDir?: Path; + roots?: Path[]; + runner?: string; + runTestsByPath?: boolean; + scriptPreprocessor?: string; + setupFiles?: Path[]; + setupTestFrameworkScriptFile?: Path; + silent?: boolean; + skipFilter?: boolean; + skipNodeResolution?: boolean; + snapshotSerializers?: Path[]; + errorOnDeprecated?: boolean; + testEnvironment?: string; + testEnvironmentOptions?: object; + testFailureExitCode?: string | number; + testLocationInResults?: boolean; + testMatch?: Glob[]; + testNamePattern?: string; + testPathDirs?: Path[]; + testPathIgnorePatterns?: string[]; + testRegex?: string; + testResultsProcessor?: Maybe; + testRunner?: string; + testURL?: string; + timers?: 'real' | 'fake'; + transform?: {[key: string]: string}; + transformIgnorePatterns?: Glob[]; + watchPathIgnorePatterns?: string[]; + unmockedModulePathPatterns?: string[]; + updateSnapshot?: boolean; + useStderr?: boolean; + verbose?: Maybe; + watch?: boolean; + watchAll?: boolean; + watchman?: boolean; + watchPlugins?: string[]; + } + interface GlobalConfig { bail: boolean; collectCoverage: boolean; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 09e9ecef99..cc86e7d577 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -213,6 +213,9 @@ describe('Assymetric matchers', () => { greeting: expect.stringContaining('hello'), }); + expect("foo").toStrictEqual("foo"); + expect({ a: "foo" }).toStrictEqual({ a: "foo" }); + const callback = jest.fn(); expect(callback).toEqual(expect.any(Function)); callback(5, "test"); @@ -254,6 +257,26 @@ describe('setTimeout', () => { }); }); +describe("spy call matchers", () => { + const spy = jest.fn(); + + expect(spy).lastReturnedWith("foo"); + expect(spy).nthReturnedWith(3, "foo"); + expect(spy).toHaveBeenCalled(); + expect(spy).toHaveBeenCalledTimes(7); + expect(spy).toHaveBeenCalledWith("foo"); + expect(spy).toHaveBeenLastCalledWith("foo"); + expect(spy).toHaveBeenNthCalledWith(3, "foo"); + expect(spy).toHaveReturned(); + expect(spy).toHaveReturnedTimes(7); + expect(spy).toHaveReturnedWith("foo"); + expect(spy).toHaveLastReturnedWith("foo"); + expect(spy).toHaveNthReturnedWith(3, "foo"); + expect(spy).toReturn(); + expect(spy).toReturnTimes(3); + expect(spy).toReturnWith("foo"); +}); + describe('Extending extend', () => { it('works', () => { expect.extend({ @@ -737,3 +760,25 @@ describe('toHaveBeenNthCalledWith', () => { expect(fn).toHaveBeenNthCalledWith(3, "foo"); }); + +// Jest config +{ +interface JestConfigModule {defaults: jest.DefaultOptions; } +// tslint:disable-next-line:no-var-requires +const {defaults} = require('jest-config') as JestConfigModule; + +const config: jest.InitialOptions = { + transform: { + '^.+\\.(ts|tsx)$': 'ts-jest' + }, + testMatch: [ + ...defaults.testMatch, + '**/__tests__/**/*.ts?(x)', + '**/?(*.)+(spec|test).ts?(x)' + ], + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + globals: { + 'ts-jest': {} + } +}; +} diff --git a/types/jquery-mockjax/index.d.ts b/types/jquery-mockjax/index.d.ts index 54cc036416..f1333b1028 100644 --- a/types/jquery-mockjax/index.d.ts +++ b/types/jquery-mockjax/index.d.ts @@ -1,11 +1,28 @@ -// Type definitions for jQuery Mockjax 2.0.1 +// Type definitions for jQuery Mockjax 2.3.0 // Project: https://github.com/jakerella/jquery-mockjax -// Definitions by: Laszlo Jakab , Vladimir Đokić +// Definitions by: +// Laszlo Jakab , +// Vladimir Đokić , +// James Johnson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +type MockJaxLoggingFunction = (message?: any, ...additionalParameters: any[]) => void; + +interface MockJaxStandardLogger { + error?: MockJaxLoggingFunction; + warn?: MockJaxLoggingFunction; + info?: MockJaxLoggingFunction; + log?: MockJaxLoggingFunction; + debug?: MockJaxLoggingFunction; +} + +interface MockJaxCustomLogger { + [key: string]: MockJaxLoggingFunction; +} + interface MockJaxSettingsHeaders { [key: string]: string; } @@ -33,15 +50,22 @@ interface MockJaxSettings { onAfterSuccess?: Function; onAfterError?: Function; onAfterComplete?: Function; + logger?: MockJaxStandardLogger | MockJaxCustomLogger; + logLevelMethods?: string[]; + namespace?: string; + throwUnmocked?: boolean; + retainAjaxCalls?: boolean; } interface MockJaxStatic { (options: MockJaxSettings): number; + (options: MockJaxSettings[]): number[]; handler(id?: number): any; clear(id?: number): void; mockedAjaxCalls(): any[]; unfiredHandlers(): any[]; unmockedAjaxCalls(): any[]; + clearRetainedAjaxCalls(): void; } interface JQueryStatic { diff --git a/types/jquery-mockjax/jquery-mockjax-tests.ts b/types/jquery-mockjax/jquery-mockjax-tests.ts index 3090a1c3cc..31babd9cd8 100644 --- a/types/jquery-mockjax/jquery-mockjax-tests.ts +++ b/types/jquery-mockjax/jquery-mockjax-tests.ts @@ -192,6 +192,81 @@ class Tests { } }); }); + + t('Standard logger type gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + error: logFunction, + warn: logFunction, + info: logFunction, + log: logFunction, + debug: logFunction + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Standard logger was called'); + done(); + } + }); + }); + + t('Custom logger object gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + customName: logFunction + }, + logLevelMethods: ['customName', 'customName', 'customName', 'customName', 'customName'] + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Custom logger was called'); + done(); + } + }); + }); + + t('Throws when ajax call is not mocked', (assert) => { + let done = assert.async(); + + $.mockjaxSettings.throwUnmocked = true; + + $.ajax({ + url: '/unmocked-ajax-call', + error: (error) => { + assert.ok(error, 'Expected the call to fail because it was not mocked'); + done(); + }, + complete: (xhr) => { + assert.ok(false, 'Expected a failure'); + done(); + } + }); + }); } } diff --git a/types/karma-chai/index.d.ts b/types/karma-chai/index.d.ts index 87910cb6e2..15c7010071 100644 --- a/types/karma-chai/index.d.ts +++ b/types/karma-chai/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for karma-chai 0.1 // Project: http://xdissent.github.io/karma-chai -// Definitions by: Jay Sherby +// Definitions by: JayAndCatchFire // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import chai = require('chai'); diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index d90ba90b13..94623c5abb 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -208,6 +208,7 @@ declare module 'luxon' { toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; toObject(options?: { includeConfig?: boolean }): DateObject; + toMillis(): number; toRFC2822(): string; toSQL(options?: Object): string; toSQLDate(): string; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index ce9d09ac8f..4396e8d7a2 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -54,6 +54,8 @@ DateTime.utc(); DateTime.local().toUTC(); DateTime.utc().toLocal(); +DateTime.fromMillis(1527780819458).toMillis(); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index cdecc3e1b4..886e6da20e 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -36,6 +36,7 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers version: string; expression: MathNode; + json: MathJsJson; config: (options: any) => void; @@ -543,7 +544,7 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers /** * Create a number or convert a string, boolean, or unit to a number. When value is a matrix, all elements will be converted to number. */ - number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber): number|MathArray|Matrix; + number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber|Fraction): number|MathArray|Matrix; number(unit: Unit, valuelessUnit: Unit|string): number|MathArray|Matrix; /** @@ -2249,4 +2250,11 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers valueOf(): any; toString(): string; } + + interface MathJsJson { + /** + * Returns reviver function that can be used as reviver in JSON.parse function. + */ + reviver(): (key: any, value: any) => any; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 6cf43dc698..09202e0599 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -365,3 +365,15 @@ Expression tree examples } }); } + +/* +JSON serialization/deserialization +*/ +{ + const data = { + bigNumber: math.bignumber('1.5') + }; + const stringified = JSON.stringify(data); + const parsed = JSON.parse(stringified, math.json.reviver); + parsed.bigNumber === math.bignumber('1.5'); // true +} diff --git a/types/meteor/meteor-tests.ts b/types/meteor/meteor-tests.ts index f9cf039c84..a321e4a409 100644 --- a/types/meteor/meteor-tests.ts +++ b/types/meteor/meteor-tests.ts @@ -781,3 +781,8 @@ DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); DDPRateLimiter.addRule({ userId: userId => userId == 'foo' }, 5, 1000); Template.instance().autorun(() => { }).stop(); + +// Mongo Collection without connection (local collection) +const collectionWithoutConnection = new Mongo.Collection("monkey", { + connection: null +}); diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 248f5a22af..771d24edc1 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -124,7 +124,7 @@ declare module Mongo { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; @@ -348,7 +348,7 @@ declare module "meteor/mongo" { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; diff --git a/types/mocha/UNUSED_FILES.txt b/types/mocha/UNUSED_FILES.txt deleted file mode 100644 index 2c70329a00..0000000000 --- a/types/mocha/UNUSED_FILES.txt +++ /dev/null @@ -1,2 +0,0 @@ -mocha-node.d.ts -mocha-node-tests.ts \ No newline at end of file diff --git a/types/mocha/index.d.ts b/types/mocha/index.d.ts index 2dd6bb2c21..1ada77c0a4 100644 --- a/types/mocha/index.d.ts +++ b/types/mocha/index.d.ts @@ -9,261 +9,2146 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 +export = Mocha; +export as namespace Mocha; + /** - * Mocha is using node.js EventEmitter for its internal classes - * But when it's executed in the browser environment it bundles a 3rd party EventEmitter in its code - * Also node.js EventEmitter brings its globals which cannot be used in the browser environment. - * So it's unsafe to reference node EventEmitter here, that's why we have a generic interface for EventEmitter. + * Mocha API * - * @see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/25117#issuecomment-383404187 + * @see https://mochajs.org/api/mocha */ -declare class GenericEventEmitter { - addListener(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - on(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - once(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - removeListener(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - removeAllListeners(event?: string): GenericEventEmitter; - emit(event: string, ...args: any[]): boolean; - } +declare class Mocha { + private _growl; + private _reporter; + private _ui; - interface MochaSetupOptions { - // milliseconds to wait before considering a test slow - slow?: number; + constructor(options?: Mocha.MochaOptions); - // timeout in milliseconds - timeout?: number; - - // ui name "bdd", "tdd", "exports" etc - ui?: Mocha.Interface; - - // array of accepted globals - globals?: any[]; - - // reporter instance (function or string), defaults to `mocha.reporters.Spec` - reporter?: string | ReporterConstructor; - - // bail on the first test failure - bail?: boolean; - - // ignore global leaks - ignoreLeaks?: boolean; - - // grep string or regexp to filter tests with - grep?: any; - - // require modules before running tests - require?: string[]; - - asyncOnly?: boolean; - delay?: boolean; - files?: string[]; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; - } - - declare const mocha: Mocha; - declare const describe: Mocha.IContextDefinition; - declare const xdescribe: Mocha.IContextDefinition; - // alias for `describe` - declare const context: Mocha.IContextDefinition; - // alias for `describe` - declare const suite: Mocha.IContextDefinition; - declare const it: Mocha.ITestDefinition; - declare const xit: Mocha.ITestDefinition; - // alias for `it` - declare const test: Mocha.ITestDefinition; - declare const specify: Mocha.ITestDefinition; - - // Used with the --delay flag; see https://mochajs.org/#hooks - declare function run(): void; - - type MochaDone = (error?: any) => void; - - declare function setup(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function teardown(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function suiteSetup(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function suiteTeardown(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function before(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function before(description: string, callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function after(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function after(description: string, callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function beforeEach(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function beforeEach(description: string, callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function afterEach(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function afterEach(description: string, callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - - interface ReporterConstructor { - new(runner: Mocha.IRunner, options: any): any; - } - - declare class Mocha { - currentTest: Mocha.ITestDefinition; - suite: Mocha.ISuite; + suite: Mocha.Suite; files: string[]; - options: MochaSetupOptions; + options: Mocha.MochaInstanceOptions; - constructor(options?: MochaSetupOptions); - - asyncOnly(): Mocha; - asyncOnly(value: boolean): Mocha; - delay(): Mocha; - forbidOnly(): Mocha; - forbidPending(): Mocha; - fullTrace(): Mocha; - /** Setup mocha with the given interface. */ - setup(interface: Mocha.Interface): Mocha; - bail(value?: boolean): Mocha; - addFile(file: string): Mocha; - /** Sets reporter by name, defaults to "spec". */ - reporter(name: string, reporterOptions?: any): Mocha; - /** Sets reporter constructor, defaults to mocha.reporters.Spec. */ - reporter(reporter: ReporterConstructor, reporterOptions?: any): Mocha; - ui(value: string): Mocha; - grep(value: string): Mocha; - grep(value: RegExp): Mocha; - invert(): Mocha; - ignoreLeaks(value: boolean): Mocha; - checkLeaks(): Mocha; /** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. + * Enable or disable bailing on the first failure. + * + * @see https://mochajs.org/api/mocha#bail */ - throwError(error: Error): void; - /** Enables growl support. */ - growl(): Mocha; - globals(value: string): Mocha; - globals(values: string[]): Mocha; - useColors(value: boolean): Mocha; - useInlineDiffs(value: boolean): Mocha; - timeout(value: number): Mocha; - slow(value: number): Mocha; - enableTimeouts(value: boolean): Mocha; - noHighlighting(value: boolean): Mocha; - /** Runs tests and invokes `onComplete()` when finished. */ - run(onComplete?: (failures: number) => void): Mocha.IRunner; - loadFiles(cb?: () => any): void; + bail(bail?: boolean): this; - // internals exposed via exports.* - Runnable: Mocha.Runnable; - Context: Mocha.Context; - Runner: Mocha.Runner; - Suite: Mocha.Suite; - Hook: Mocha.Hook; - Test: Mocha.Test; - } + /** + * Add test `file`. + * + * @see https://mochajs.org/api/mocha#addFile + */ + addFile(file: string): this; - // merge the Mocha class declaration with a module - declare namespace Mocha { - /** Third-party declarations that want to add new interfaces can contribute names here */ - interface InterfaceContributions { - bdd: any; - tdd: any; - qunit: any; - exports: any; + /** + * Set reporter to one of the built-in reporters. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter: Mocha.Reporter, reporterOptions?: any): this; + + /** + * Set reporter to the provided constructor, one of the built-in reporters, or loads a reporter + * from a module path. Defaults to `"spec"`. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter?: string | Mocha.ReporterConstructor, reporterOptions?: any): this; + + /** + * Set test UI to one of the built-in test interfaces. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name: Mocha.Interface): this; + + /** + * Set test UI to one of the built-in test interfaces or loads a test interface from a module + * path. Defaults to `"bdd"`. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name?: string): this; + + /** + * Escape string and add it to grep as a RegExp. + * + * @see https://mochajs.org/api/mocha#fgrep + */ + fgrep(str: string): this; + + /** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @see https://mochajs.org/api/mocha#grep + */ + grep(re: string | RegExp): this; + + /** + * Invert `.grep()` matches. + * + * @see https://mochajs.org/api/mocha#invert + */ + invert(): this; + + /** + * Ignore global leaks. + * + * @see https://mochajs.org/api/mocha#ignoreLeaks + */ + ignoreLeaks(ignore: boolean): this; + + /** + * Enable global leak checking. + * + * @see https://mochajs.org/api/mocha#checkLeaks + */ + checkLeaks(): this; + + /** + * Display long stack-trace on failing + * + * @see https://mochajs.org/api/mocha#fullTrace + */ + fullTrace(): this; + + /** + * Enable growl support. + * + * @see https://mochajs.org/api/mocha#growl + */ + growl(): this; + + /** + * Ignore `globals` array or string. + * + * @see https://mochajs.org/api/mocha#globals + */ + globals(globals: string | ReadonlyArray): this; + + /** + * Emit color output. + * + * @see https://mochajs.org/api/mocha#useColors + */ + useColors(colors: boolean): this; + + /** + * Use inline diffs rather than +/-. + * + * @see https://mochajs.org/api/mocha#useInlineDiffs + */ + useInlineDiffs(inlineDiffs: boolean): this; + + /** + * Do not show diffs at all. + * + * @see https://mochajs.org/api/mocha#hideDiff + */ + hideDiff(hideDiff: boolean): this; + + /** + * Set the timeout in milliseconds. + * + * @see https://mochajs.org/api/mocha#timeout + */ + timeout(timeout: string | number): this; + + /** + * Set the number of times to retry failed tests. + * + * @see https://mochajs.org/api/mocha#retries + */ + retries(n: number): this; + + /** + * Set slowness threshold in milliseconds. + * + * @see https://mochajs.org/api/mocha#slow + */ + slow(slow: string | number): this; + + /** + * Enable timeouts. + * + * @see https://mochajs.org/api/mocha#enableTimeouts + */ + enableTimeouts(enabled?: boolean): this; + + /** + * Makes all tests async (accepting a callback) + * + * @see https://mochajs.org/api/mocha#asyncOnly. + */ + asyncOnly(): this; + + /** + * Disable syntax highlighting (in browser). + * + * @see https://mochajs.org/api/mocha#noHighlighting + */ + noHighlighting(): this; + + /** + * Enable uncaught errors to propagate (in browser). + * + * @see https://mochajs.org/api/mocha#allowUncaught + */ + allowUncaught(): boolean; + + /** + * Delay root suite execution. + * + * @see https://mochajs.org/api/mocha#delay + */ + delay(): boolean; + + /** + * Tests marked only fail the suite + * + * @see https://mochajs.org/api/mocha#forbidOnly + */ + forbidOnly(): boolean; + + /** + * Pending tests and tests marked skip fail the suite + * + * @see https://mochajs.org/api/mocha#forbidPending + */ + forbidPending(): boolean; + + /** + * Run tests and invoke `fn()` when complete. + * + * Note that `run` relies on Node's `require` to execute + * the test interface functions and will be subject to the + * cache - if the files are already in the `require` cache, + * they will effectively be skipped. Therefore, to run tests + * multiple times or to run tests in files that are already + * in the `require` cache, make sure to clear them from the + * cache first in whichever manner best suits your needs. + * + * @see https://mochajs.org/api/mocha#run + */ + run(fn?: (failures: number) => void): Mocha.Runner; + + /** + * Load registered files. + * + * @see https://mochajs.org/api/mocha#loadFiles + */ + protected loadFiles(fn?: () => void): void; +} + +declare namespace Mocha { + namespace utils { + /** + * Compute a slug from the given `str`. + * + * @see https://mochajs.org/api/module-utils.html#.slug + */ + function slug(str: string): string; + + /** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @see https://mochajs.org/api/module-utils.html#.clean + */ + function clean(str: string): string; + + /** + * Highlight the given string of `js`. + */ + function highlight(js: string): string; + + /** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it is. + */ + function type(value: any): string; + + /** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, returns `'{}'`, `'[Function]'`, or `'[]'` respectively. + * - If `value` has properties, call canonicalize} on it, then return result of `JSON.stringify()` + * + * @see https://mochajs.org/api/module-utils.html#.stringify + */ + function stringify(value: any): string; + + /** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, returns `'[]'`, `'{}'`, or `'[Function]'` respectively. + * + * @see https://mochajs.org/api/module-utils.html#.canonicalize + */ + function canonicalize(value: any, stack: any[], typeHint: string): any; + + /** + * Lookup file names at the given `path`. + * + * @see https://mochajs.org/api/Mocha.utils.html#.exports.lookupFiles + */ + function lookupFiles(filepath: string, extensions?: string[], recursive?: boolean): string[]; + + /** + * Generate an undefined error with a message warning the user. + * + * @see https://mochajs.org/api/module-utils.html#.undefinedError + */ + function undefinedError(): Error; + + /** + * Generate an undefined error if `err` is not defined. + * + * @see https://mochajs.org/api/module-utils.html#.getError + */ + function getError(err: Error | undefined): Error; + + /** + * When invoking this function you get a filter function that get the Error.stack as an + * input, and return a prettify output. (i.e: strip Mocha and internal node functions from + * stack trace). + * + * @see https://mochajs.org/api/module-utils.html#.stackTraceFilter + */ + function stackTraceFilter(): (stack: string) => string; } - type Interface = keyof InterfaceContributions; - - interface IContext { - _runnable?: IRunnable; - test?: IRunnable; - - runnable(): IRunnable | undefined; - runnable(runnable: IRunnable): IContext; - timeout(): number; - timeout(timeout: number): IContext; - enableTimeouts(enableTimeouts: boolean): IContext; - slow(slow: number): IContext; - skip(): IContext; - retries(): number; - retries(retries: number): IContext; - inspect(): string; + namespace interfaces { + function bdd(suite: Suite): void; + function tdd(suite: Suite): void; + function qunit(suite: Suite): void; + function exports(suite: Suite): void; } - interface ISuiteCallbackContext { - timeout(ms: number | string): this; - retries(n: number): this; - slow(ms: number): this; + // #region Test interface augmentations + + interface HookFunction { + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: AsyncFunc): void; } - interface IHookCallbackContext { - skip(): this; - timeout(ms: number | string): this; - [index: string]: any; + interface SuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; + + /** + * [bdd, tdd, qunit] Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveSuiteFunction; + + /** + * [bdd, tdd] Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingSuiteFunction; } - interface ITestCallbackContext { - skip(): this; - timeout(ms: number | string): this; - retries(n: number): this; - slow(ms: number): this; - [index: string]: any; + interface ExclusiveSuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. Indicates this suite should be executed + * exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; } - /** Partial interface for Mocha's `Runnable` class. */ - interface IRunnable extends GenericEventEmitter { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + * + * @returns [bdd] `Suite` + * @returns [tdd] `void` + */ + type PendingSuiteFunction = (title: string, fn: (this: Suite) => void) => Suite | void; + + interface TestFunction { + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + + /** + * Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveTestFunction; + + /** + * Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingTestFunction; + + /** + * Number of attempts to retry. + * + * - _Only available when invoked via the mocha CLI._ + */ + retries(n: number): void; + } + + interface ExclusiveTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + interface PendingTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let afterEach: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let beforeEach: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let before: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let describe: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let it: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let xit: PendingTestFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let setup: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let suiteTeardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let suite: SuiteFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let teardown: HookFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let test: TestFunction; + + /** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ + function run(): void; + + // #endregion Test interface augmentations + + namespace reporters { + /** + * Initialize a new `Base` reporter. + * + * All other reporters generally inherit from this reporter, providing stats such as test duration, + * number of tests passed / failed, etc. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html + */ + class Base { + constructor(runner: Runner, options?: MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: MochaOptions); + + /** + * Test run statistics + */ + stats: Stats; + + /** + * Test failures + */ + failures: Test[]; + + /** + * The configured runner + */ + runner: Runner; + + /** + * Output common epilogue used by many of the bundled reporters. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.Base#epilogue + */ + epilogue(): void; + + done?(failures: number, fn?: (failures: number) => void): void; + } + + namespace Base { + /** + * Enables coloring by default + * + * @see https://mochajs.org/api/module-base#.useColors + */ + let useColors: boolean; + + /** + * Inline diffs instead of +/- + * + * @see https://mochajs.org/api/module-base#.inlineDiffs + */ + let inlineDiffs: boolean; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + const colors: ColorMap; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + interface ColorMap { + // added by Base + pass: number; + fail: number; + "bright pass": number; + "bright fail": number; + "bright yellow": number; + pending: number; + suite: number; + "error title": number; + "error message": number; + "error stack": number; + checkmark: number; + fast: number; + medium: number; + slow: number; + green: number; + light: number; + "diff gutter": number; + "diff added": number; + "diff removed": number; + + // added by Progress + progress: number; + + // added by Landing + plane: number; + "plane crash": number; + runway: number; + + [key: string]: number; + } + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + const symbols: SymbolMap; + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + interface SymbolMap { + ok: string; + err: string; + dot: string; + comma: string; + bang: string; + [key: string]: string; + } + + /** + * Color `str` with the given `type` (from `colors`) + * + * @see https://mochajs.org/api/module-base#.color + */ + function color(type: string, str: string): string; + + /** + * Expose terminal window size + * + * @see https://mochajs.org/api/module-base#.window + */ + const window: { + width: number; + }; + + /** + * ANSI TTY control sequences common among reporters. + * + * @see https://mochajs.org/api/module-base#.cursor + */ + namespace cursor { + /** + * Hides the cursor + */ + function hide(): void; + + /** + * Shows the cursor + */ + function show(): void; + + /** + * Deletes the current line + */ + function deleteLine(): void; + + /** + * Moves to the beginning of the line + */ + function beginningOfLine(): void; + + /** + * Clears the line and moves to the beginning of the line. + */ + function CR(): void; + } + + /** + * Returns a diff between two strings with colored ANSI output. + * + * @see https://mochajs.org/api/module-base#.generateDiff + */ + function generateDiff(actual: string, expected: string): string; + + /** + * Output the given `failures` as a list. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.exports.list1 + */ + function list(failures: Test[]): void; + } + + /** + * Initialize a new `Dot` matrix test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Dot.html + */ + class Dot extends Base { + } + + /** + * Initialize a new `Doc` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Doc.html + */ + class Doc extends Base { + } + + /** + * Initialize a new `TAP` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.TAP.html + */ + class TAP extends Base { + } + + /** + * Initialize a new `JSON` reporter + * + * @see https://mochajs.org/api/Mocha.reporters.JSON.html + */ + class JSON extends Base { + } + + /** + * Initialize a new `HTML` reporter. + * + * - _This reporter cannot be used on the console._ + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html + */ + class HTML extends Base { + /** + * Provide suite URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#suiteURL + */ + suiteURL(suite: Suite): string; + + /** + * Provide test URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#testURL + */ + testURL(test: Test): string; + + /** + * Adds code toggle functionality for the provided test's list element. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#addCodeToggle + */ + addCodeToggle(el: HTMLLIElement, contents: string): void; + } + + /** + * Initialize a new `List` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.List.html + */ + class List extends Base { + } + + /** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @see https://mochajs.org/api/Mocha.reporters.Min.html + */ + class Min extends Base { + } + + /** + * Initialize a new `Spec` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Spec.html + */ + class Spec extends Base { + } + + /** + * Initialize a new `NyanCat` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Nyan.html + */ + class Nyan extends Base { + private colorIndex; + private numberOfLines; + private rainbowColors; + private scoreboardWidth; + private tick; + private trajectories; + private trajectoryWidthMax; + private draw; + private drawScoreboard; + private appendRainbow; + private drawRainbow; + private drawNyanCat; + private face; + private cursorUp; + private cursorDown; + private generateColors; + private rainbowify; + } + + /** + * Initialize a new `XUnit` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html + */ + class XUnit extends Base { + constructor(runner: Runner, options?: XUnit.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: XUnit.MochaOptions); + + /** + * Override done to close the stream (if it's a file). + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#done + */ + done(failures: number, fn: (failures: number) => void): void; + + /** + * Write out the given line. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#write + */ + write(line: string): void; + + /** + * Output tag for the given `test.` + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#test + */ + test(test: Test): void; + } + + namespace XUnit { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + output?: string; + suiteName?: string; + } + } + + /** + * Initialize a new `Markdown` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Markdown.html + */ + class Markdown extends Base { + } + + /** + * Initialize a new `Progress` bar test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Progress.html + */ + class Progress extends Base { + constructor(runner: Runner, options?: Progress.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: Progress.MochaOptions); + } + + namespace Progress { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + open?: string; + complete?: string; + incomplete?: string; + close?: string; + verbose?: boolean; + } + } + + /** + * Initialize a new `Landing` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Landing.html + */ + class Landing extends Base { + } + + /** + * Initialize a new `JSONStream` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.JSONStream.html + */ + class JSONStream extends Base { + } + + // value-only aliases + const base: typeof Base; + const dot: typeof Dot; + const doc: typeof Doc; + const tap: typeof TAP; + const json: typeof JSON; + const html: typeof HTML; + const list: typeof List; + const spec: typeof Spec; + const nyan: typeof Nyan; + const xunit: typeof XUnit; + const markdown: typeof Markdown; + const progress: typeof Progress; + const landing: typeof Landing; + // NOTE: not possible to type this correctly: + // const "json-stream": typeof JSONStream; + } + + /** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Runnable.html + */ + class Runnable { + private _slow; + private _enableTimeouts; + private _retries; + private _currentRetry; + private _timeout; + private _timeoutError; + + constructor(title: string, fn?: Func | AsyncFunc); + title: string; - fn: Function; + fn: Func | AsyncFunc | undefined; + body: string; async: boolean; sync: boolean; timedOut: boolean; - timeout(n: number | string): this; - duration?: number; - } - - /** Partial interface for Mocha's `Suite` class. */ - interface ISuite { - ctx: IContext; - parent: ISuite; - root: boolean; - title: string; - suites: ISuite[]; - tests: ITest[]; - - _beforeEach: IHook[]; - _beforeAll: IHook[]; - _afterEach: IHook[]; - _afterAll: IHook[]; - - bail(): boolean; - bail(bail: boolean): ISuite; - fullTitle(): string; - retries(): number; - retries(retries: number): ISuite; - slow(): number; - slow(slow: number): ISuite; - timeout(): number; - timeout(timeout: number): ISuite; - } - - /** Partial interface for Mocha's `Test` class. */ - interface ITest extends IRunnable { - body?: string; - file?: string; - parent: ISuite; pending: boolean; - state: 'failed' | 'passed' | undefined; - type: 'test'; + duration?: number; + parent?: Suite; + state?: "failed" | "passed"; + timer?: any; + ctx?: Context; + callback?: Done; + allowUncaught?: boolean; + file?: string; + /** + * Get test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(): number; + + /** + * Set test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(): number; + + /** + * Set test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Halt and mark as pending. + */ + skip(): never; + + /** + * Check if this runnable or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Runnable.html#isPending + */ + isPending(): boolean; + + /** + * Return `true` if this Runnable has failed. + */ + isFailed(): boolean; + + /** + * Return `true` if this Runnable has passed. + */ + isPassed(): boolean; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(): number; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(n: number): void; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(): number; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(n: number): void; + + /** + * Return the full title generated by recursively concatenating the parent's full title. + */ fullTitle(): string; + + /** + * Return the title path generated by concatenating the parent's title path with the title. + */ + titlePath(): string[]; + + /** + * Clear the timeout. + * + * @see https://mochajs.org/api/Runnable.html#clearTimeout + */ + clearTimeout(): void; + + /** + * Inspect the runnable void of private properties. + * + * @see https://mochajs.org/api/Runnable.html#inspect + */ + inspect(): string; + + /** + * Reset the timeout. + * + * @see https://mochajs.org/api/Runnable.html#resetTimeout + */ + resetTimeout(): void; + + /** + * Get a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(): string[]; + + /** + * Set a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(globals: ReadonlyArray): void; + + /** + * Run the test and invoke `fn(err)`. + * + * @see https://mochajs.org/api/Runnable.html#run + */ + run(fn: Done): void; } - interface IHook extends IRunnable { - ctx?: IContext; - parent?: ISuite; - type: 'hook'; + // #region Runnable "error" event + interface Runnable extends NodeJS.EventEmitter { + on(event: "error", listener: (error: any) => void): this; + once(event: "error", listener: (error: any) => void): this; + addListener(event: "error", listener: (error: any) => void): this; + removeListener(event: "error", listener: (error: any) => void): this; + prependListener(event: "error", listener: (error: any) => void): this; + prependOnceListener(event: "error", listener: (error: any) => void): this; + emit(name: "error", error: any): boolean; + } + // #endregion Runnable "error" event + // #region Runnable untyped events + interface Runnable extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runnable untyped events - error(err: Error): void; + /** + * Test context + * + * @see https://mochajs.org/api/module-Context.html#~Context + */ + class Context { + private _runnable; + + test?: Runnable; + currentTest?: Test; + + /** + * Get the context `Runnable`. + */ + runnable(): Runnable; + + /** + * Set the context `Runnable`. + */ + runnable(runnable: Runnable): this; + /** @deprecated Use the overload that accepts `Mocha.Runnable` instead. */ + runnable(runnable: IRunnable): this; + + /** + * Get test timeout. + */ + timeout(): number; + + /** + * Set test timeout. + */ + timeout(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get test slowness threshold. + */ + slow(): number; + + /** + * Set test slowness threshold. + */ + slow(ms: string | number): this; + + /** + * Mark a test as skipped. + */ + skip(): never; + + /** + * Get the number of allowed retries on failed tests. + */ + retries(): number; + + /** + * Set the number of allowed retries on failed tests. + */ + retries(n: number): this; + + [key: string]: any; } - interface IBeforeAndAfterContext extends IHookCallbackContext { - currentTest: ITest; + /** + * Initialize a `Runner` for the given `suite`. + * + * @see https://mochajs.org/api/Mocha.Runner.html + */ + class Runner { + private _globals; + private _abort; + private _delay; + private _defaultGrep; + private next; + private hookErr; + private prevGlobalsLength; + private nextSuite; + + constructor(suite: Suite, delay: boolean); + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + constructor(suite: ISuite, delay: boolean); + + suite: Suite; + started: boolean; + total: number; + failures: number; + asyncOnly?: boolean; + allowUncaught?: boolean; + fullStackTrace?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + ignoreLeaks?: boolean; + test?: Test; + currentRunnable?: Runnable; + stats?: Stats; // added by reporters + + /** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grep + */ + grep(re: RegExp, invert: boolean): this; + + /** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grepTotal + */ + grepTotal(suite: Suite): number; + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + grepTotal(suite: ISuite): number; + + /** + * Gets the allowed globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(): string[]; + + /** + * Allow the given `arr` of globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(arr: ReadonlyArray): this; + + /** + * Run the root suite and invoke `fn(failures)` on completion. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#run + */ + run(fn?: (failures: number) => void): this; + + /** + * Cleanly abort execution. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#abort + */ + abort(): this; + + /** + * Handle uncaught exceptions. + * + * @see https://mochajs.org/api/Mocha.Runner.html#uncaught + */ + uncaught(err: any): void; + + /** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + */ + protected static immediately(callback: Function): void; + + /** + * Return a list of global properties. + * + * @see https://mochajs.org/api/Mocha.Runner.html#globalProps + */ + protected globalProps(): string[]; + + /** + * Check for global variable leaks. + * + * @see https://mochajs.org/api/Mocha.Runner.html#checkGlobals + */ + protected checkGlobals(test: Test): void; + + /** + * Fail the given `test`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#fail + */ + protected fail(test: Test, err: any): void; + + /** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @see https://mochajs.org/api/Mocha.Runner.html#failHook + */ + protected failHook(hook: Hook, err: any): void; + + /** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hook + */ + protected hook(name: string, fn: () => void): void; + + /** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hooks + */ + protected hooks(name: string, suites: Suite[], fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the top level down. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookUp + */ + protected hookUp(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the bottom up. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookDown + */ + protected hookDown(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Return an array of parent Suites from closest to furthest. + * + * @see https://mochajs.org/api/Mocha.Runner.html#parents + */ + protected parents(): Suite[]; + + /** + * Run the current test and callback `fn(err)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTest + */ + protected runTest(fn: Done): any; + + /** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTests + */ + protected runTests(suite: Suite, fn: (errSuite?: Suite) => void): void; + + /** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runSuite + */ + protected runSuite(suite: Suite, fn: (errSuite?: Suite) => void): void; } - interface IStats { + // #region Runner "waiting" event + interface Runner { + on(event: "waiting", listener: (rootSuite: Suite) => void): this; + once(event: "waiting", listener: (rootSuite: Suite) => void): this; + addListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + removeListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependOnceListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + emit(name: "waiting", rootSuite: Suite): boolean; + } + // #endregion Runner "waiting" event + // #region Runner "start" event + interface Runner extends NodeJS.EventEmitter { + on(event: "start", listener: () => void): this; + once(event: "start", listener: () => void): this; + addListener(event: "start", listener: () => void): this; + removeListener(event: "start", listener: () => void): this; + prependListener(event: "start", listener: () => void): this; + prependOnceListener(event: "start", listener: () => void): this; + emit(name: "start"): boolean; + } + // #endregion Runner "start" event + // #region Runner "end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "end", listener: () => void): this; + once(event: "end", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + emit(name: "end"): boolean; + } + // #endregion Runner "end" event + // #region Runner "suite" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Runner "suite" event + // #region Runner "suite end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite end", listener: (suite: Suite) => void): this; + once(event: "suite end", listener: (suite: Suite) => void): this; + addListener(event: "suite end", listener: (suite: Suite) => void): this; + removeListener(event: "suite end", listener: (suite: Suite) => void): this; + prependListener(event: "suite end", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite end", listener: (suite: Suite) => void): this; + emit(name: "suite end", suite: Suite): boolean; + } + // #endregion Runner "suite end" event + // #region Runner "test" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Runner "test" event + // #region Runner "test end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test end", listener: (test: Test) => void): this; + once(event: "test end", listener: (test: Test) => void): this; + addListener(event: "test end", listener: (test: Test) => void): this; + removeListener(event: "test end", listener: (test: Test) => void): this; + prependListener(event: "test end", listener: (test: Test) => void): this; + prependOnceListener(event: "test end", listener: (test: Test) => void): this; + emit(name: "test end", test: Test): boolean; + } + // #endregion Runner "test end" event + // #region Runner "hook" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook", listener: (hook: Hook) => void): this; + once(event: "hook", listener: (hook: Hook) => void): this; + addListener(event: "hook", listener: (hook: Hook) => void): this; + removeListener(event: "hook", listener: (hook: Hook) => void): this; + prependListener(event: "hook", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook", listener: (hook: Hook) => void): this; + emit(name: "hook", hook: Hook): boolean; + } + // #endregion Runner "hook" event + // #region Runner "hook end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook end", listener: (hook: Hook) => void): this; + once(event: "hook end", listener: (hook: Hook) => void): this; + addListener(event: "hook end", listener: (hook: Hook) => void): this; + removeListener(event: "hook end", listener: (hook: Hook) => void): this; + prependListener(event: "hook end", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook end", listener: (hook: Hook) => void): this; + emit(name: "hook end", hook: Hook): boolean; + } + // #endregion Runner "hook end" event + // #region Runner "pass" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pass", listener: (test: Test) => void): this; + once(event: "pass", listener: (test: Test) => void): this; + addListener(event: "pass", listener: (test: Test) => void): this; + removeListener(event: "pass", listener: (test: Test) => void): this; + prependListener(event: "pass", listener: (test: Test) => void): this; + prependOnceListener(event: "pass", listener: (test: Test) => void): this; + emit(name: "pass", test: Test): boolean; + } + // #endregion Runner "pass" event + // #region Runner "fail" event + interface Runner extends NodeJS.EventEmitter { + on(event: "fail", listener: (test: Test, err: any) => void): this; + once(event: "fail", listener: (test: Test, err: any) => void): this; + addListener(event: "fail", listener: (test: Test, err: any) => void): this; + removeListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependOnceListener(event: "fail", listener: (test: Test, err: any) => void): this; + emit(name: "fail", test: Test, err: any): boolean; + } + // #endregion Runner "fail" event + // #region Runner "pending" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pending", listener: (test: Test) => void): this; + once(event: "pending", listener: (test: Test) => void): this; + addListener(event: "pending", listener: (test: Test) => void): this; + removeListener(event: "pending", listener: (test: Test) => void): this; + prependListener(event: "pending", listener: (test: Test) => void): this; + prependOnceListener(event: "pending", listener: (test: Test) => void): this; + emit(name: "pending", test: Test): boolean; + } + // #endregion Runner "pending" event + // #region Runner untyped events + interface Runner extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Suite` with the given `title` and `ctx`. + * + * @see https://mochajs.org/api/Mocha.Suite.html + */ + class Suite { + private _beforeEach; + private _beforeAll; + private _afterEach; + private _afterAll; + private _timeout; + private _enableTimeouts; + private _slow; + private _bail; + private _retries; + private _onlyTests; + private _onlySuites; + + constructor(title: string, parentContext?: Context); + /** @deprecated Use the overload that accepts `Mocha.Context` instead. */ + constructor(title: string, parentContext?: IContext); + + ctx: Context; + suites: Suite[]; + tests: Test[]; + pending: boolean; + file?: string; + root: boolean; + delayed: boolean; + parent: Suite | undefined; + title: string; + + /** + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. + * + * @see https://mochajs.org/api/mocha#.exports.create + */ + static create(parent: Suite, title: string): Suite; + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + static create(parent: ISuite, title: string): Suite; + + /** + * Return a clone of this `Suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#clone + */ + clone(): Suite; + + /** + * Get timeout `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(): number; + + /** + * Set timeout `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(): number; + + /** + * Set number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(n: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are `enabled`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get slow `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(): number; + + /** + * Set slow `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(): boolean; + + /** + * Set whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(bail: boolean): this; + + /** + * Check if this suite or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Mocha.Suite.html#isPending + */ + isPending(): boolean; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: AsyncFunc): this; + + /** + * Add a test `suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addSuite + */ + addSuite(suite: Suite): this; + /** @deprecated Use the overload that accepts `Mocha.ISuite` instead. */ + addSuite(suite: ISuite): this; + + /** + * Add a `test` to this suite. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addTest + */ + addTest(test: Test): this; + /** @deprecated Use the overload that accepts `Mocha.ITest` instead. */ + addTest(test: ITest): this; + + /** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#fullTitle + */ + fullTitle(): string; + + /** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#titlePath + */ + titlePath(): string[]; + + /** + * Return the total number of tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#total + */ + total(): number; + + /** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#eachTest + */ + eachTest(fn: (test: Test) => void): this; + + /** + * This will run the root suite if we happen to be running in delayed mode. + * + * @see https://mochajs.org/api/Mocha.Suite.html#run + */ + run(): void; + + /** + * Generic hook-creator. + */ + protected _createHook(title: string, fn?: Func | AsyncFunc): Hook; + } + + // #region Suite "beforeAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeAll", listener: (hook: Hook) => void): this; + once(event: "beforeAll", listener: (hook: Hook) => void): this; + addListener(event: "beforeAll", listener: (hook: Hook) => void): this; + removeListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeAll", listener: (hook: Hook) => void): this; + emit(name: "beforeAll", hook: Hook): boolean; + } + // #endregion Suite "beforeAll" event + // #region Suite "afterAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterAll", listener: (hook: Hook) => void): this; + once(event: "afterAll", listener: (hook: Hook) => void): this; + addListener(event: "afterAll", listener: (hook: Hook) => void): this; + removeListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterAll", listener: (hook: Hook) => void): this; + emit(name: "afterAll", hook: Hook): boolean; + } + // #endregion Suite "afterAll" event + // #region Suite "beforeEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeEach", listener: (hook: Hook) => void): this; + once(event: "beforeEach", listener: (hook: Hook) => void): this; + addListener(event: "beforeEach", listener: (hook: Hook) => void): this; + removeListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeEach", listener: (hook: Hook) => void): this; + emit(name: "beforeEach", hook: Hook): boolean; + } + // #endregion Suite "beforeEach" event + // #region Suite "afterEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterEach", listener: (hook: Hook) => void): this; + once(event: "afterEach", listener: (hook: Hook) => void): this; + addListener(event: "afterEach", listener: (hook: Hook) => void): this; + removeListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterEach", listener: (hook: Hook) => void): this; + emit(name: "afterEach", hook: Hook): boolean; + } + // #endregion Suite "afterEach" event + // #region Suite "suite" event + interface Suite extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Suite "suite" event + // #region Suite "test" event + interface Suite { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Suite "test" event + // #region Suite "run" event + interface Suite extends NodeJS.EventEmitter { + on(event: "run", listener: () => void): this; + once(event: "run", listener: () => void): this; + addListener(event: "run", listener: () => void): this; + removeListener(event: "run", listener: () => void): this; + prependListener(event: "run", listener: () => void): this; + prependOnceListener(event: "run", listener: () => void): this; + emit(name: "run"): boolean; + } + // #endregion Suite "run" event + // #region Suite "pre-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "pre-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "pre-require" event + // #region Suite "require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + once(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + addListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + removeListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + emit(name: "require", module: any, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "require" event + // #region Suite "post-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "post-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "post-require" event + // #region Suite untyped events + interface Suite extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Hook` with the given `title` and callback `fn` + * + * @see https://mochajs.org/api/Hook.html + */ + class Hook extends Runnable { + private _error; + + type: "hook"; + originalTitle?: string; // added by Runner + + /** + * Get the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(): any; + + /** + * Set the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(err: any): void; + } + + /** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Test.html + */ + class Test extends Runnable { + type: "test"; + speed?: "slow" | "medium" | "fast"; // added by reporters + err?: Error; // added by reporters + clone(): Test; + } + + /** + * Test statistics + */ + interface Stats { suites: number; tests: number; passes: number; @@ -271,252 +2156,701 @@ declare class GenericEventEmitter { failures: number; start?: Date; end?: Date; - duration?: Date; + duration?: number; } - /** Partial interface for Mocha's `Runner` class. */ - interface IRunner extends GenericEventEmitter { - asyncOnly?: boolean; - stats?: IStats; - started: boolean; - suite: ISuite; - total: number; - failures: number; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; + type TestInterface = (suite: Suite) => void; + + interface ReporterConstructor { + new (runner: Runner, options: { reporterOptions?: any; }): reporters.Base; + } + + type Done = (err?: any) => void; + + /** + * Callback function used for tests and hooks. + */ + type Func = (this: Context, done: Done) => void; + + /** + * Async callback function used for tests and hooks. + */ + type AsyncFunc = (this: Context) => PromiseLike; + + /** + * Options to pass to Mocha. + */ + interface MochaOptions { + /** Test interfaces ("bdd", "tdd", "exports", etc.). */ + ui?: Interface; + + /** + * Reporter constructor, built-in reporter name, or reporter module path. Defaults to + * `"spec"`. + */ + reporter?: string | ReporterConstructor; + + /** Options to pass to the reporter. */ + reporterOptions?: any; + + /** Array of accepted globals. */ + globals?: string[]; + + /** timeout in milliseconds. */ + timeout?: number; + + enableTimeouts?: boolean; + + /** number of times to retry failed tests. */ + retries?: number; + + /** bail on the first test failure. */ + bail?: boolean; + + /** milliseconds to wait before considering a test slow. */ + slow?: number; + + /** ignore global leaks. */ ignoreLeaks?: boolean; - grep: (re: string, invert: boolean) => this; - grepTotal: (suite: ISuite) => number; - globals: (arr: ReadonlyArray) => this | string[]; - abort: () => this; - run: (fn?: (failures: number) => void) => this; + /** display the full stack trace on failure. */ + fullStackTrace?: boolean; + + /** string or regexp to filter tests with. */ + grep?: string | RegExp; + + /** Enable growl support. */ + growl?: boolean; + + /** Emit color output. */ + useColors?: boolean; + + /** Use inline diffs rather than +/-. */ + inlineDiffs?: boolean; + + /** Do not show diffs at all. */ + hideDiff?: boolean; + + asyncOnly?: boolean; + delay?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + noHighlighting?: boolean; + allowUncaught?: boolean; } - interface IContextDefinition { - (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; - only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; - skip(description: string, callback: (this: ISuiteCallbackContext) => void): void; - timeout(ms: number | string): void; + interface MochaInstanceOptions extends MochaOptions { + files?: string[]; } - interface ITestDefinition { - (expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; - only(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; - skip(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): void; - timeout(ms: number | string): void; - state: "failed" | "passed"; - } - - namespace reporters { - class Base { - runner: IRunner; - stats: IStats; - - constructor(runner: IRunner); - } - - class Doc extends Base { } - class Dot extends Base { } - class HTML extends Base { } - class HTMLCov extends Base { } - class JSON extends Base { } - class JSONCov extends Base { } - class JSONStream extends Base { } - class Landing extends Base { } - class List extends Base { } - class Markdown extends Base { } - class Min extends Base { } - class Nyan extends Base { } - class Progress extends Base { - /** - * @param options.open String used to indicate the start of the progress bar. - * @param options.complete String used to indicate a complete test on the progress bar. - * @param options.incomplete String used to indicate an incomplete test on the progress bar. - * @param options.close String used to indicate the end of the progress bar. - */ - constructor(runner: IRunner, options?: { - open?: string; - complete?: string; - incomplete?: string; - close?: string; - }); - } - class Spec extends Base { } - class TAP extends Base { } - class XUnit extends Base { - constructor(runner: IRunner, options?: any); - } - } - - /* - * All ambient functions are also available via require('mocha') when invoked via the mocha CLI - * See for details: https://mochajs.org/#require - */ - - /** Only available when invoked via the mocha CLI */ - const describe: IContextDefinition; - /** Only available when invoked via the mocha CLI */ - const xdescribe: IContextDefinition; /** - * alias for `describe` - * Only available when invoked via the mocha CLI + * Variables added to the global scope by Mocha when run in the CLI. */ - const context: IContextDefinition; - /** - * alias for `describe` - * Only available when invoked via the mocha CLI - */ - const suite: IContextDefinition; - /** Only available when invoked via the mocha CLI */ - const it: ITestDefinition; - /** Only available when invoked via the mocha CLI */ - const xit: ITestDefinition; - /** - * alias for `it` - * Only available when invoked via the mocha CLI - */ - const test: ITestDefinition; - /** - * Alias for `it` - * Only available when invoked via the mocha CLI - */ - const specify: ITestDefinition; - /** Only available when invoked via the mocha CLI */ - function setup(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function teardown(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function suiteSetup(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function suiteTeardown(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function before(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function before(description: string, callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function after(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function after(description: string, callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function beforeEach(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function beforeEach(description: string, callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function afterEach(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function afterEach(description: string, callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; + interface MochaGlobals { + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + before: HookFunction; - class Runnable extends GenericEventEmitter { - new(title: string, fn: () => any): IRunnable; + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + beforeEach: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + afterEach: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + describe: SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + context: SuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xdescribe: PendingSuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xcontext: PendingSuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + it: TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + specify: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xit: PendingTestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xspecify: PendingTestFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + suiteTeardown: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + setup: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + teardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + suite: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + test: TestFunction; + + run: typeof run; } - class Context implements IContext { - constructor(); + /** + * Third-party declarations that want to add new entries to the `Reporter` union can + * contribute names here. + */ + interface ReporterContributions { + Base: never; + base: never; + Dot: never; + dot: never; + TAP: never; + tap: never; + JSON: never; + json: never; + HTML: never; + html: never; + List: never; + list: never; + Min: never; + min: never; + Spec: never; + spec: never; + Nyan: never; + nyan: never; + XUnit: never; + xunit: never; + Markdown: never; + markdown: never; + Progress: never; + progress: never; + Landing: never; + landing: never; + JSONStream: never; + "json-stream": never; + } - _runnable?: IRunnable; + type Reporter = keyof ReporterContributions; + + /** + * Third-party declarations that want to add new entries to the `Interface` union can + * contribute names here. + */ + interface InterfaceContributions { + bdd: never; + tdd: never; + qunit: never; + exports: never; + } + + type Interface = keyof InterfaceContributions; + + // #region Deprecations + + /** @deprecated use `Mocha.Context` instead. */ + interface IContext { test?: IRunnable; - runnable(): IRunnable | undefined; + /** @deprecated `.runnable()` returns `this` in `Mocha.Context`. */ runnable(runnable: IRunnable): IContext; timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Context`. */ timeout(timeout: number): IContext; + /** @deprecated `.enableTimeouts()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.enableTimeouts()` returns `this` in `Mocha.Context`. */ enableTimeouts(enableTimeouts: boolean): IContext; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.slow()` returns `this` in `Mocha.Context`. */ slow(slow: number): IContext; + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ skip(): IContext; retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Context`. */ retries(retries: number): IContext; - inspect(): string; } - class Runner extends GenericEventEmitter implements IRunner { - constructor(suite: ISuite, delay: boolean); - - asyncOnly?: boolean; - stats?: IStats; - started: boolean; - suite: ISuite; - total: number; - failures: number; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; - ignoreLeaks?: boolean; - - grep: (re: string, invert: boolean) => this; - grepTotal: (suite: ISuite) => number; - globals: (arr: ReadonlyArray) => this | string[]; - abort: () => this; - run: (fn?: (failures: number) => void) => this; + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuiteCallbackContext { + /** @deprecated `.timeout()` has additional overloads in `Mocha.Suite`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Suite`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Suite`. */ + slow(ms: number): this; } - class Suite extends GenericEventEmitter implements ISuite { - constructor(title: string, parentContext: IContext); + /** @deprecated use `Mocha.Context` instead. */ + interface IHookCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + [index: string]: any; + } + /** @deprecated use `Mocha.Context` instead. */ + interface ITestCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Context`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + slow(ms: number): this; + [index: string]: any; + } + + /** Partial interface for Mocha's `Runnable` class. */ + /** @deprecated use `Mocha.Runnable` instead. */ + interface IRunnable extends NodeJS.EventEmitter { + title: string; + /** @deprecated `.fn` has type `Func | AsyncFunc` in `Mocha.Runnable`. */ + fn: Function | undefined; + async: boolean; + sync: boolean; + timedOut: boolean; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Runnable`. */ + timeout(n: number | string): this; + duration?: number; + } + + /** Partial interface for Mocha's `Suite` class. */ + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuite { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Suite`. */ ctx: IContext; - parent: ISuite; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Suite`. */ + parent: ISuite | undefined; root: boolean; title: string; + /** @deprecated `.suites` has type `Mocha.Suite[]` in `Mocha.Suite`. */ suites: ISuite[]; + /** @deprecated `.tests` has type `Mocha.Test[]` in `Mocha.Suite`. */ tests: ITest[]; - _beforeEach: IHook[]; - _beforeAll: IHook[]; - _afterEach: IHook[]; - _afterAll: IHook[]; - bail(): boolean; + /** @deprecated `.bail()` returns `this` in `Mocha.Suite`. */ bail(bail: boolean): ISuite; fullTitle(): string; retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Suite`. */ retries(retries: number): ISuite; slow(): number; + /** @deprecated `.slow()` returns `this` in `Mocha.Suite`. */ slow(slow: number): ISuite; timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Suite`. */ timeout(timeout: number): ISuite; } - class Hook extends Runnable implements IHook { - constructor(title: string, fn: () => any); - - async: boolean; - ctx?: IContext; - duration?: number; - fn: Function; + /** Partial interface for Mocha's `Test` class. */ + /** @deprecated use `Mocha.Test` instead. */ + interface ITest extends IRunnable { + body?: string; + file?: string; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Test`. */ parent?: ISuite; - sync: boolean; - timedOut: boolean; - timeout(n: number | string): this; - title: string; - type: 'hook'; + pending: boolean; + state?: 'failed' | 'passed'; + type: 'test'; + fullTitle(): string; + } + /** @deprecated use `Mocha.Hook` instead. */ + interface IHook extends IRunnable { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Runnable`. */ + ctx?: IContext; + /** @deprecated `.parent` has type `Mocha.Suite` in `Mocha.Runnable`. */ + parent?: ISuite; + type: 'hook'; + /** @deprecated `.error()` has additional overloads in `Mocha.Hook`. */ error(err: Error): void; } - class Test extends Runnable implements ITest { - constructor(title: string, fn: () => any); - - async: boolean; - body?: string; - duration?: number; - file?: string; - fn: Function; - parent: ISuite; - pending: boolean; - state: 'failed' | 'passed' | undefined; - sync: boolean; - timedOut: boolean; - timeout(n: number | string): this; - title: string; - type: 'test'; - - fullTitle(): string; + /** @deprecated use `Mocha.Context` instead. */ + interface IBeforeAndAfterContext extends IHookCallbackContext { + /** @deprecated `.currentTest` has type `Mocha.Test` in `Mocha.Context`. */ + currentTest?: ITest; } - } - declare module "mocha" { - export = Mocha; - } + /** @deprecated use `Mocha.Stats` instead. */ + type IStats = Stats; + + /** Partial interface for Mocha's `Runner` class. */ + /** @deprecated use `Mocha.Runner` instead. */ + interface IRunner extends NodeJS.EventEmitter { + asyncOnly?: boolean; + stats?: IStats; + started: boolean; + /** @deprecated `.suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + suite: ISuite; + total: number; + failures: number; + forbidOnly?: boolean; + forbidPending?: boolean; + fullStackTrace?: boolean; + ignoreLeaks?: boolean; + grep(re: RegExp, invert: boolean): this; + /** @deprecated Parameter `suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + grepTotal(suite: ISuite): number; + /** @deprecated `.globals()` has different overloads in `Mocha.Runner`. */ + globals(arr: ReadonlyArray): this | string[]; + abort(): this; + run(fn?: (failures: number) => void): this; + } + + /** @deprecated use `Mocha.SuiteFunction` instead. */ + interface IContextDefinition { + /** @deprecated use `Mocha.SuiteFunction` instead. */ + (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + skip(description: string, callback: (this: ISuiteCallbackContext) => void): void; + } + + /** @deprecated use `Mocha.TestFunction` instead. */ + interface ITestDefinition { + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction` does not allow mixing `done` with a return type of `PromiseLike`. */ + (expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#only` does not allow mixing `done` with a return type of `PromiseLike`. */ + only(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#skip` does not allow mixing `done` with a return type of `PromiseLike`. */ + skip(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): void; + } + + // #endregion +} + +declare global { + // #region Test interface augmentations + + /** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ + function run(): void; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + var before: Mocha.HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + var suiteSetup: Mocha.HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + var after: Mocha.HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + var suiteTeardown: Mocha.HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + var beforeEach: Mocha.HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + var setup: Mocha.HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + var afterEach: Mocha.HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + var teardown: Mocha.HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var describe: Mocha.SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var context: Mocha.SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var suite: Mocha.SuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xdescribe: Mocha.PendingSuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xcontext: Mocha.PendingSuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var it: Mocha.TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var specify: Mocha.TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var test: Mocha.TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xit: Mocha.PendingTestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xspecify: Mocha.PendingTestFunction; + + // #endregion Test interface augmentations + + // #region Reporter augmentations + + // Forward declaration for `HTMLLIElement` from lib.dom.d.ts. + // Required by Mocha.reporters.HTML. + // NOTE: Mocha *must not* have a direct dependency on DOM types. + // tslint:disable-next-line no-empty-interface + interface HTMLLIElement { } + + // Augments the DOM `Window` object when lib.dom.d.ts is loaded. + // tslint:disable-next-line no-empty-interface + interface Window extends Mocha.MochaGlobals { } + + namespace NodeJS { + // Forward declaration for `NodeJS.EventEmitter` from node.d.ts. + // Required by Mocha.Runnable, Mocha.Runner, and Mocha.Suite. + // NOTE: Mocha *must not* have a direct dependency on @types/node. + // tslint:disable-next-line no-empty-interface + interface EventEmitter { } + + // Augments NodeJS's `global` object when node.d.ts is loaded + // tslint:disable-next-line no-empty-interface + interface Global extends Mocha.MochaGlobals { } + } + + // #endregion Reporter augmentations + + // #region Browser augmentations + + /** + * Mocha global. + * + * - _Only supported in the browser._ + */ + const mocha: BrowserMocha; + + interface BrowserMocha extends Mocha { + /** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + * + * - _Only supported in the browser._ + */ + throwError(err: any): never; + + /** + * Setup mocha with the given settings options. + * + * - _Only supported in the browser._ + */ + setup(opts?: Mocha.Interface | MochaSetupOptions): this; + } + + /** + * Options to pass to `mocha.setup` in the browser. + */ + interface MochaSetupOptions extends Mocha.MochaOptions { + // TODO: This does not seem to be supported according to the source. Should it be removed? + require?: string[]; + fullTrace?: boolean; + } + + // #endregion Browser augmentations + + // #region Deprecations + + /** @deprecated use `Mocha.DoneCallback` instead. */ + type MochaDone = Mocha.Done; + + /** @deprecated use `Mocha.ReporterConstructor` instead. */ + type ReporterConstructor = Mocha.ReporterConstructor; + + // #endregion Deprecations +} diff --git a/types/mocha/lib/interfaces/common.d.ts b/types/mocha/lib/interfaces/common.d.ts new file mode 100644 index 0000000000..9756482354 --- /dev/null +++ b/types/mocha/lib/interfaces/common.d.ts @@ -0,0 +1,109 @@ +import Mocha = require("../../"); + +export = common; + +declare function common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, mocha: Mocha): common.CommonFunctions; + +declare namespace common { + interface CommonFunctions { + /** + * This is only present if flag --delay is passed into Mocha. It triggers + * root suite execution. + */ + runWithSuite(suite: Mocha.Suite): () => void; + + /** + * Execute before running tests. + */ + before(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before running tests. + */ + before(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + suite: SuiteFunctions; + test: TestFunctions; + } + + interface CreateOptions { + /** Title of suite */ + title: string; + + /** Suite function */ + fn?: (this: Mocha.Suite) => void; + + /** Is suite pending? */ + pending?: boolean; + + /** Filepath where this Suite resides */ + file?: string; + + /** Is suite exclusive? */ + isOnly?: boolean; + } + + interface SuiteFunctions { + /** + * Create an exclusive Suite; convenience function + */ + only(opts: CreateOptions): Mocha.Suite; + + /** + * Create a Suite, but skip it; convenience function + */ + skip(opts: CreateOptions): Mocha.Suite; + + /** + * Creates a suite. + */ + create(opts: CreateOptions): Mocha.Suite; + } + + interface TestFunctions { + /** + * Exclusive test-case. + */ + only(mocha: Mocha, test: Mocha.Test): Mocha.Test; + + /** + * Pending test case. + */ + skip(title: string): void; + + /** + * Number of retry attempts + */ + retries(n: number): void; + } +} diff --git a/types/mocha/lib/ms.d.ts b/types/mocha/lib/ms.d.ts new file mode 100644 index 0000000000..3b89a55fc5 --- /dev/null +++ b/types/mocha/lib/ms.d.ts @@ -0,0 +1,17 @@ +export = milliseconds; + +/** + * Parse the given `str` and return milliseconds. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~parse} + */ +declare function milliseconds(val: string): number; + +/** + * Format for `ms`. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~format} + */ +declare function milliseconds(val: number): string; diff --git a/types/mocha/mocha-node-tests.ts b/types/mocha/mocha-node-tests.ts deleted file mode 100644 index e5cd80c8cf..0000000000 --- a/types/mocha/mocha-node-tests.ts +++ /dev/null @@ -1,37 +0,0 @@ - - -import MochaDef = require('mocha'); - -class CustomSpecReporter extends MochaDef.reporters.Spec { - constructor(runner: Mocha.IRunner) { - super(runner); - - runner.on('test', (test: Mocha.ITest) => { - console.log(test.parent.title + '/' + test.title); - }); - } -} - -class MyReporter extends MochaDef.reporters.Base { - passes: number = 0; - failures: number = 0; - - constructor(runner: Mocha.IRunner) { - super(runner); - - runner.on('pass', (test: Mocha.ITest) => { - this.passes++; - console.log('pass: %s', test.fullTitle()); - }); - - runner.on('fail', (test: Mocha.ITest, err: Error) => { - this.failures++; - console.log('fail: %s -- error: %s', test.fullTitle(), err.message); - }); - - runner.on('end', () => { - console.log('end: %d/%d', this.passes, this.passes + this.failures); - process.exit(this.failures); - }); - } -} diff --git a/types/mocha/mocha-node.d.ts b/types/mocha/mocha-node.d.ts deleted file mode 100644 index dcee001b54..0000000000 --- a/types/mocha/mocha-node.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for mocha 2.2.5 -// Project: http://mochajs.org/ -// Definitions by: Vadim Macagon , vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -declare namespace Mocha { - interface IRunnable extends NodeJS.EventEmitter { - } - interface ISuite extends NodeJS.EventEmitter { - } - interface IRunner extends NodeJS.EventEmitter { - } -} diff --git a/types/mocha/mocha-tests.ts b/types/mocha/mocha-tests.ts index ec9b238d80..b80d7b415d 100644 --- a/types/mocha/mocha-tests.ts +++ b/types/mocha/mocha-tests.ts @@ -3,36 +3,36 @@ import { before as importedBefore, afterEach as importedAfterEach, beforeEach as importedBeforeEach, - context as importedContext, describe as importedDescribe, it as importedIt, - xdescribe as importedXdescribe, - xit as importedXit, + xit as importedXit } from 'mocha'; -// tslint:disable-next-line -import * as Mocha from 'mocha'; +import LocalMocha = require('mocha'); // Warning!! // Don't refer node.d.ts!! // See #22510. (): number => setTimeout(() => 0, 0); -let boolean: boolean; -let string: string; -let number: number; -let stringOrUndefined: string | undefined; -let dateOrUndefined: Date | undefined; -const resolved = Promise.resolve(); -const rejected = Promise.reject('some error'); +declare let number: number; +declare let boolean: boolean; +declare let string: string; +declare let stringOrUndefined: string | undefined; +declare let any: any; -// Use module augmentation to add a third-party interface +// Use module augmentation to add a third-party interface or reporter declare module 'mocha' { interface InterfaceContributions { - 'third-party-interface': any; + 'third-party-interface': never; + } + interface ReporterContributions { + 'third-party-reporter': never; } } -const i: Mocha.Interface = 'third-party-interface'; + +const thirdPartyInterface: Mocha.Interface = 'third-party-interface'; +const thirdPartyReporter: Mocha.Reporter = 'third-party-reporter'; // Lazy tests of compatibility between imported and global functions; should be identical const _after: typeof after = importedAfter; @@ -43,469 +43,786 @@ const _afterEach: typeof afterEach = importedAfterEach; const _afterEach2: typeof importedAfterEach = afterEach; const _beforeEach: typeof beforeEach = importedBeforeEach; const _beforeEach2: typeof importedBeforeEach = beforeEach; -const _context: typeof context = importedContext; -const _context2: typeof importedContext = context; const _describe: typeof describe = importedDescribe; const _describe2: typeof importedDescribe = describe; const _it: typeof it = importedIt; const _it2: typeof importedIt = it; -const _xdescribe: typeof xdescribe = importedXdescribe; -const _xdescribe2: typeof importedXdescribe = xdescribe; const _xit: typeof xit = importedXit; const _xit2: typeof importedXit = xit; -function test_describe() { - describe('something', () => { }); - - describe.only('something', () => { }); - - describe.skip('something', () => { }); - +function test_bdd_describe() { + // $ExpectType Suite describe('something', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); + // $ExpectType Suite + this; + }); + + // $ExpectType Suite + describe.only('something', function() { + // $ExpectType Suite + this; + }); + + // $ExpectType void | Suite + describe.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_context() { - context('some context', () => { }); +function test_bdd_context() { + // $ExpectType Suite + context('something', function() { + // $ExpectType Suite + this; + }); - context.only('some context', () => { }); + // $ExpectType Suite + context.only('something', function() { + // $ExpectType Suite + this; + }); - context.skip('some context', () => { }); - - context('some context', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); + // $ExpectType void | Suite + context.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_suite() { - suite('some context', () => { }); - - suite.only('some context', () => { }); - - suite.skip('some context', () => { }); - - suite('some context', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); +function test_bdd_xdescribe() { + // $ExpectType void | Suite + xdescribe('something', function() { + // $ExpectType Suite + this; }); } -function test_it() { - it('does something', () => { }).timeout('2s'); - - it('does something', function() { this['sharedState'] = true; }); - - it('does something', (done) => { done(); }); - - it('does something', () => resolved); - it('does something', () => rejected); - - it.only('does something', () => { }); - - it.skip('does something', () => { }); - - it('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); +function test_bdd_xcontext() { + // $ExpectType void | Suite + xcontext('something', function() { + // $ExpectType Suite + this; }); } -function test_test() { - test('does something', () => { }); +function test_tdd_suite() { + // $ExpectType Suite + suite('something', function() { + // $ExpectType Suite + this; + }); - test('does something', function() { this['sharedState'] = true; }); + // $ExpectType Suite + suite.only('something', function() { + // $ExpectType Suite + this; + }); - test('does something', (done) => { done(); }); - - test('does something', () => resolved); - test('does something', () => rejected); - - test.only('does something', () => { }); - - test.skip('does something', () => { }); - - test('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); + // $ExpectType void | Suite + suite.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_specify() { - specify('does something', () => { }); +function test_qunit_suite() { + // $ExpectType Suite + suite('some context'); - specify('does something', function() { this['sharedState'] = true; }); + // $ExpectType Suite + suite.only('some context'); +} - specify('does something', (done) => { done(); }); +function test_bdd_it() { + // $ExpectType Test + it(function doesSomething(done) { + // $ExpectType Done + done; - specify('does something', () => resolved); - specify('does something', () => rejected); + // $ExpectType Context + this; + }); - specify.only('does something', () => { }); + // $ExpectType Test + it(async function doesSomething() { + // $ExpectType Context + this; + }); - specify.skip('does something', () => { }); + // $ExpectType Test + it('does something', function(done) { + // $ExpectType Done + done; - specify('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); + // $ExpectType Context + this; + }); + + // $ExpectType Test + it('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + it.retries(number); +} + +function test_bdd_xit() { + // $ExpectType Test + xit(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit('does something', async function() { + // $ExpectType Context + this; }); } -function test_before() { - before(() => { }); +function test_bdd_specify() { + // $ExpectType Test + specify(function doesSomething(done) { + // $ExpectType Done + done; - before(function() { this['sharedState'] = true; }); + // $ExpectType Context + this; + }); - before((done) => { done(); }); + // $ExpectType Test + specify(async function doesSomething() { + // $ExpectType Context + this; + }); - before(() => resolved); - before(() => rejected); + // $ExpectType Test + specify('does something', function(done) { + // $ExpectType Done + done; - before("my description", () => { }); + // $ExpectType Context + this; + }); - before("my description", done => { }); + // $ExpectType Test + specify('does something', async function() { + // $ExpectType Context + this; + }); - before("my description", () => resolved); + // $ExpectType Test + specify.only(function doesSomething(done) { + // $ExpectType Done + done; - before("my description", function() { - this.skip().timeout(2000).skip(); + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + specify.retries(number); +} + +function test_bdd_xspecify() { + // $ExpectType Test + xspecify(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify('does something', async function() { + // $ExpectType Context + this; }); } -function test_setup() { - setup(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; +function test_tdd_qunit_test() { + // $ExpectType Test + test(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; }); - setup(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Test + test(async function doesSomething() { + // $ExpectType Context + this; }); + // $ExpectType Test + test('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + test.retries(number); +} + +function test_bdd_qunit_before() { + before(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + before(async function() { + // $ExpectType Context + this; + }); + + before('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + before('description', async function() { + // $ExpectType Context + this; + }); +} + +function test_tdd_setup() { setup(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - setup(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + setup(async function() { + // $ExpectType Context + this; + }); + + setup('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + setup('description', async function() { + // $ExpectType Context + this; }); } -function test_after() { - after(() => { }); +function test_bdd_qunit_after() { + after(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - after(function() { this['sharedState'] = true; }); + after(async function() { + // $ExpectType Context + this; + }); - after((done) => { done(); }); + after('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - after(() => resolved); - - after("my description", () => { }); - - after("my description", done => { }); - - after("my description", () => resolved); + after('description', async function() { + // $ExpectType Context + this; + }); } -function test_teardown() { - teardown(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - teardown(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_tdd_teardown() { teardown(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - teardown(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + teardown(async function() { + // $ExpectType Context + this; + }); + + teardown('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + teardown('description', async function() { + // $ExpectType Context + this; }); } -function test_beforeEach() { - beforeEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - beforeEach(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_bdd_qunit_beforeEach() { beforeEach(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - beforeEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + beforeEach(async function() { + // $ExpectType Context + this; }); - beforeEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + beforeEach('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; }); - beforeEach("my description", function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - beforeEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + beforeEach('description', async function() { + // $ExpectType Context + this; }); } -function test_suiteSetup() { - suiteSetup(() => { }); +function test_tdd_suiteSetup() { + suiteSetup(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteSetup(function() { this['sharedState'] = true; }); + suiteSetup(async function() { + // $ExpectType Context + this; + }); - suiteSetup((done) => { done(); }); + suiteSetup('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteSetup(() => resolved); + suiteSetup('description', async function() { + // $ExpectType Context + this; + }); } -function test_afterEach() { - afterEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - afterEach(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_bdd_qunit_afterEach() { afterEach(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - afterEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + afterEach(async function() { + // $ExpectType Context + this; }); - afterEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + afterEach('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; }); - afterEach("my description", function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - afterEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + afterEach('description', async function() { + // $ExpectType Context + this; }); } -function test_suiteTeardown() { - suiteTeardown(() => { }); +function test_tdd_suiteTeardown() { + suiteTeardown(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteTeardown(function() { this['sharedState'] = true; }); + suiteTeardown(async function() { + // $ExpectType Context + this; + }); - suiteTeardown((done) => { done(); }); + suiteTeardown('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteTeardown(() => resolved); + suiteTeardown('description', async function() { + // $ExpectType Context + this; + }); } -function test_reporter_string() { +function test_Context(ctx: LocalMocha.Context, runnable: LocalMocha.Runnable) { + // $ExpectType never + ctx.skip(); // throws + + // $ExpectType boolean + ctx.enableTimeouts(); + + // $ExpectType Context + ctx.enableTimeouts(boolean); + + // $ExpectType number + ctx.retries(); + + // $ExpectType Context + ctx.retries(number); + + // $ExpectType Runnable + ctx.runnable(); + + // $ExpectType Context + ctx.runnable(runnable); + + // $ExpectType number + ctx.slow(); + + // $ExpectType Context + ctx.slow(number); + + // $ExpectType number + ctx.timeout(); + + // $ExpectType Context + ctx.timeout(number); + + // $ExpectType Test | undefined + ctx.currentTest; + + // $ExpectType Runnable | undefined + ctx.test; + + ctx["extended"] = any; + + // $ExpectType any + ctx["extended"]; + + ctx.enableTimeouts(boolean) + .retries(number) + .runnable(runnable) + .slow(number) + .timeout(number) + .skip(); +} + +function test_reporter_string(localMocha: LocalMocha) { + // $ExpectType BrowserMocha mocha.reporter('html'); + + // $ExpectType Mocha + localMocha.reporter('html'); } -function test_reporter_function() { - mocha.reporter(class { }); +function test_reporter_function(localMocha: LocalMocha) { + // $ExpectType BrowserMocha + mocha.reporter(class extends LocalMocha.reporters.Base { }); + + // $ExpectType Mocha + localMocha.reporter(class extends LocalMocha.reporters.Base { }); } -function test_setup_slow_option() { - new Mocha({ slow: 25 }); +function test_browser_mocha_setup_slow_option() { + // $ExpectType BrowserMocha + mocha.setup({ slow: 25 }); } -function test_setup_timeout_option() { - new Mocha({ timeout: 25 }); +function test_browser_mocha_setup_timeout_option() { + // $ExpectType BrowserMocha + mocha.setup({ timeout: 25 }); } -function test_setup_globals_option() { - new Mocha({ globals: ['mocha'] }); +function test_browser_mocha_setup_globals_option() { + // $ExpectType BrowserMocha + mocha.setup({ globals: ['mocha'] }); } -function test_setup_ui_option() { - new Mocha({ ui: 'bdd' }); +function test_browser_mocha_setup_ui_option() { + // $ExpectType BrowserMocha + mocha.setup({ ui: 'bdd' }); } -function test_setup_reporter_string_option() { - new Mocha({ reporter: 'html' }); +function test_browser_mocha_setup_reporter_string_option() { + // $ExpectType BrowserMocha + mocha.setup({ reporter: 'html' }); } -function test_setup_require_stringArray_option() { - new Mocha({ require: ['ts-node/register'] }); +function test_browser_mocha_setup_require_stringArray_option() { + // $ExpectType BrowserMocha + mocha.setup({ require: ['ts-node/register'] }); } -function test_setup_reporter_function_option() { - new Mocha({ reporter: class { } }); +function test_browser_mocha_setup_reporter_function_option() { + // $ExpectType BrowserMocha + mocha.setup({ reporter: class extends LocalMocha.reporters.Base { } }); } -function test_setup_bail_option() { - new Mocha({ bail: false }); +function test_browser_mocha_setup_bail_option() { + // $ExpectType BrowserMocha + mocha.setup({ bail: false }); } -function test_setup_ignore_leaks_option() { - new Mocha({ ignoreLeaks: false }); +function test_browser_mocha_setup_ignore_leaks_option() { + // $ExpectType BrowserMocha + mocha.setup({ ignoreLeaks: false }); } -function test_setup_grep_string_option() { - new Mocha({ grep: "describe" }); +function test_browser_mocha_setup_grep_string_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: "describe" }); } -function test_setup_grep_regex_option() { - new Mocha({ grep: new RegExp('describe') }); +function test_browser_mocha_setup_grep_regex_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: new RegExp('describe') }); } -function test_setup_grep_regex_literal_option() { - new Mocha({ grep: /(expect|should)/i }); +function test_browser_mocha_setup_grep_regex_literal_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: /(expect|should)/i }); } -function test_setup_all_options() { - new Mocha({ +function test_browser_mocha_setup_all_options() { + // $ExpectType BrowserMocha + mocha.setup({ slow: 25, timeout: 25, ui: 'bdd', @@ -514,12 +831,97 @@ function test_setup_all_options() { bail: true, ignoreLeaks: true, grep: 'test', - require: ['ts-node/register'] + require: ['ts-node/register'] // TODO: It doesn't appear this is actually supported. Should it be removed? }); } -function test_run() { - mocha.run(() => {}); +function test_constructor_slow_option() { + // $ExpectType Mocha + new LocalMocha({ slow: 25 }); +} + +function test_constructor_timeout_option() { + // $ExpectType Mocha + new LocalMocha({ timeout: 25 }); +} + +function test_constructor_globals_option() { + // $ExpectType Mocha + new LocalMocha({ globals: ['mocha'] }); +} + +function test_constructor_ui_option() { + // $ExpectType Mocha + new LocalMocha({ ui: 'bdd' }); +} + +function test_constructor_reporter_string_option() { + // $ExpectType Mocha + new LocalMocha({ reporter: 'html' }); +} + +function test_constructor_reporter_function_option() { + // $ExpectType Mocha + new LocalMocha({ reporter: class extends LocalMocha.reporters.Base { } }); +} + +function test_constructor_bail_option() { + // $ExpectType Mocha + new LocalMocha({ bail: false }); +} + +function test_constructor_ignore_leaks_option() { + // $ExpectType Mocha + new LocalMocha({ ignoreLeaks: false }); +} + +function test_constructor_grep_string_option() { + // $ExpectType Mocha + new LocalMocha({ grep: "describe" }); +} + +function test_constructor_grep_regex_option() { + // $ExpectType Mocha + new LocalMocha({ grep: new RegExp('describe') }); +} + +function test_constructor_grep_regex_literal_option() { + // $ExpectType Mocha + new LocalMocha({ grep: /(expect|should)/i }); +} + +function test_constructor_all_options() { + // $ExpectType Mocha + new LocalMocha({ + slow: 25, + timeout: 25, + ui: 'bdd', + globals: ['mocha'], + reporter: 'html', + bail: true, + ignoreLeaks: true, + grep: 'test' + }); +} + +function test_run(localMocha: LocalMocha) { + // $ExpectType Runner + mocha.run(); + + // $ExpectType Runner + mocha.run((failures) => { + // $ExpectType number + failures; + }); + + // $ExpectType Runner + localMocha.run(); + + // $ExpectType Runner + localMocha.run((failures) => { + // $ExpectType number + failures; + }); } function test_growl() { @@ -527,24 +929,22 @@ function test_growl() { } function test_chaining() { - new Mocha({ slow: 25 }) + new LocalMocha({ slow: 25 }) .growl() .reporter('html') - .reporter(class { }); + .reporter(class extends LocalMocha.reporters.Base { }); } -import MochaDef = require('mocha'); - function test_require_constructor_empty() { - const instance = new MochaDef(); + const instance = new LocalMocha(); } function test_require_constructor_noOptions() { - const instance = new MochaDef({}); + const instance = new LocalMocha({}); } function test_require_constructor_allOptions() { - const instance = new MochaDef({ + const instance = new LocalMocha({ grep: /[a-z]*/, ui: 'tdd', reporter: 'dot', @@ -554,13 +954,13 @@ function test_require_constructor_allOptions() { } function test_require_fluentParams() { - const instance = new MochaDef(); + const instance = new LocalMocha(); instance.bail(true) .bail() .addFile('foo.js') - .reporter('bdd') - .ui('dot') + .reporter('dot') + .ui('bdd') .grep('[a-z]*') .grep(/[a-z]*/) .invert() @@ -574,60 +974,290 @@ function test_require_fluentParams() { .timeout(500) .slow(100) .enableTimeouts(true) - .asyncOnly(false) - .noHighlighting(true) + .asyncOnly() + .noHighlighting() .run(); } -function test_run_withOnComplete() { - const instance = new MochaDef(); - - instance.run((failures: number): void => { - console.log(failures); - }); -} - function test_throwError() { mocha.throwError(new Error("I'm an error!")); } -function test_mochaRunner_properties(runner: MochaDef.IRunner, suite: MochaDef.ISuite) { - runner = runner.abort(); +function test_mochaRunner_properties(runner: LocalMocha.Runner, suite: LocalMocha.Suite) { + // $Expecttype Runner + runner.abort(); - if (runner.stats !== undefined) { - number = runner.stats.failures; - number = runner.stats.passes; - number = runner.stats.pending; - number = runner.stats.suites; - number = runner.stats.tests; + // $ExpectType Suite + runner.suite; - dateOrUndefined = runner.stats.start; - dateOrUndefined = runner.stats.end; - dateOrUndefined = runner.stats.duration; - } + // $ExpectType boolean + runner.started; - const s: MochaDef.ISuite = runner.suite; - boolean = runner.started; - number = runner.total; - number = runner.failures; + // $ExpectType number + runner.total; - runner = runner.grep("regex", false); - number = runner.grepTotal(suite); + // $ExpectType number + runner.failures; - const globals: string[] | MochaDef.IRunner = runner.globals(["hello", "world"]); + // $ExpectType Runner + runner.grep(/regex/, false); - runner = runner.run(); - runner = runner.run((f: number) => {}); + // $ExpectType number + runner.grepTotal(suite); + + // $ExpectType string[] + runner.globals(); + + // $ExpectType Runner + runner.globals(["hello", "world"]); + + // $ExpectType Runner + runner.run(); + + // $ExpectType Runner + runner.run((failures) => { + // $ExpectType number + failures; + }); } -function test_base_reporter_properties(reporter: MochaDef.reporters.Base) { - number = reporter.stats.failures; - number = reporter.stats.passes; - number = reporter.stats.pending; - number = reporter.stats.suites; - number = reporter.stats.tests; +function test_base_reporter_properties(reporter: LocalMocha.reporters.Base) { + // $ExpectType number + reporter.stats.failures; - dateOrUndefined = reporter.stats.start; - dateOrUndefined = reporter.stats.end; - dateOrUndefined = reporter.stats.duration; + // $ExpectType number + reporter.stats.passes; + + // $ExpectType number + reporter.stats.pending; + + // $ExpectType number + reporter.stats.suites; + + // $ExpectType number + reporter.stats.tests; + + // $ExpectType Date | undefined + reporter.stats.start; + + // $ExpectType Date | undefined + reporter.stats.end; + + // $ExpectType number | undefined + reporter.stats.duration; +} + +function test_runner_events(runner: LocalMocha.Runner) { + // $ExpectType Runner + runner.on("start", () => {}); + + // $ExpectType Runner + runner.on("end", () => {}); + + // $ExpectType Runner + runner.on("suite", (suite) => { + // $ExpectType Suite + suite; + }); + + // $ExpectType Runner + runner.on("suite end", (suite) => { + // $ExpectType Suite + suite; + }); + + // $ExpectType Runner + runner.on("test", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("test end", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("hook", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Runner + runner.on("hook end", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Runner + runner.on("pass", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("fail", (test, err) => { + // $ExpectType Test + test; + + // $ExpectType any + err; + }); + + // $ExpectType Runner + runner.on("pending", (test) => { + // $ExpectType Test + test; + }); +} + +function test_runnable_events(runnable: LocalMocha.Runnable) { + // $ExpectType Runnable + runnable.on("error", (error) => { + // $ExpectType any + error; + }); +} + +function test_suite_events(suite: LocalMocha.Suite) { + // $ExpectType Suite + suite.on("beforeAll", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("afterAll", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("beforeEach", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("afterEach", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("run", () => { }); + + // $ExpectType Suite + suite.on("pre-require", (context, file, mocha) => { + // $ExpectType MochaGlobals + context; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); + + // $ExpectType Suite + suite.on("require", (module, file, mocha) => { + // $ExpectType any + module; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); + + // $ExpectType Suite + suite.on("post-require", (context, file, mocha) => { + // $ExpectType MochaGlobals + context; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); +} + +function test_backcompat_Suite(suite: Mocha.Suite, iSuite: Mocha.ISuite, iSuiteContext: Mocha.ISuiteCallbackContext, iTest: Mocha.ITest, iContext: Mocha.IContext) { + iSuite = suite; + iSuiteContext = suite; + suite.addTest(iTest); + suite.addSuite(iSuite); + LocalMocha.Suite.create(iSuite, string); + new LocalMocha.Suite(string, iContext); +} + +function test_backcompat_Runner(runner: Mocha.Runner, iRunner: Mocha.IRunner, iSuite: Mocha.ISuite) { + iRunner = runner; + runner.grepTotal(iSuite); +} + +function test_backcompat_Runnable(runnable: Mocha.Runnable, iRunnable: Mocha.IRunnable) { + iRunnable = runnable; +} + +function test_backcompat_Test(test: Mocha.Test, iTest: Mocha.ITest) { + iTest = test; +} + +function test_backcompat_Hook(hook: Mocha.Hook, iHook: Mocha.IHook) { + iHook = hook; +} + +function test_backcompat_Context(context: Mocha.Context, iContext: Mocha.IContext, + iHookContext: Mocha.IHookCallbackContext, iBeforeAfterContext: Mocha.IBeforeAndAfterContext, + iTestContext: Mocha.ITestCallbackContext, iRunnable: Mocha.IRunnable) { + iContext = context; + iHookContext = context; + iBeforeAfterContext = context; + iTestContext = context; + context.runnable(iRunnable); +} + +function test_backcompat_Base(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.Base(iRunner); +} + +function test_backcompat_XUnit(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.XUnit(iRunner); +} + +function test_backcompat_Progress(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.Progress(iRunner); +} + +import common = require("mocha/lib/interfaces/common"); + +function test_interfaces_common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, localMocha: Mocha, + fn: Mocha.Func | Mocha.AsyncFunc, test: Mocha.Test) { + const funcs = common(suites, context, localMocha); + // $ExpectType CommonFunctions + funcs; + + funcs.before(fn); + funcs.before(string, fn); + funcs.beforeEach(fn); + funcs.beforeEach(string, fn); + funcs.after(fn); + funcs.after(string, fn); + funcs.afterEach(fn); + funcs.afterEach(string, fn); + + // $ExpectType Suite + funcs.suite.create({ title: string }); + funcs.suite.create({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Suite + funcs.suite.only({ title: string }); + funcs.suite.only({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Suite + funcs.suite.skip({ title: string }); + funcs.suite.skip({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Test + funcs.test.only(mocha, test); + funcs.test.skip(string); + funcs.test.retries(number); } diff --git a/types/mocha/tsconfig.json b/types/mocha/tsconfig.json index 6e88356fe4..f26091927f 100644 --- a/types/mocha/tsconfig.json +++ b/types/mocha/tsconfig.json @@ -19,6 +19,8 @@ }, "files": [ "index.d.ts", + "lib/ms.d.ts", + "lib/interfaces/common.d.ts", "mocha-tests.ts" ] } \ No newline at end of file diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 59a5c95989..a94f3a691d 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -103,7 +103,10 @@ declare module "mongoose" { export function createConnection(): Connection; export function createConnection(uri: string, options?: ConnectionOptions - ): Connection; + ): Connection & { + then: Promise["then"]; + catch: Promise["catch"]; + }; /** * Disconnects all connections. @@ -201,7 +204,7 @@ declare module "mongoose" { */ open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - + /** * Opens the connection to MongoDB. * @param mongodb://uri or the host to which you are connecting @@ -451,9 +454,6 @@ declare module "mongoose" { /** Expose the possible connection states. */ static STATES: any; - - then: Promise["then"]; - catch: Promise["catch"]; } /* @@ -2727,9 +2727,9 @@ declare module "mongoose" { * This function does not trigger save middleware. * @param docs Documents to insert. * @param options Optional settings. - * @param options.ordered if true, will fail fast on the first error encountered. + * @param options.ordered if true, will fail fast on the first error encountered. * If false, will insert all the documents it can and report errors later. - * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. + * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. * If `false`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 90b6fc2561..90259483f2 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -161,6 +161,13 @@ mongoose.Connection.STATES.hasOwnProperty(''); conn1.on('data', cb); conn1.addListener('close', cb); +// The connection returned by useDb is *not* thenable. +// From https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26057#issuecomment-396150819 +const getDB = async (tenant: string)=> { + return conn1.useDb(tenant); +}; + + /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js diff --git a/types/multer/index.d.ts b/types/multer/index.d.ts index d019b9fdcb..7d2bfefc26 100644 --- a/types/multer/index.d.ts +++ b/types/multer/index.d.ts @@ -71,6 +71,8 @@ declare namespace multer { fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ any(): express.RequestHandler; + /** Accept only text fields. If any file upload is made, error with code “LIMIT_UNEXPECTED_FILE” will be issued. This is the same as doing upload.fields([]). */ + none(): express.RequestHandler; } } diff --git a/types/next/app.d.ts b/types/next/app.d.ts new file mode 100644 index 0000000000..18bca653cf --- /dev/null +++ b/types/next/app.d.ts @@ -0,0 +1,18 @@ +import * as React from "react"; +import { NextContext } from "."; +import { SingletonRouter } from "./router"; + +export interface AppComponentProps { + Component: React.ComponentType; + pageProps: any; +} + +export interface AppComponentContext { + Component: React.ComponentType; + router: SingletonRouter; + ctx: NextContext; +} + +export class Container extends React.Component {} + +export default class App extends React.Component {} diff --git a/types/next/document.d.ts b/types/next/document.d.ts index b8ae0864ba..38e20e00c0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,30 +1,5 @@ import * as React from "react"; -import * as http from "http"; - -export interface Context { - err?: Error; - req: http.IncomingMessage; - res: http.ServerResponse; - pathname: string; - query?: { - [key: string]: - | boolean - | boolean[] - | number - | number[] - | string - | string[]; - }; - asPath: string; - - renderPage( - enhancer?: (page: React.Component) => React.ComponentType - ): { - html?: string; - head: Array>; - errorHtml: string; - }; -} +import { NextContext } from "."; export interface DocumentProps { __NEXT_DATA__?: any; @@ -38,9 +13,21 @@ export interface DocumentProps { [key: string]: any; } +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage( + cb?: (enhancer: () => JSX.Element) => React.ComponentType + ): { + [key: string]: any + }; +} + export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} export default class extends React.Component { - static getInitialProps(ctx: Context): DocumentProps; + static getInitialProps(ctx: NextContext): DocumentProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index fe44537f5f..95395bc2b8 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for next 2.4 +// Type definitions for next 6.0 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Brice BERNARD +// James Hegedus +// Resi Respati // Scott Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -11,7 +13,44 @@ import * as http from "http"; import * as url from "url"; +import { Response as NodeResponse } from "node-fetch"; + declare namespace next { + /** + * Context object used in methods like `getInitialProps()` + * <> + */ + interface NextContext { + /** path section of URL */ + pathname: string; + /** query string section of URL parsed as an object */ + query: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + /** String of the actual path (including the query) shows in the browser */ + asPath: string; + /** HTTP request object (server only) */ + req?: http.IncomingMessage; + /** HTTP response object (server only) */ + res?: http.ServerResponse; + /** Fetch Response object (client only) - from https://developer.mozilla.org/en-US/docs/Web/API/Response */ + jsonPageRes?: NodeResponse; + /** Error object if any error is encountered during the rendering */ + err?: Error; + } + + type NextSFC = NextStatelessComponent; + interface NextStatelessComponent + extends React.StatelessComponent { + getInitialProps?: (ctx: NextContext) => Promise; + } + type UrlLike = url.UrlObject | url.Url; interface ServerConfig { @@ -41,12 +80,12 @@ declare namespace next { handleRequest( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; getRequestHandler(): ( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ) => Promise; prepare(): Promise; close(): Promise; @@ -55,7 +94,7 @@ declare namespace next { run( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; render( @@ -71,7 +110,7 @@ declare namespace next { | string | string[]; }, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; renderError( err: any, @@ -86,12 +125,12 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; render404( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; renderToHTML( req: http.IncomingMessage, @@ -105,7 +144,7 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; renderErrorToHTML( err: any, @@ -120,13 +159,13 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; serveStatic( req: http.IncomingMessage, res: http.ServerResponse, - path: string, + path: string ): Promise; isServeableUrl(path: string): boolean; isInternalUrl(req: http.IncomingMessage): boolean; @@ -135,12 +174,12 @@ declare namespace next { getCompilationError( page: string, req: http.IncomingMessage, - res: http.ServerResponse, + res: http.ServerResponse ): Promise; handleBuildHash( filename: string, hash: string, - res: http.ServerResponse, + res: http.ServerResponse ): void; send404(res: http.ServerResponse): void; } diff --git a/types/next/test/next-app-tests.tsx b/types/next/test/next-app-tests.tsx new file mode 100644 index 0000000000..3e7c56f87c --- /dev/null +++ b/types/next/test/next-app-tests.tsx @@ -0,0 +1,27 @@ +import * as React from "react"; +import App, { Container } from "next/app"; + +interface NextComponentProps { + example: string; +} + +class TestApp extends App { + static async getInitialProps({ Component, router, ctx }: any) { + let pageProps = {}; + + if (Component.getInitialProps) { + pageProps = await Component.getInitialProps(ctx); + } + + return { pageProps }; + } + + render() { + const { Component, pageProps } = this.props; + return ( + + + + ); + } +} diff --git a/types/next/test/next-component-tests.tsx b/types/next/test/next-component-tests.tsx new file mode 100644 index 0000000000..55173fd25c --- /dev/null +++ b/types/next/test/next-component-tests.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import { NextStatelessComponent, NextContext } from "next"; + +interface NextComponentProps { + example: string; +} + +class ClassNext extends React.Component { + static async getInitialProps(ctx: NextContext) { + const { example } = ctx.query; + return { example }; + } + + render() { + return ( +
I'm a class component! {this.props.example}
+ ); + } +} + +const StatelessNext: NextStatelessComponent = ({ example }) => ( +
I'm a stateless component! {example}
+); + +StatelessNext.getInitialProps = async ({ query }: NextContext) => { + const { example } = query; + return { example: example as string }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 0177d1d451..2b3257cd25 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,40 @@ -import Document, * as document from "next/document"; +import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as React from "react"; const results = ( - + - - - + +
+ ); + +const Wrapper: React.SFC = ({ children }) => {children}; + +export default class MyDocument extends Document { + static async getInitialProps({ renderPage }: NextDocumentContext) { + // Without callback + const page = renderPage(); + // With callback + const differentPage = renderPage(App => props => ); + const style = {}; + return { ...page, style }; + } + + render() { + return ( + + + My page +