diff --git a/analytics-node/analytics-node-tests.ts b/analytics-node/analytics-node-tests.ts index acefd108b6..594c15fae6 100644 --- a/analytics-node/analytics-node-tests.ts +++ b/analytics-node/analytics-node-tests.ts @@ -1,10 +1,8 @@ - - +import AnalyticsNode = require("analytics-node"); var analytics: AnalyticsNode.Analytics; -import Analytics = require("analytics-node"); function testConfig(): void { - analytics = new Analytics('YOUR_WRITE_KEY', { + analytics = new AnalyticsNode.Analytics('YOUR_WRITE_KEY', { flushAt: 20, flushAfter: 10000 }); diff --git a/analytics-node/index.d.ts b/analytics-node/index.d.ts index aed257c9cc..455b13c92b 100644 --- a/analytics-node/index.d.ts +++ b/analytics-node/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Andrew Fong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = AnalyticsNode; + declare namespace AnalyticsNode { interface Integrations { @@ -77,7 +79,3 @@ declare namespace AnalyticsNode { }) => void): Analytics; } } - -declare module "analytics-node" { - export = AnalyticsNode.Analytics; -} diff --git a/angular-dynamic-locale/angular-dynamic-locale-tests.ts b/angular-dynamic-locale/angular-dynamic-locale-tests.ts index 3a4cc06e25..968d4995e8 100644 --- a/angular-dynamic-locale/angular-dynamic-locale-tests.ts +++ b/angular-dynamic-locale/angular-dynamic-locale-tests.ts @@ -1,3 +1,4 @@ +import * as angular from 'angularjs'; var app = angular.module('testModule', ['tmh.dynamicLocale']); app.config((localStorageServiceProvider: angular.dynamicLocale.tmhDynamicLocaleProvider) => { localStorageServiceProvider diff --git a/angular-dynamic-locale/index.d.ts b/angular-dynamic-locale/index.d.ts index 5d84e60757..13bf9d795f 100644 --- a/angular-dynamic-locale/index.d.ts +++ b/angular-dynamic-locale/index.d.ts @@ -5,22 +5,23 @@ /// -declare module "angular-dynamic-locale" { - import ng = angular.dynamicLocale; - export = ng; -} +import * as angular from 'angularjs'; -declare namespace angular.dynamicLocale { +declare module 'angularjs' { + export namespace dynamicLocale { - interface tmhDynamicLocaleService { - set(locale: string): void; - get(): string; - } + interface tmhDynamicLocaleService { + set(locale: string): void; + get(): string; + } - interface tmhDynamicLocaleProvider extends angular.IServiceProvider { - localeLocationPattern(location: string): tmhDynamicLocaleProvider; - localeLocationPattern(): string; - useStorage(storageName: string): void; - useCookieStorage(): void; + interface tmhDynamicLocaleProvider extends angular.IServiceProvider { + localeLocationPattern(location: string): tmhDynamicLocaleProvider; + localeLocationPattern(): string; + useStorage(storageName: string): void; + useCookieStorage(): void; + } } } + + diff --git a/angular-locker/angular-locker-tests.ts b/angular-locker/angular-locker-tests.ts index 266f51825e..e7076d11bd 100644 --- a/angular-locker/angular-locker-tests.ts +++ b/angular-locker/angular-locker-tests.ts @@ -1,5 +1,7 @@ +import * as angular from 'angularjs'; + angular -.module('angular-locker-tests', ['angular-locker']) + .module('angular-locker-tests', ['angular-locker']) .config(['lockerProvider', function config(lockerProvider: angular.locker.ILockerProvider) { let lockerSettings: angular.locker.ILockerSettings = { driver: 'session', diff --git a/angular-locker/index.d.ts b/angular-locker/index.d.ts index 1c1d13d6fb..89816d97dd 100644 --- a/angular-locker/index.d.ts +++ b/angular-locker/index.d.ts @@ -5,166 +5,165 @@ /// -declare module "angular-locker" { - var _: string; - export = _; -} +import * as angular from 'angularjs'; -declare namespace angular.locker { - interface ILockerServicePutFunction { - (current: any): any - } +declare module 'angularjs' { + export namespace locker { + interface ILockerServicePutFunction { + (current: any): any + } - interface ILockerService { - /** - * Add an item to storage if it doesn't already exist - * - * @param {String} key The key to add - * @param {Mixed} value The value to add - */ - add(key: string, value: any): boolean; - /** - * Return all items in storage within the current namespace/driver - * - */ - all(): any; - /** - * Remove all items set within the current namespace/driver - */ - clean(): ILockerService; - /** - * Get the total number of items within the current namespace - */ - count(): number; - /** - * Retrieve the specified item from storage - * - * @param {String|Array} key The key to get - * @param {Mixed} def The default value if it does not exist - */ - get(key: string | Array, defaultValue?: any): any; - /** - * Determine whether the item exists in storage - * - * @param {String|Function} key - The key to remove - */ - has(key: string): boolean - /** - * Get the storage keys as an array - */ - keys(): Array; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Object} keyValuePairs Key value object - */ - put(keyValuePairs: Object): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} putFunction The default to pass to function if doesn't already exist - */ - put(putFunction: Function): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} key The key to add - * @param {Mixed} value The value to add - */ - put(key: string, value: any): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} key The key to add - * @param {Mixed} putFunction The default to pass to function if doesn't already exist - * @param {Mixed} value The value to add - */ - put(key: string, putFunction: ILockerServicePutFunction, value: any): ILockerService | boolean; - /** - * Remove specified item(s) from storage - * - * @param {String} key The key to remove - */ - forget(key: string): ILockerService; - /** - * Remove specified item(s) from storage - * - * @param {Array} keys The array of keys to remove - * - */ - forget(keys: Array): ILockerService; - /** - * Retrieve the specified item from storage and then remove it - * - * @param {String|Array} key The key to pull from storage - * @param {Mixed} def The default value if it does not exist - */ - pull(key: string | Array, defaultValue?: any): any; - /** - * Bind a storage key to a $scope property - * - * @param {Object} $scope The angular $scope object - * @param {String} key The key in storage to bind to - * @param {Mixed} def The default value to initially bind - */ - bind(scope: IScope, property: string, defaultPropertyValue?: any): ILockerService; - /** - * Set the storage driver on a new instance to enable overriding defaults - * - * @param {String} driver The driver to switch to - */ - driver(localStorageType: string): ILockerService; - /** - * Empty the current storage driver completely. careful now. - */ - empty(): ILockerService; - /** - * Get the currently set namespace - */ - getNamespace(): string; - /** - * Get a new instance of Locker - * - * @param {Object} options The config options to instantiate with - */ - instance(lockerSettings: ILockerSettings): ILockerService; - /** - * Set the namespace on a new instance to enable overriding defaults - * - * @param {String} namespace The namespace to switch to - */ - 'namespace'(name: string): ILockerService; - /** - * Check browser support - * - * @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47 - * - * @param {String} driver The driver to check support with - */ - supported(): boolean; - /** - * Unbind a storage key from a $scope property - * - * @param {Object} $scope The angular $scope object - * @param {String} key The key to remove from bindings - */ - unbind(scope: IScope, property: string): ILockerService; - } + interface ILockerService { + /** + * Add an item to storage if it doesn't already exist + * + * @param {String} key The key to add + * @param {Mixed} value The value to add + */ + add(key: string, value: any): boolean; + /** + * Return all items in storage within the current namespace/driver + * + */ + all(): any; + /** + * Remove all items set within the current namespace/driver + */ + clean(): ILockerService; + /** + * Get the total number of items within the current namespace + */ + count(): number; + /** + * Retrieve the specified item from storage + * + * @param {String|Array} key The key to get + * @param {Mixed} def The default value if it does not exist + */ + get(key: string | Array, defaultValue?: any): any; + /** + * Determine whether the item exists in storage + * + * @param {String|Function} key - The key to remove + */ + has(key: string): boolean + /** + * Get the storage keys as an array + */ + keys(): Array; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Object} keyValuePairs Key value object + */ + put(keyValuePairs: Object): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} putFunction The default to pass to function if doesn't already exist + */ + put(putFunction: Function): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} key The key to add + * @param {Mixed} value The value to add + */ + put(key: string, value: any): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} key The key to add + * @param {Mixed} putFunction The default to pass to function if doesn't already exist + * @param {Mixed} value The value to add + */ + put(key: string, putFunction: ILockerServicePutFunction, value: any): ILockerService | boolean; + /** + * Remove specified item(s) from storage + * + * @param {String} key The key to remove + */ + forget(key: string): ILockerService; + /** + * Remove specified item(s) from storage + * + * @param {Array} keys The array of keys to remove + * + */ + forget(keys: Array): ILockerService; + /** + * Retrieve the specified item from storage and then remove it + * + * @param {String|Array} key The key to pull from storage + * @param {Mixed} def The default value if it does not exist + */ + pull(key: string | Array, defaultValue?: any): any; + /** + * Bind a storage key to a $scope property + * + * @param {Object} $scope The angular $scope object + * @param {String} key The key in storage to bind to + * @param {Mixed} def The default value to initially bind + */ + bind(scope: IScope, property: string, defaultPropertyValue?: any): ILockerService; + /** + * Set the storage driver on a new instance to enable overriding defaults + * + * @param {String} driver The driver to switch to + */ + driver(localStorageType: string): ILockerService; + /** + * Empty the current storage driver completely. careful now. + */ + empty(): ILockerService; + /** + * Get the currently set namespace + */ + getNamespace(): string; + /** + * Get a new instance of Locker + * + * @param {Object} options The config options to instantiate with + */ + instance(lockerSettings: ILockerSettings): ILockerService; + /** + * Set the namespace on a new instance to enable overriding defaults + * + * @param {String} namespace The namespace to switch to + */ + 'namespace'(name: string): ILockerService; + /** + * Check browser support + * + * @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47 + * + * @param {String} driver The driver to check support with + */ + supported(): boolean; + /** + * Unbind a storage key from a $scope property + * + * @param {Object} $scope The angular $scope object + * @param {String} key The key to remove from bindings + */ + unbind(scope: IScope, property: string): ILockerService; + } - interface ILockerSettings { - driver?: string; - 'namespace'?: string | boolean; - separator?: string; - eventsEnabled?: boolean; - extend?: Object; - } + interface ILockerSettings { + driver?: string; + 'namespace'?: string | boolean; + separator?: string; + eventsEnabled?: boolean; + extend?: Object; + } - interface ILockerProvider extends angular.IServiceProvider { - /** - * Allow the defaults to be specified via the `lockerProvider` - * - * @param {ILockerSettings} lockerSettings The defaults to override - */ - defaults(lockerSettings: ILockerSettings): void; + interface ILockerProvider extends angular.IServiceProvider { + /** + * Allow the defaults to be specified via the `lockerProvider` + * + * @param {ILockerSettings} lockerSettings The defaults to override + */ + defaults(lockerSettings: ILockerSettings): void; + } } } diff --git a/angular-toastr/angular-toastr-tests.ts b/angular-toastr/angular-toastr-tests.ts index 6cb4290b3c..ba11179df0 100644 --- a/angular-toastr/angular-toastr-tests.ts +++ b/angular-toastr/angular-toastr-tests.ts @@ -1,3 +1,5 @@ +import * as angular from 'angularjs'; + angular .module('toastr-tests', ['toastr']) .config(function(toastrConfig: angular.toastr.IToastrConfig) { diff --git a/angular-toastr/index.d.ts b/angular-toastr/index.d.ts index 8e95e336bc..7c9e40a420 100644 --- a/angular-toastr/index.d.ts +++ b/angular-toastr/index.d.ts @@ -5,118 +5,117 @@ /// -declare module "angular-toastr" { - var _: string; - export = _; -} +import * as angular from 'angularjs'; -declare namespace angular.toastr { - interface IToastBaseConfig { - allowHtml?: boolean; - closeButton?: boolean; - closeHtml?: string; - extendedTimeOut?: number; - messageClass?: string; - onHidden?: Function; - onShown?: Function; - onTap?: Function; - progressBar?: boolean; - tapToDismiss?: boolean; - templates?: { - toast?: string; - progressbar?: string; - }; - timeOut?: number; - titleClass?: string; - toastClass?: string; - } +declare module 'angularjs' { + export namespace toastr { + interface IToastBaseConfig { + allowHtml?: boolean; + closeButton?: boolean; + closeHtml?: string; + extendedTimeOut?: number; + messageClass?: string; + onHidden?: Function; + onShown?: Function; + onTap?: Function; + progressBar?: boolean; + tapToDismiss?: boolean; + templates?: { + toast?: string; + progressbar?: string; + }; + timeOut?: number; + titleClass?: string; + toastClass?: string; + } - interface IToastContainerConfig { - autoDismiss?: boolean; - containerId?: string; - maxOpened?: number; - newestOnTop?: boolean; - positionClass?: string; - preventDuplicates?: boolean; - preventOpenDuplicates?: boolean; - target?: string; - } + interface IToastContainerConfig { + autoDismiss?: boolean; + containerId?: string; + maxOpened?: number; + newestOnTop?: boolean; + positionClass?: string; + preventDuplicates?: boolean; + preventOpenDuplicates?: boolean; + target?: string; + } - interface IToastConfig extends IToastBaseConfig { - iconClasses?: { - error?: string; - info?: string; - success?: string; - warning?: string; - }; - } + interface IToastConfig extends IToastBaseConfig { + iconClasses?: { + error?: string; + info?: string; + success?: string; + warning?: string; + }; + } - interface IToastrConfig extends IToastContainerConfig, IToastConfig { } + interface IToastrConfig extends IToastContainerConfig, IToastConfig { } - interface IToastScope extends angular.IScope { - message: string; - options: IToastConfig; - title: string; - toastId: number; - toastType: string; - } + interface IToastScope extends angular.IScope { + message: string; + options: IToastConfig; + title: string; + toastId: number; + toastType: string; + } - interface IToast { - el: angular.IAugmentedJQuery; - iconClass: string; - isOpened: boolean; - open: angular.IPromise; - scope: IToastScope; - toastId: number; - } + interface IToast { + el: angular.IAugmentedJQuery; + iconClass: string; + isOpened: boolean; + open: angular.IPromise; + scope: IToastScope; + toastId: number; + } - interface IToastOptions extends IToastBaseConfig { - iconClass?: string; - target?: string; - } + interface IToastOptions extends IToastBaseConfig { + iconClass?: string; + target?: string; + } - interface IToastrService { - /** - * Return the number of active toasts in screen. - */ - active(): number; - /** - * Remove toast from screen. If no toast is passed in, all toasts will be closed. - * - * @param {IToast} toast Optional toast object to delete - */ - clear(toast?: IToast): void; - /** - * Create error toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - error(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create info toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - info(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create success toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - success(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create warning toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - warning(message: string, title?: string, options?: IToastOptions): IToast; + interface IToastrService { + /** + * Return the number of active toasts in screen. + */ + active(): number; + /** + * Remove toast from screen. If no toast is passed in, all toasts will be closed. + * + * @param {IToast} toast Optional toast object to delete + */ + clear(toast?: IToast): void; + /** + * Create error toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + error(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create info toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + info(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create success toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + success(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create warning toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + warning(message: string, title?: string, options?: IToastOptions): IToast; + } } } diff --git a/angular-touchspin/angular-touchspin-tests.ts b/angular-touchspin/angular-touchspin-tests.ts index a37837ad9c..ed7fd0a2ca 100644 --- a/angular-touchspin/angular-touchspin-tests.ts +++ b/angular-touchspin/angular-touchspin-tests.ts @@ -1,4 +1,4 @@ - +import angularTouchSpin = require("angular-touchspin"); angular .module('touchspin-tests', ['lm.touchspin']) diff --git a/angular-touchspin/index.d.ts b/angular-touchspin/index.d.ts index 3a2ee0f0c4..f4ad318a77 100644 --- a/angular-touchspin/index.d.ts +++ b/angular-touchspin/index.d.ts @@ -5,10 +5,8 @@ /// -declare module "angular-touchspin" { - let _: string; - export = _; -} +declare let angularTouchSpin: string; +export = angularTouchSpin; declare namespace angularTouchSpin { interface ITouchSpinOptions { diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 9eeee57b00..f1ab855e63 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -1,4 +1,5 @@ - +import * as ng from 'angularjs'; +import * as angular from 'angularjs'; var myApp = angular.module('testModule'); diff --git a/angular-ui-router/index.d.ts b/angular-ui-router/index.d.ts index c3a8fb52cc..7d36968165 100644 --- a/angular-ui-router/index.d.ts +++ b/angular-ui-router/index.d.ts @@ -3,367 +3,368 @@ // Definitions by: Michel Salib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as angular from 'angularjs'; // Support for AMD require and CommonJS -declare module 'angular-ui-router' { - // Since angular-ui-router adds providers for a bunch of - // injectable dependencies, it doesn't really return any - // actual data except the plain string 'ui.router'. - // - // As such, I don't think anybody will ever use the actual - // default value of the module. So I've only included the - // the types. (@xogeny) - export type IState = angular.ui.IState; - export type IStateProvider = angular.ui.IStateProvider; - export type IUrlMatcher = angular.ui.IUrlMatcher; - export type IUrlRouterProvider = angular.ui.IUrlRouterProvider; - export type IStateOptions = angular.ui.IStateOptions; - export type IHrefOptions = angular.ui.IHrefOptions; - export type IStateService = angular.ui.IStateService; - export type IResolvedState = angular.ui.IResolvedState; - export type IStateParamsService = angular.ui.IStateParamsService; - export type IUrlRouterService = angular.ui.IUrlRouterService; - export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider; - export type IType = angular.ui.IType; -} +// Since angular-ui-router adds providers for a bunch of +// injectable dependencies, it doesn't really return any +// actual data except the plain string 'ui.router'. +// +// As such, I don't think anybody will ever use the actual +// default value of the module. So I've only included the +// the types. (@xogeny) +export type IState = angular.ui.IState; +export type IStateProvider = angular.ui.IStateProvider; +export type IUrlMatcher = angular.ui.IUrlMatcher; +export type IUrlRouterProvider = angular.ui.IUrlRouterProvider; +export type IStateOptions = angular.ui.IStateOptions; +export type IHrefOptions = angular.ui.IHrefOptions; +export type IStateService = angular.ui.IStateService; +export type IResolvedState = angular.ui.IResolvedState; +export type IStateParamsService = angular.ui.IStateParamsService; +export type IUrlRouterService = angular.ui.IUrlRouterService; +export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider; +export type IType = angular.ui.IType; -declare namespace angular.ui { - - interface IState { - name?: string; - /** - * String HTML content, or function that returns an HTML string - */ - template?: string | {(): string}; - /** - * String URL path to template file OR Function, returns URL path string - */ - templateUrl?: string | {(params: IStateParamsService): string}; - /** - * Function, returns HTML content string - */ - templateProvider?: Function | Array; - /** - * A controller paired to the state. Function, annotated array or name as String - */ - controller?: Function|string|Array; - controllerAs?: string; - /** - * Function (injectable), returns the actual controller function or string. - */ - controllerProvider?: Function|Array; - - /** - * Specifies the parent state of this state - */ - parent?: string | IState; - - - resolve?: { [name:string]: any }; - /** - * A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. - */ - url?: string | IUrlMatcher; - /** - * A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. - */ - params?: any; - /** - * Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views. - */ - views?: { [name:string]: IState }; - abstract?: boolean; - /** - * Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. - */ - onEnter?: Function|Array; - /** - * Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. - */ - onExit?: Function|Array; - /** - * Arbitrary data object, useful for custom configuration. - */ - data?: any; - - /** - * Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. - */ - reloadOnSearch?: boolean; - - /** - * Boolean (default true). If false will reload state on everytransitions. Useful for when you'd like to restore all data to its initial state. - */ - cache?: boolean; - } - - interface IUnfoundState { - to: string, - toParams: {}, - options: IStateOptions - } - - interface IStateProvider extends angular.IServiceProvider { - state(name:string, config:IState): IStateProvider; - state(config:IState): IStateProvider; - decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; - } - - interface IUrlMatcher { - concat(pattern: string): IUrlMatcher; - exec(path: string, searchParams: {}): {}; - parameters(): string[]; - format(values: {}): string; - } - - interface IUrlMatcherFactory { - /** - * Creates a UrlMatcher for the specified pattern. - * - * @param pattern {string} The URL pattern. - * - * @returns {IUrlMatcher} The UrlMatcher. - */ - compile(pattern: string): IUrlMatcher; - /** - * Returns true if the specified object is a UrlMatcher, or false otherwise. - * - * @param o {any} The object to perform the type check against. - * - * @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods. - */ - isMatcher(o: any): boolean; - /** - * Returns a type definition for the specified name - * - * @param name {string} The type definition name - * - * @returns {IType} The type definition - */ - type(name: string): IType; - /** - * Registers a custom Type object that can be used to generate URLs with typed parameters. - * - * @param {IType} definition The type definition. - * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. - * - * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. - */ - type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory; - /** - * Registers a custom Type object that can be used to generate URLs with typed parameters. - * - * @param {IType} definition The type definition. - * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. - * - * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. - */ - type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory; - /** - * Defines whether URL matching should be case sensitive (the default behavior), or not. - * - * @param value {boolean} false to match URL in a case sensitive manner; otherwise true; - * - * @returns {boolean} the current value of caseInsensitive - */ - caseInsensitive(value?: boolean): boolean; - /** - * Sets the default behavior when generating or matching URLs with default parameter values - * - * @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string. - */ - defaultSquashPolicy(value: string): void; - /** - * Defines whether URLs should match trailing slashes, or not (the default behavior). - * - * @param value {boolean} false to match trailing slashes in URLs, otherwise true. - * - * @returns {boolean} the current value of strictMode - */ - strictMode(value?: boolean): boolean; - } - - interface IUrlRouterProvider extends angular.IServiceProvider { - when(whenPath: RegExp, handler: Function): IUrlRouterProvider; - when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; - when(whenPath: RegExp, toPath: string): IUrlRouterProvider; - when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; - when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; - when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; - when(whenPath: string, handler: Function): IUrlRouterProvider; - when(whenPath: string, handler: any[]): IUrlRouterProvider; - when(whenPath: string, toPath: string): IUrlRouterProvider; - otherwise(handler: Function): IUrlRouterProvider; - otherwise(handler: any[]): IUrlRouterProvider; - otherwise(path: string): IUrlRouterProvider; - rule(handler: Function): IUrlRouterProvider; - rule(handler: any[]): IUrlRouterProvider; - /** - * Disables (or enables) deferring location change interception. - * - * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler. - * - * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true. - */ - deferIntercept(defer?: boolean): void; - } - - interface IStateOptions { - /** - * {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record. - */ - location?: boolean | string; - /** - * {boolean=true}, If true will inherit url parameters from current url. - */ - inherit?: boolean; - /** - * {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from. - */ - relative?: IState; - /** - * {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events. - */ - notify?: boolean; - /** - * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. - */ - reload?: boolean; - } - - interface IHrefOptions { - lossy?: boolean; - inherit?: boolean; - relative?: IState; - absolute?: boolean; - } - - interface IStateService { - /** - * Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states). - * - * @param to Absolute state name or relative state path. Some examples: - * - * $state.go('contact.detail') - will go to the contact.detail state - * $state.go('^') - will go to a parent state - * $state.go('^.sibling') - will go to a sibling state - * $state.go('.child.grandchild') - will go to grandchild state - * - * @param params A map of the parameters that will be sent to the state, will populate $stateParams. Any parameters that are not specified will be inherited from currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc. - * - * @param options Options object. - */ - go(to: string, params?: {}, options?: IStateOptions): angular.IPromise; - go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise; - transitionTo(state: string, params?: {}, updateLocation?: boolean): angular.IPromise; - transitionTo(state: IState, params?: {}, updateLocation?: boolean): angular.IPromise; - transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise; - transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise; - includes(state: string, params?: {}): boolean; - includes(state: string, params?: {}, options?:any): boolean; - is(state:string, params?: {}): boolean; - is(state: IState, params?: {}): boolean; - href(state: IState, params?: {}, options?: IHrefOptions): string; - href(state: string, params?: {}, options?: IHrefOptions): string; - get(state: string, context?: string): IState; - get(state: IState, context?: string): IState; - get(state: string, context?: IState): IState; - get(state: IState, context?: IState): IState; - get(): IState[]; - /** A reference to the state's config object. However you passed it in. Useful for accessing custom data. */ - current: IState; - /** A param object, e.g. {sectionId: section.id)}, that you'd like to test against the current active state. */ - params: IStateParamsService; - reload(): angular.IPromise; - - /** Currently pending transition. A promise that'll resolve or reject. */ - transition: angular.IPromise<{}>; - - $current: IResolvedState; - } - - interface IResolvedState { - locals: { +declare module 'angularjs' { + export namespace ui { + interface IState { + name?: string; /** - * Currently resolved "resolve" values from the current state + * String HTML content, or function that returns an HTML string */ - globals: { [key: string]: any; }; - }; + template?: string | {(): string}; + /** + * String URL path to template file OR Function, returns URL path string + */ + templateUrl?: string | {(params: IStateParamsService): string}; + /** + * Function, returns HTML content string + */ + templateProvider?: Function | Array; + /** + * A controller paired to the state. Function, annotated array or name as String + */ + controller?: Function|string|Array; + controllerAs?: string; + /** + * Function (injectable), returns the actual controller function or string. + */ + controllerProvider?: Function|Array; + + /** + * Specifies the parent state of this state + */ + parent?: string | IState; + + + resolve?: { [name:string]: any }; + /** + * A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. + */ + url?: string | IUrlMatcher; + /** + * A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. + */ + params?: any; + /** + * Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views. + */ + views?: { [name:string]: IState }; + abstract?: boolean; + /** + * Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. + */ + onEnter?: Function|Array; + /** + * Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. + */ + onExit?: Function|Array; + /** + * Arbitrary data object, useful for custom configuration. + */ + data?: any; + + /** + * Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. + */ + reloadOnSearch?: boolean; + + /** + * Boolean (default true). If false will reload state on everytransitions. Useful for when you'd like to restore all data to its initial state. + */ + cache?: boolean; + } + + interface IUnfoundState { + to: string, + toParams: {}, + options: IStateOptions + } + + interface IStateProvider extends angular.IServiceProvider { + state(name:string, config:IState): IStateProvider; + state(config:IState): IStateProvider; + decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; + } + + interface IUrlMatcher { + concat(pattern: string): IUrlMatcher; + exec(path: string, searchParams: {}): {}; + parameters(): string[]; + format(values: {}): string; + } + + interface IUrlMatcherFactory { + /** + * Creates a UrlMatcher for the specified pattern. + * + * @param pattern {string} The URL pattern. + * + * @returns {IUrlMatcher} The UrlMatcher. + */ + compile(pattern: string): IUrlMatcher; + /** + * Returns true if the specified object is a UrlMatcher, or false otherwise. + * + * @param o {any} The object to perform the type check against. + * + * @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods. + */ + isMatcher(o: any): boolean; + /** + * Returns a type definition for the specified name + * + * @param name {string} The type definition name + * + * @returns {IType} The type definition + */ + type(name: string): IType; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory; + /** + * Defines whether URL matching should be case sensitive (the default behavior), or not. + * + * @param value {boolean} false to match URL in a case sensitive manner; otherwise true; + * + * @returns {boolean} the current value of caseInsensitive + */ + caseInsensitive(value?: boolean): boolean; + /** + * Sets the default behavior when generating or matching URLs with default parameter values + * + * @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string. + */ + defaultSquashPolicy(value: string): void; + /** + * Defines whether URLs should match trailing slashes, or not (the default behavior). + * + * @param value {boolean} false to match trailing slashes in URLs, otherwise true. + * + * @returns {boolean} the current value of strictMode + */ + strictMode(value?: boolean): boolean; + } + + interface IUrlRouterProvider extends angular.IServiceProvider { + when(whenPath: RegExp, handler: Function): IUrlRouterProvider; + when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; + when(whenPath: RegExp, toPath: string): IUrlRouterProvider; + when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; + when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; + when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; + when(whenPath: string, handler: Function): IUrlRouterProvider; + when(whenPath: string, handler: any[]): IUrlRouterProvider; + when(whenPath: string, toPath: string): IUrlRouterProvider; + otherwise(handler: Function): IUrlRouterProvider; + otherwise(handler: any[]): IUrlRouterProvider; + otherwise(path: string): IUrlRouterProvider; + rule(handler: Function): IUrlRouterProvider; + rule(handler: any[]): IUrlRouterProvider; + /** + * Disables (or enables) deferring location change interception. + * + * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler. + * + * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true. + */ + deferIntercept(defer?: boolean): void; + } + + interface IStateOptions { + /** + * {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record. + */ + location?: boolean | string; + /** + * {boolean=true}, If true will inherit url parameters from current url. + */ + inherit?: boolean; + /** + * {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from. + */ + relative?: IState; + /** + * {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events. + */ + notify?: boolean; + /** + * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. + */ + reload?: boolean; + } + + interface IHrefOptions { + lossy?: boolean; + inherit?: boolean; + relative?: IState; + absolute?: boolean; + } + + interface IStateService { + /** + * Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states). + * + * @param to Absolute state name or relative state path. Some examples: + * + * $state.go('contact.detail') - will go to the contact.detail state + * $state.go('^') - will go to a parent state + * $state.go('^.sibling') - will go to a sibling state + * $state.go('.child.grandchild') - will go to grandchild state + * + * @param params A map of the parameters that will be sent to the state, will populate $stateParams. Any parameters that are not specified will be inherited from currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc. + * + * @param options Options object. + */ + go(to: string, params?: {}, options?: IStateOptions): angular.IPromise; + go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise; + transitionTo(state: string, params?: {}, updateLocation?: boolean): angular.IPromise; + transitionTo(state: IState, params?: {}, updateLocation?: boolean): angular.IPromise; + transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise; + transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise; + includes(state: string, params?: {}): boolean; + includes(state: string, params?: {}, options?:any): boolean; + is(state:string, params?: {}): boolean; + is(state: IState, params?: {}): boolean; + href(state: IState, params?: {}, options?: IHrefOptions): string; + href(state: string, params?: {}, options?: IHrefOptions): string; + get(state: string, context?: string): IState; + get(state: IState, context?: string): IState; + get(state: string, context?: IState): IState; + get(state: IState, context?: IState): IState; + get(): IState[]; + /** A reference to the state's config object. However you passed it in. Useful for accessing custom data. */ + current: IState; + /** A param object, e.g. {sectionId: section.id)}, that you'd like to test against the current active state. */ + params: IStateParamsService; + reload(): angular.IPromise; + + /** Currently pending transition. A promise that'll resolve or reject. */ + transition: angular.IPromise<{}>; + + $current: IResolvedState; + } + + interface IResolvedState { + locals: { + /** + * Currently resolved "resolve" values from the current state + */ + globals: { [key: string]: any; }; + }; + } + + interface IStateParamsService { + [key: string]: any; + } + + interface IUrlRouterService { + /* + * Triggers an update; the same update that happens when the address bar + * url changes, aka $locationChangeSuccess. + * + * This method is useful when you need to use preventDefault() on the + * $locationChangeSuccess event, perform some custom logic (route protection, + * auth, config, redirection, etc) and then finally proceed with the transition + * by calling $urlRouter.sync(). + * + */ + sync(): void; + listen(): Function; + href(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): string; + update(read?: boolean): void; + push(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): void; + } + + interface IUiViewScrollProvider { + /* + * Reverts back to using the core $anchorScroll service for scrolling + * based on the url anchor. + */ + useAnchorScroll(): void; + } + + interface IType { + /** + * Converts a parameter value (from URL string or transition param) to a custom/native value. + * + * @param val {string} The URL parameter value to decode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {any} Returns a custom representation of the URL parameter value. + */ + decode(val: string, key: string): any; + /** + * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string. + * + * @param val {any} The value to encode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {string} Returns a string representation of val that can be encoded in a URL. + */ + encode(val: any, key: string): string; + /** + * Determines whether two decoded values are equivalent. + * + * @param a {any} A value to compare against. + * @param b {any} A value to compare against. + * + * @returns {boolean} Returns true if the values are equivalent/equal, otherwise false. + */ + equals? (a: any, b: any): boolean; + /** + * Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object. + * + * @param val {any} The value to check. + * @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {boolean} Returns true if the value matches the type, otherwise false. + */ + is(val: any, key: string): boolean; + /** + * The regular expression pattern used to match values of this type when coming from a substring of a URL. + */ + pattern?: RegExp; + } } - interface IStateParamsService { - [key: string]: any; - } - - interface IUrlRouterService { - /* - * Triggers an update; the same update that happens when the address bar - * url changes, aka $locationChangeSuccess. - * - * This method is useful when you need to use preventDefault() on the - * $locationChangeSuccess event, perform some custom logic (route protection, - * auth, config, redirection, etc) and then finally proceed with the transition - * by calling $urlRouter.sync(). - * - */ - sync(): void; - listen(): Function; - href(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): string; - update(read?: boolean): void; - push(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): void; - } - - interface IUiViewScrollProvider { - /* - * Reverts back to using the core $anchorScroll service for scrolling - * based on the url anchor. - */ - useAnchorScroll(): void; - } - - interface IType { - /** - * Converts a parameter value (from URL string or transition param) to a custom/native value. - * - * @param val {string} The URL parameter value to decode. - * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {any} Returns a custom representation of the URL parameter value. - */ - decode(val: string, key: string): any; - /** - * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string. - * - * @param val {any} The value to encode. - * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {string} Returns a string representation of val that can be encoded in a URL. - */ - encode(val: any, key: string): string; - /** - * Determines whether two decoded values are equivalent. - * - * @param a {any} A value to compare against. - * @param b {any} A value to compare against. - * - * @returns {boolean} Returns true if the values are equivalent/equal, otherwise false. - */ - equals? (a: any, b: any): boolean; - /** - * Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object. - * - * @param val {any} The value to check. - * @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {boolean} Returns true if the value matches the type, otherwise false. - */ - is(val: any, key: string): boolean; - /** - * The regular expression pattern used to match values of this type when coming from a substring of a URL. - */ - pattern?: RegExp; - } } + diff --git a/angularjs/index.d.ts b/angularjs/index.d.ts index 4e9707596f..1d2f37e281 100644 --- a/angularjs/index.d.ts +++ b/angularjs/index.d.ts @@ -14,12 +14,13 @@ interface Function { $inject?: string[]; } -// Collapse angular into ng -import ng = angular; +export as namespace angular; +export as namespace ng; + // Support AMD require -declare module 'angular' { - export = angular; -} +export = angular; + +import ng = angular; /////////////////////////////////////////////////////////////////////////////// // ng module (angular.js) @@ -617,7 +618,7 @@ declare namespace angular { /** * calling preventDefault sets defaultPrevented flag to true. */ - preventDefault: Function; + preventDefault(): void; /** * true if preventDefault was called. */ diff --git a/atom-keymap/index.d.ts b/atom-keymap/index.d.ts index 8701875695..0b425c83d9 100644 --- a/atom-keymap/index.d.ts +++ b/atom-keymap/index.d.ts @@ -5,6 +5,8 @@ /// +export = AtomKeymap; + declare namespace AtomKeymap { type Disposable = AtomEventKit.Disposable; @@ -129,7 +131,3 @@ declare namespace AtomKeymap { /** Allows commands to be associated with keystrokes in a context-sensitive way.*/ var KeymapManager: KeymapManagerStatic; } - -declare module 'atom-keymap' { - export = AtomKeymap; -} diff --git a/autobahn/index.d.ts b/autobahn/index.d.ts index ca293ed2cf..29c8217d10 100644 --- a/autobahn/index.d.ts +++ b/autobahn/index.d.ts @@ -5,6 +5,8 @@ /// +export = autobahn; + declare namespace autobahn { export class Session { @@ -262,7 +264,3 @@ declare namespace autobahn { var transports: ITransports; var auth_cra: IAuthCra; } - -declare module "autobahn" { - export = autobahn; -} diff --git a/babel-core/index.d.ts b/babel-core/index.d.ts index 1892cbccb5..a3cd7019ab 100644 --- a/babel-core/index.d.ts +++ b/babel-core/index.d.ts @@ -7,138 +7,138 @@ /// /// -declare module "babel-core" { - import * as t from 'babel-types'; - export {t as types}; - type Node = t.Node; - export import template = require('babel-template'); - export var version: string; - import traverse, {Visitor} from "babel-traverse"; - export {traverse, Visitor}; +import * as t from 'babel-types'; +export {t as types}; +type Node = t.Node; +export import template = require('babel-template'); +export var version: string; +import traverse, {Visitor} from "babel-traverse"; +export {traverse, Visitor}; - /** Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. */ - export function transform(code: string, opts?: TransformOptions): BabelFileResult; +/** Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. */ +export function transform(code: string, opts?: TransformOptions): BabelFileResult; - /** Asynchronously transforms the entire contents of a file. */ - export function transformFile(filename: string, opts: TransformOptions, callback: (err: any, result: BabelFileResult) => void): void; +/** Asynchronously transforms the entire contents of a file. */ +export function transformFile(filename: string, opts: TransformOptions, callback: (err: any, result: BabelFileResult) => void): void; - /** Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. */ - export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult; +/** Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. */ +export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult; - export function transformFromAst(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult; +export function transformFromAst(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult; - export interface TransformOptions { +export interface TransformOptions { - /** Filename to use when reading from stdin - this will be used in source-maps, errors etc. Default: "unknown". */ - filename?: string; + /** Filename to use when reading from stdin - this will be used in source-maps, errors etc. Default: "unknown". */ + filename?: string; - /** Filename relative to `sourceRoot`. */ - filenameRelative?: string; + /** Filename relative to `sourceRoot`. */ + filenameRelative?: string; - /** A source map object that the output source map will be based on. */ - inputSourceMap?: Object; + /** A source map object that the output source map will be based on. */ + inputSourceMap?: Object; - /** - * This is an object of keys that represent different environments. For example, you may have: - * `{ env: { production: { / * specific options * / } } }` - * which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. - * If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"`. - */ - env?: Object; + /** + * This is an object of keys that represent different environments. For example, you may have: + * `{ env: { production: { / * specific options * / } } }` + * which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. + * If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"`. + */ + env?: Object; - /** Retain line numbers - will result in really ugly code. Default: `false` */ - retainLines?: boolean; + /** Retain line numbers - will result in really ugly code. Default: `false` */ + retainLines?: boolean; - /** Enable/disable ANSI syntax highlighting of code frames. Default: `true`. */ - highlightCode?: boolean; + /** Enable/disable ANSI syntax highlighting of code frames. Default: `true`. */ + highlightCode?: boolean; - /** List of presets (a set of plugins) to load and use. */ - presets?: any[]; + /** List of presets (a set of plugins) to load and use. */ + presets?: any[]; - /** List of plugins to load and use. */ - plugins?: any[]; + /** List of plugins to load and use. */ + plugins?: any[]; - /** list of glob paths to **not** compile. Opposite to the `only` option. */ - ignore?: string[]; + /** list of glob paths to **not** compile. Opposite to the `only` option. */ + ignore?: string[]; - /** - * A glob, regex, or mixed array of both, matching paths to only compile. Can also be an array of arrays containing - * paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. - */ - only?: string | RegExp | Array; + /** + * A glob, regex, or mixed array of both, matching paths to only compile. Can also be an array of arrays containing + * paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. + */ + only?: string | RegExp | Array; - /** Enable code generation. Default: `true`. */ - code?: boolean; + /** Enable code generation. Default: `true`. */ + code?: boolean; - /** Include the AST in the returned object. Default: `true`. */ - ast?: boolean; + /** Include the AST in the returned object. Default: `true`. */ + ast?: boolean; - /** A path to an .babelrc file to extend. */ - extends?: string; + /** A path to an .babelrc file to extend. */ + extends?: string; - /** write comments to generated output. Default: `true`. */ - comments?: boolean; + /** write comments to generated output. Default: `true`. */ + comments?: boolean; - /** - * An optional callback that controls whether a comment should be output or not. Called as - * `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comments` option when used. - */ - shouldPrintComment?: (comment: string) => boolean; + /** + * An optional callback that controls whether a comment should be output or not. Called as + * `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comments` option when used. + */ + shouldPrintComment?: (comment: string) => boolean; - /** - * Do not include superfluous whitespace characters and line terminators. When set to `"auto"`, `compact` is set to - * `true` on input sizes of >100KB. - */ - compact?: boolean | "auto"; + /** + * Do not include superfluous whitespace characters and line terminators. When set to `"auto"`, `compact` is set to + * `true` on input sizes of >100KB. + */ + compact?: boolean | "auto"; - /** - * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a `sourceMappingURL` - * directive is added to the bottom of the returned code. If set to `"both"` then a map property is returned as well - * as a source map comment appended. - */ - sourceMaps?: boolean | "inline" | "both"; + /** + * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a `sourceMappingURL` + * directive is added to the bottom of the returned code. If set to `"both"` then a map property is returned as well + * as a source map comment appended. + */ + sourceMaps?: boolean | "inline" | "both"; - /** Set `file` on returned source map. */ - sourceMapTarget?: string; + /** Set `file` on returned source map. */ + sourceMapTarget?: string; - /** Set `sources[0]` on returned source map. */ - sourceFileName?: string; + /** Set `sources[0]` on returned source map. */ + sourceFileName?: string; - /** The root from which all sources are relative. */ - sourceRoot?: string; + /** The root from which all sources are relative. */ + sourceRoot?: string; - /** Specify whether or not to use `.babelrc` and `.babelignore` files. Default: `true`. */ - babelrc?: boolean; + /** Specify whether or not to use `.babelrc` and `.babelignore` files. Default: `true`. */ + babelrc?: boolean; - /** Attach a comment before all non-user injected code. */ - auxiliaryCommentBefore?: string; + /** Attach a comment before all non-user injected code. */ + auxiliaryCommentBefore?: string; - /** Attach a comment after all non-user injected code. */ - auxiliaryCommentAfter?: string; + /** Attach a comment after all non-user injected code. */ + auxiliaryCommentAfter?: string; - /** - * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. - * If falsy value is returned then the generated module id is used. - */ - getModuleId?: (moduleName: string) => string; + /** + * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. + * If falsy value is returned then the generated module id is used. + */ + getModuleId?: (moduleName: string) => string; - /** Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. */ - moduleRoot?: string; + /** Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. */ + moduleRoot?: string; - /** - * If truthy, insert an explicit id for modules. By default, all modules are anonymous. - * (Not available for `common` modules). - */ - moduleIds?: boolean; + /** + * If truthy, insert an explicit id for modules. By default, all modules are anonymous. + * (Not available for `common` modules). + */ + moduleIds?: boolean; - /** Specify a custom name for module ids. */ - moduleId?: string; - } - - export interface BabelFileResult { - ast?: Node; - code?: string; - map?: Object; - } + /** Specify a custom name for module ids. */ + moduleId?: string; } + +export interface BabelFileResult { + ast?: Node; + code?: string; + map?: Object; +} +export as namespace babel; + diff --git a/babel-generator/index.d.ts b/babel-generator/index.d.ts index 73546722c1..f30505623f 100644 --- a/babel-generator/index.d.ts +++ b/babel-generator/index.d.ts @@ -5,98 +5,97 @@ /// -declare module "babel-generator" { - import * as t from 'babel-types'; - type Node = t.Node; +import * as t from 'babel-types'; +type Node = t.Node; + +/** + * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output. + * @param ast - the abstract syntax tree from which to generate output code. + * @param opts - used for specifying options for code generation. + * @param code - the original source code, used for source maps. + * @returns - an object containing the output code and source map. + */ +export default function generate(ast: Node, opts?: GeneratorOptions, code?: string | {[filename: string]: string}): GeneratorResult; + +export interface GeneratorOptions { /** - * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output. - * @param ast - the abstract syntax tree from which to generate output code. - * @param opts - used for specifying options for code generation. - * @param code - the original source code, used for source maps. - * @returns - an object containing the output code and source map. + * Optional string to add as a block comment at the start of the output file. + */ + auxiliaryCommentBefore?: string; + + /** + * Optional string to add as a block comment at the end of the output file. + */ + auxiliaryCommentAfter?: string; + + /** + * Function that takes a comment (as a string) and returns true if the comment should be included in the output. + * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment + * contains `@preserve` or `@license`. */ - export default function generate(ast: Node, opts?: GeneratorOptions, code?: string | {[filename: string]: string}): GeneratorResult; + shouldPrintComment?: (comment: string) => boolean; - export interface GeneratorOptions { + /** + * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces). + * Defaults to `false`. + */ + retainLines?: boolean; - /** - * Optional string to add as a block comment at the start of the output file. - */ - auxiliaryCommentBefore?: string; + /** + * Should comments be included in output? Defaults to `true`. + */ + comments?: boolean; - /** - * Optional string to add as a block comment at the end of the output file. - */ - auxiliaryCommentAfter?: string; + /** + * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`. + */ + compact?: boolean | 'auto'; - /** - * Function that takes a comment (as a string) and returns true if the comment should be included in the output. - * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment - * contains `@preserve` or `@license`. - */ - shouldPrintComment?: (comment: string) => boolean; + /** + * Should the output be minified. Defaults to `false`. + */ + minified?: boolean; - /** - * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces). - * Defaults to `false`. - */ - retainLines?: boolean; + /** + * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`. + */ + concise?: boolean; - /** - * Should comments be included in output? Defaults to `true`. - */ - comments?: boolean; + /** + * The type of quote to use in the output. If omitted, autodetects based on `ast.tokens`. + */ + quotes?: 'single' | 'double'; - /** - * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`. - */ - compact?: boolean | 'auto'; + /** + * Used in warning messages + */ + filename?: string; - /** - * Should the output be minified. Defaults to `false`. - */ - minified?: boolean; + /** + * Enable generating source maps. Defaults to `false`. + */ + sourceMaps?: boolean; - /** - * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`. - */ - concise?: boolean; + /** + * The filename of the generated code that the source map will be associated with. + */ + sourceMapTarget?: string; - /** - * The type of quote to use in the output. If omitted, autodetects based on `ast.tokens`. - */ - quotes?: 'single' | 'double'; + /** + * A root for all relative URLs in the source map. + */ + sourceRoot?: string; - /** - * Used in warning messages - */ - filename?: string; - - /** - * Enable generating source maps. Defaults to `false`. - */ - sourceMaps?: boolean; - - /** - * The filename of the generated code that the source map will be associated with. - */ - sourceMapTarget?: string; - - /** - * A root for all relative URLs in the source map. - */ - sourceRoot?: string; - - /** - * The filename for the source code (i.e. the code in the `code` argument). - * This will only be used if `code` is a string. - */ - sourceFileName?: string; - } - - export interface GeneratorResult { - map: Object; - code: string; - } + /** + * The filename for the source code (i.e. the code in the `code` argument). + * This will only be used if `code` is a string. + */ + sourceFileName?: string; } + +export interface GeneratorResult { + map: Object; + code: string; +} + diff --git a/babel-template/index.d.ts b/babel-template/index.d.ts index 2386f68a2a..7d73adc466 100644 --- a/babel-template/index.d.ts +++ b/babel-template/index.d.ts @@ -6,16 +6,16 @@ /// /// -declare module "babel-template" { - import {BabylonOptions} from 'babylon'; - import * as t from 'babel-types'; - type Node = t.Node; - // NB: This export doesn't match the handbook example, where `template` is the default export. - // But it does match the runtime behaviour (at least at the time of this writing). For some reason, - // babel-template/lib/index.js has this line at the bottom: module.exports = exports["default"]; - export = template; - function template(code: string, opts?: BabylonOptions): UseTemplate; +import {BabylonOptions} from 'babylon'; +import * as t from 'babel-types'; +type Node = t.Node; + +// NB: This export doesn't match the handbook example, where `template` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-template/lib/index.js has this line at the bottom: module.exports = exports["default"]; +export = template; +declare function template(code: string, opts?: BabylonOptions): UseTemplate; + +type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node; - type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node; -} diff --git a/babel-traverse/index.d.ts b/babel-traverse/index.d.ts index fac965eb3d..11d51dc2cb 100644 --- a/babel-traverse/index.d.ts +++ b/babel-traverse/index.d.ts @@ -5,962 +5,962 @@ /// -declare module "babel-traverse" { - import * as t from 'babel-types'; - type Node = t.Node; - export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; +import * as t from 'babel-types'; +type Node = t.Node; - export interface TraverseOptions extends Visitor { - scope?: Scope; - noScope?: boolean; - } +export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; - export class Scope { - constructor(path: NodePath, parentScope?: Scope); - path: NodePath; - block: Node; - parentBlock: Node; - parent: Scope; - hub: Hub; - bindings: { [name: string]: Binding; }; - - /** Traverse node with current scope and path. */ - traverse(node: Node | Node[], opts?: TraverseOptions, state?: any): void; - - /** Generate a unique identifier and add it to the current scope. */ - generateDeclaredUidIdentifier(name?: string): t.Identifier; - - /** Generate a unique identifier. */ - generateUidIdentifier(name?: string): t.Identifier; - - /** Generate a unique `_id1` binding. */ - generateUid(name?: string): string; - - /** Generate a unique identifier based on a node. */ - generateUidIdentifierBasedOnNode(parent: Node, defaultName?: string): t.Identifier; - - /** - * Determine whether evaluating the specific input `node` is a consequenceless reference. ie. - * evaluating it wont result in potentially arbitrary code from being ran. The following are - * whitelisted and determined not to cause side effects: - * - * - `this` expressions - * - `super` expressions - * - Bound identifiers - */ - isStatic(node: Node): boolean; - - /** Possibly generate a memoised identifier if it is not static and has consequences. */ - maybeGenerateMemoised(node: Node, dontPush?: boolean): t.Identifier; - - checkBlockScopedCollisions(local: Node, kind: string, name: string, id: Object): void; - - rename(oldName: string, newName?: string, block?: Node): void; - - dump(): void; - - toArray(node: Node, i?: number): Node; - - registerDeclaration(path: NodePath): void; - - buildUndefinedNode(): Node; - - registerConstantViolation(path: NodePath): void; - - registerBinding(kind: string, path: NodePath, bindingPath?: NodePath): void; - - addGlobal(node: Node): void; - - hasUid(name: string): boolean; - - hasGlobal(name: string): boolean; - - hasReference(name: string): boolean; - - isPure(node: Node, constantsOnly?: boolean): boolean; - - setData(key: string, val: any): any; - - getData(key: string): any; - - removeData(key: string): void; - - push(opts: any): void; - - getProgramParent(): Scope; - - getFunctionParent(): Scope; - - getBlockParent(): Scope; - - /** Walks the scope tree and gathers **all** bindings. */ - getAllBindings(...kinds: string[]): Object; - - bindingIdentifierEquals(name: string, node: Node): boolean; - - getBinding(name: string): Binding; - - getOwnBinding(name: string): Binding; - - getBindingIdentifier(name: string): t.Identifier; - - getOwnBindingIdentifier(name: string): t.Identifier; - - hasOwnBinding(name: string): boolean; - - hasBinding(name: string, noGlobals?: boolean): boolean; - - parentHasBinding(name: string, noGlobals?: boolean): boolean; - - /** Move a binding of `name` to another `scope`. */ - moveBindingTo(name: string, scope: Scope): void; - - removeOwnBinding(name: string): void; - - removeBinding(name: string): void; - } - - export class Binding { - constructor(opts: { existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath; kind: 'var' | 'let' | 'const'; }); - identifier: t.Identifier; - scope: Scope; - path: NodePath; - kind: 'var' | 'let' | 'const'; - referenced: boolean; - references: number; - referencePaths: NodePath[]; - constant: boolean; - constantViolations: NodePath[]; - } - - export interface Visitor extends VisitNodeObject { - ArrayExpression?: VisitNode; - AssignmentExpression?: VisitNode; - LVal?: VisitNode; - Expression?: VisitNode; - BinaryExpression?: VisitNode; - Directive?: VisitNode; - DirectiveLiteral?: VisitNode; - BlockStatement?: VisitNode; - BreakStatement?: VisitNode; - Identifier?: VisitNode; - CallExpression?: VisitNode; - CatchClause?: VisitNode; - ConditionalExpression?: VisitNode; - ContinueStatement?: VisitNode; - DebuggerStatement?: VisitNode; - DoWhileStatement?: VisitNode; - Statement?: VisitNode; - EmptyStatement?: VisitNode; - ExpressionStatement?: VisitNode; - File?: VisitNode; - Program?: VisitNode; - ForInStatement?: VisitNode; - VariableDeclaration?: VisitNode; - ForStatement?: VisitNode; - FunctionDeclaration?: VisitNode; - FunctionExpression?: VisitNode; - IfStatement?: VisitNode; - LabeledStatement?: VisitNode; - StringLiteral?: VisitNode; - NumericLiteral?: VisitNode; - NullLiteral?: VisitNode; - BooleanLiteral?: VisitNode; - RegExpLiteral?: VisitNode; - LogicalExpression?: VisitNode; - MemberExpression?: VisitNode; - NewExpression?: VisitNode; - ObjectExpression?: VisitNode; - ObjectMethod?: VisitNode; - ObjectProperty?: VisitNode; - RestElement?: VisitNode; - ReturnStatement?: VisitNode; - SequenceExpression?: VisitNode; - SwitchCase?: VisitNode; - SwitchStatement?: VisitNode; - ThisExpression?: VisitNode; - ThrowStatement?: VisitNode; - TryStatement?: VisitNode; - UnaryExpression?: VisitNode; - UpdateExpression?: VisitNode; - VariableDeclarator?: VisitNode; - WhileStatement?: VisitNode; - WithStatement?: VisitNode; - AssignmentPattern?: VisitNode; - ArrayPattern?: VisitNode; - ArrowFunctionExpression?: VisitNode; - ClassBody?: VisitNode; - ClassDeclaration?: VisitNode; - ClassExpression?: VisitNode; - ExportAllDeclaration?: VisitNode; - ExportDefaultDeclaration?: VisitNode; - ExportNamedDeclaration?: VisitNode; - Declaration?: VisitNode; - ExportSpecifier?: VisitNode; - ForOfStatement?: VisitNode; - ImportDeclaration?: VisitNode; - ImportDefaultSpecifier?: VisitNode; - ImportNamespaceSpecifier?: VisitNode; - ImportSpecifier?: VisitNode; - MetaProperty?: VisitNode; - ClassMethod?: VisitNode; - ObjectPattern?: VisitNode; - SpreadElement?: VisitNode; - Super?: VisitNode; - TaggedTemplateExpression?: VisitNode; - TemplateLiteral?: VisitNode; - TemplateElement?: VisitNode; - YieldExpression?: VisitNode; - AnyTypeAnnotation?: VisitNode; - ArrayTypeAnnotation?: VisitNode; - BooleanTypeAnnotation?: VisitNode; - BooleanLiteralTypeAnnotation?: VisitNode; - NullLiteralTypeAnnotation?: VisitNode; - ClassImplements?: VisitNode; - ClassProperty?: VisitNode; - DeclareClass?: VisitNode; - DeclareFunction?: VisitNode; - DeclareInterface?: VisitNode; - DeclareModule?: VisitNode; - DeclareTypeAlias?: VisitNode; - DeclareVariable?: VisitNode; - ExistentialTypeParam?: VisitNode; - FunctionTypeAnnotation?: VisitNode; - FunctionTypeParam?: VisitNode; - GenericTypeAnnotation?: VisitNode; - InterfaceExtends?: VisitNode; - InterfaceDeclaration?: VisitNode; - IntersectionTypeAnnotation?: VisitNode; - MixedTypeAnnotation?: VisitNode; - NullableTypeAnnotation?: VisitNode; - NumericLiteralTypeAnnotation?: VisitNode; - NumberTypeAnnotation?: VisitNode; - StringLiteralTypeAnnotation?: VisitNode; - StringTypeAnnotation?: VisitNode; - ThisTypeAnnotation?: VisitNode; - TupleTypeAnnotation?: VisitNode; - TypeofTypeAnnotation?: VisitNode; - TypeAlias?: VisitNode; - TypeAnnotation?: VisitNode; - TypeCastExpression?: VisitNode; - TypeParameterDeclaration?: VisitNode; - TypeParameterInstantiation?: VisitNode; - ObjectTypeAnnotation?: VisitNode; - ObjectTypeCallProperty?: VisitNode; - ObjectTypeIndexer?: VisitNode; - ObjectTypeProperty?: VisitNode; - QualifiedTypeIdentifier?: VisitNode; - UnionTypeAnnotation?: VisitNode; - VoidTypeAnnotation?: VisitNode; - JSXAttribute?: VisitNode; - JSXIdentifier?: VisitNode; - JSXNamespacedName?: VisitNode; - JSXElement?: VisitNode; - JSXExpressionContainer?: VisitNode; - JSXClosingElement?: VisitNode; - JSXMemberExpression?: VisitNode; - JSXOpeningElement?: VisitNode; - JSXEmptyExpression?: VisitNode; - JSXSpreadAttribute?: VisitNode; - JSXText?: VisitNode; - Noop?: VisitNode; - ParenthesizedExpression?: VisitNode; - AwaitExpression?: VisitNode; - BindExpression?: VisitNode; - Decorator?: VisitNode; - DoExpression?: VisitNode; - ExportDefaultSpecifier?: VisitNode; - ExportNamespaceSpecifier?: VisitNode; - RestProperty?: VisitNode; - SpreadProperty?: VisitNode; - Binary?: VisitNode; - Scopable?: VisitNode; - BlockParent?: VisitNode; - Block?: VisitNode; - Terminatorless?: VisitNode; - CompletionStatement?: VisitNode; - Conditional?: VisitNode; - Loop?: VisitNode; - While?: VisitNode; - ExpressionWrapper?: VisitNode; - For?: VisitNode; - ForXStatement?: VisitNode; - Function?: VisitNode; - FunctionParent?: VisitNode; - Pureish?: VisitNode; - Literal?: VisitNode; - Immutable?: VisitNode; - UserWhitespacable?: VisitNode; - Method?: VisitNode; - ObjectMember?: VisitNode; - Property?: VisitNode; - UnaryLike?: VisitNode; - Pattern?: VisitNode; - Class?: VisitNode; - ModuleDeclaration?: VisitNode; - ExportDeclaration?: VisitNode; - ModuleSpecifier?: VisitNode; - Flow?: VisitNode; - FlowBaseAnnotation?: VisitNode; - FlowDeclaration?: VisitNode; - JSX?: VisitNode; - } - - export type VisitNode = VisitNodeFunction | VisitNodeObject; - - export type VisitNodeFunction = (path: NodePath, state: any) => void; - - export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; - } - - export class NodePath { - constructor(hub: Hub, parent: Node); - parent: Node; - hub: Hub; - contexts: TraversalContext[]; - data: Object; - shouldSkip: boolean; - shouldStop: boolean; - removed: boolean; - state: any; - opts: Object; - skipKeys: Object; - parentPath: NodePath; - context: TraversalContext; - container: Object | Object[]; - listKey: string; - inList: boolean; - parentKey: string; - key: string; - node: T; - scope: Scope; - type: string; - typeAnnotation: Object; - - getScope(scope: Scope): Scope; - - setData(key: string, val: any): any; - - getData(key: string, def?: any): any; - - buildCodeFrameError(msg: string, Error: Error): Error; - - traverse(visitor: Visitor, state?: any): void; - - set(key: string, node: Node): void; - - getPathLocation(): string; - - debug(buildMessage: Function): void; - - // ------------------------- ancestry ------------------------- - /** - * Call the provided `callback` with the `NodePath`s of all the parents. - * When the `callback` returns a truthy value, we return that node path. - */ - findParent(callback: (path: NodePath) => boolean): NodePath; - - find(callback: (path: NodePath) => boolean): NodePath; - - /** Get the parent function of the current path. */ - getFunctionParent(): NodePath; - - /** Walk up the tree until we hit a parent node path in a list. */ - getStatementParent(): NodePath; - - /** - * Get the deepest common ancestor and then from it, get the earliest relationship path - * to that ancestor. - * - * Earliest is defined as being "before" all the other nodes in terms of list container - * position and visiting key. - */ - getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath; - - /** Get the earliest path in the tree where the provided `paths` intersect. */ - getDeepestCommonAncestorFrom(paths: NodePath[], filter?: Function): NodePath; - - /** - * Build an array of node paths containing the entire ancestry of the current node path. - * - * NOTE: The current node path is included in this. - */ - getAncestry(): NodePath[]; - - inType(...candidateTypes: string[]): boolean; - - // ------------------------- inference ------------------------- - /** Infer the type of the current `NodePath`. */ - getTypeAnnotation(): t.FlowTypeAnnotation; - - isBaseType(baseName: string, soft?: boolean): boolean; - - couldBeBaseType(name: string): boolean; - - baseTypeStrictlyMatches(right: NodePath): boolean; - - isGenericType(genericName: string): boolean; - - // ------------------------- replacement ------------------------- - /** - * Replace a node with an array of multiple. This method performs the following steps: - * - * - Inherit the comments of first provided node with that of the current node. - * - Insert the provided nodes after the current node. - * - Remove the current node. - */ - replaceWithMultiple(nodes: Node[]): void; - - /** - * Parse a string as an expression and replace the current node with the result. - * - * NOTE: This is typically not a good idea to use. Building source strings when - * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's - * easier to use, your transforms will be extremely brittle. - */ - replaceWithSourceString(replacement: any): void; - - /** Replace the current node with another. */ - replaceWith(replacement: Node | NodePath): void; - - /** - * This method takes an array of statements nodes and then explodes it - * into expressions. This method retains completion records which is - * extremely important to retain original semantics. - */ - replaceExpressionWithStatements(nodes: Node[]): Node; - - replaceInline(nodes: Node | Node[]): void; - - // ------------------------- evaluation ------------------------- - /** - * Walk the input `node` and statically evaluate if it's truthy. - * - * Returning `true` when we're sure that the expression will evaluate to a - * truthy value, `false` if we're sure that it will evaluate to a falsy - * value and `undefined` if we aren't sure. Because of this please do not - * rely on coercion when using this method and check with === if it's false. - */ - evaluateTruthy(): boolean; - - /** - * Walk the input `node` and statically evaluate it. - * - * Returns an object in the form `{ confident, value }`. `confident` indicates - * whether or not we had to drop out of evaluating the expression because of - * hitting an unknown node that we couldn't confidently find the value of. - * - * Example: - * - * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } - * t.evaluate(parse("!true")) // { confident: true, value: false } - * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined } - */ - evaluate(): { confident: boolean; value: any }; - - // ------------------------- introspection ------------------------- - /** - * Match the current node if it matches the provided `pattern`. - * - * For example, given the match `React.createClass` it would match the - * parsed nodes of `React.createClass` and `React["createClass"]`. - */ - matchesPattern(pattern: string, allowPartial?: boolean): boolean; - - /** - * Check whether we have the input `key`. If the `key` references an array then we check - * if the array has any items, otherwise we just check if it's falsy. - */ - has(key: string): boolean; - - isStatic(): boolean; - - /** Alias of `has`. */ - is(key: string): boolean; - - /** Opposite of `has`. */ - isnt(key: string): boolean; - - /** Check whether the path node `key` strict equals `value`. */ - equals(key: string, value: any): boolean; - - /** - * Check the type against our stored internal type of the node. This is handy when a node has - * been removed yet we still internally know the type and need it to calculate node replacement. - */ - isNodeType(type: string): boolean; - - /** - * This checks whether or not we're in one of the following positions: - * - * for (KEY in right); - * for (KEY;;); - * - * This is because these spots allow VariableDeclarations AND normal expressions so we need - * to tell the path replacement that it's ok to replace this with an expression. - */ - canHaveVariableDeclarationOrExpression(): boolean; - - /** - * This checks whether we are swapping an arrow function's body between an - * expression and a block statement (or vice versa). - * - * This is because arrow functions may implicitly return an expression, which - * is the same as containing a block statement. - */ - canSwapBetweenExpressionAndStatement(replacement: Node): boolean; - - /** Check whether the current path references a completion record */ - isCompletionRecord(allowInsideFunction?: boolean): boolean; - - /** - * Check whether or not the current `key` allows either a single statement or block statement - * so we can explode it if necessary. - */ - isStatementOrBlock(): boolean; - - /** Check if the currently assigned path references the `importName` of `moduleSource`. */ - referencesImport(moduleSource: string, importName: string): boolean; - - /** Get the source code associated with this node. */ - getSource(): string; - - // ------------------------- context ------------------------- - call(key: string): boolean; - - isBlacklisted(): boolean; - - visit(): boolean; - - skip(): void; - - skipKey(key: string): void; - - stop(): void; - - setScope(): void; - - setContext(context: TraversalContext): NodePath; - - popContext(): void; - - pushContext(context: TraversalContext): void; - - // ------------------------- removal ------------------------- - remove(): void; - - // ------------------------- modification ------------------------- - /** Insert the provided nodes before the current one. */ - insertBefore(nodes: Node | Node[]): any; - - /** - * Insert the provided nodes after the current one. When inserting nodes after an - * expression, ensure that the completion record is correct by pushing the current node. - */ - insertAfter(nodes: Node | Node[]): any; - - /** Update all sibling node paths after `fromIndex` by `incrementBy`. */ - updateSiblingKeys(fromIndex: number, incrementBy: number): void; - - /** Hoist the current node to the highest scope possible and return a UID referencing it. */ - hoist(scope: Scope): void; - - // ------------------------- family ------------------------- - getStatementParent(): NodePath; - - getOpposite(): NodePath; - - getCompletionRecords(): NodePath[]; - - getSibling(key: string): NodePath; - - get(key: string, context?: boolean | TraversalContext): NodePath; - - getBindingIdentifiers(duplicates?: boolean): Node[]; - - getOuterBindingIdentifiers(duplicates?: boolean): Node[]; - - // ------------------------- comments ------------------------- - /** Share comments amongst siblings. */ - shareCommentsWithSiblings(): void; - - addComment(type: string, content: string, line?: boolean): void; - - /** Give node `comments` of the specified `type`. */ - addComments(type: string, comments: any[]): void; - - // ------------------------- isXXX ------------------------- - isArrayExpression(opts?: Object): boolean; - isAssignmentExpression(opts?: Object): boolean; - isBinaryExpression(opts?: Object): boolean; - isDirective(opts?: Object): boolean; - isDirectiveLiteral(opts?: Object): boolean; - isBlockStatement(opts?: Object): boolean; - isBreakStatement(opts?: Object): boolean; - isCallExpression(opts?: Object): boolean; - isCatchClause(opts?: Object): boolean; - isConditionalExpression(opts?: Object): boolean; - isContinueStatement(opts?: Object): boolean; - isDebuggerStatement(opts?: Object): boolean; - isDoWhileStatement(opts?: Object): boolean; - isEmptyStatement(opts?: Object): boolean; - isExpressionStatement(opts?: Object): boolean; - isFile(opts?: Object): boolean; - isForInStatement(opts?: Object): boolean; - isForStatement(opts?: Object): boolean; - isFunctionDeclaration(opts?: Object): boolean; - isFunctionExpression(opts?: Object): boolean; - isIdentifier(opts?: Object): boolean; - isIfStatement(opts?: Object): boolean; - isLabeledStatement(opts?: Object): boolean; - isStringLiteral(opts?: Object): boolean; - isNumericLiteral(opts?: Object): boolean; - isNullLiteral(opts?: Object): boolean; - isBooleanLiteral(opts?: Object): boolean; - isRegExpLiteral(opts?: Object): boolean; - isLogicalExpression(opts?: Object): boolean; - isMemberExpression(opts?: Object): boolean; - isNewExpression(opts?: Object): boolean; - isProgram(opts?: Object): boolean; - isObjectExpression(opts?: Object): boolean; - isObjectMethod(opts?: Object): boolean; - isObjectProperty(opts?: Object): boolean; - isRestElement(opts?: Object): boolean; - isReturnStatement(opts?: Object): boolean; - isSequenceExpression(opts?: Object): boolean; - isSwitchCase(opts?: Object): boolean; - isSwitchStatement(opts?: Object): boolean; - isThisExpression(opts?: Object): boolean; - isThrowStatement(opts?: Object): boolean; - isTryStatement(opts?: Object): boolean; - isUnaryExpression(opts?: Object): boolean; - isUpdateExpression(opts?: Object): boolean; - isVariableDeclaration(opts?: Object): boolean; - isVariableDeclarator(opts?: Object): boolean; - isWhileStatement(opts?: Object): boolean; - isWithStatement(opts?: Object): boolean; - isAssignmentPattern(opts?: Object): boolean; - isArrayPattern(opts?: Object): boolean; - isArrowFunctionExpression(opts?: Object): boolean; - isClassBody(opts?: Object): boolean; - isClassDeclaration(opts?: Object): boolean; - isClassExpression(opts?: Object): boolean; - isExportAllDeclaration(opts?: Object): boolean; - isExportDefaultDeclaration(opts?: Object): boolean; - isExportNamedDeclaration(opts?: Object): boolean; - isExportSpecifier(opts?: Object): boolean; - isForOfStatement(opts?: Object): boolean; - isImportDeclaration(opts?: Object): boolean; - isImportDefaultSpecifier(opts?: Object): boolean; - isImportNamespaceSpecifier(opts?: Object): boolean; - isImportSpecifier(opts?: Object): boolean; - isMetaProperty(opts?: Object): boolean; - isClassMethod(opts?: Object): boolean; - isObjectPattern(opts?: Object): boolean; - isSpreadElement(opts?: Object): boolean; - isSuper(opts?: Object): boolean; - isTaggedTemplateExpression(opts?: Object): boolean; - isTemplateElement(opts?: Object): boolean; - isTemplateLiteral(opts?: Object): boolean; - isYieldExpression(opts?: Object): boolean; - isAnyTypeAnnotation(opts?: Object): boolean; - isArrayTypeAnnotation(opts?: Object): boolean; - isBooleanTypeAnnotation(opts?: Object): boolean; - isBooleanLiteralTypeAnnotation(opts?: Object): boolean; - isNullLiteralTypeAnnotation(opts?: Object): boolean; - isClassImplements(opts?: Object): boolean; - isClassProperty(opts?: Object): boolean; - isDeclareClass(opts?: Object): boolean; - isDeclareFunction(opts?: Object): boolean; - isDeclareInterface(opts?: Object): boolean; - isDeclareModule(opts?: Object): boolean; - isDeclareTypeAlias(opts?: Object): boolean; - isDeclareVariable(opts?: Object): boolean; - isExistentialTypeParam(opts?: Object): boolean; - isFunctionTypeAnnotation(opts?: Object): boolean; - isFunctionTypeParam(opts?: Object): boolean; - isGenericTypeAnnotation(opts?: Object): boolean; - isInterfaceExtends(opts?: Object): boolean; - isInterfaceDeclaration(opts?: Object): boolean; - isIntersectionTypeAnnotation(opts?: Object): boolean; - isMixedTypeAnnotation(opts?: Object): boolean; - isNullableTypeAnnotation(opts?: Object): boolean; - isNumericLiteralTypeAnnotation(opts?: Object): boolean; - isNumberTypeAnnotation(opts?: Object): boolean; - isStringLiteralTypeAnnotation(opts?: Object): boolean; - isStringTypeAnnotation(opts?: Object): boolean; - isThisTypeAnnotation(opts?: Object): boolean; - isTupleTypeAnnotation(opts?: Object): boolean; - isTypeofTypeAnnotation(opts?: Object): boolean; - isTypeAlias(opts?: Object): boolean; - isTypeAnnotation(opts?: Object): boolean; - isTypeCastExpression(opts?: Object): boolean; - isTypeParameterDeclaration(opts?: Object): boolean; - isTypeParameterInstantiation(opts?: Object): boolean; - isObjectTypeAnnotation(opts?: Object): boolean; - isObjectTypeCallProperty(opts?: Object): boolean; - isObjectTypeIndexer(opts?: Object): boolean; - isObjectTypeProperty(opts?: Object): boolean; - isQualifiedTypeIdentifier(opts?: Object): boolean; - isUnionTypeAnnotation(opts?: Object): boolean; - isVoidTypeAnnotation(opts?: Object): boolean; - isJSXAttribute(opts?: Object): boolean; - isJSXClosingElement(opts?: Object): boolean; - isJSXElement(opts?: Object): boolean; - isJSXEmptyExpression(opts?: Object): boolean; - isJSXExpressionContainer(opts?: Object): boolean; - isJSXIdentifier(opts?: Object): boolean; - isJSXMemberExpression(opts?: Object): boolean; - isJSXNamespacedName(opts?: Object): boolean; - isJSXOpeningElement(opts?: Object): boolean; - isJSXSpreadAttribute(opts?: Object): boolean; - isJSXText(opts?: Object): boolean; - isNoop(opts?: Object): boolean; - isParenthesizedExpression(opts?: Object): boolean; - isAwaitExpression(opts?: Object): boolean; - isBindExpression(opts?: Object): boolean; - isDecorator(opts?: Object): boolean; - isDoExpression(opts?: Object): boolean; - isExportDefaultSpecifier(opts?: Object): boolean; - isExportNamespaceSpecifier(opts?: Object): boolean; - isRestProperty(opts?: Object): boolean; - isSpreadProperty(opts?: Object): boolean; - isExpression(opts?: Object): boolean; - isBinary(opts?: Object): boolean; - isScopable(opts?: Object): boolean; - isBlockParent(opts?: Object): boolean; - isBlock(opts?: Object): boolean; - isStatement(opts?: Object): boolean; - isTerminatorless(opts?: Object): boolean; - isCompletionStatement(opts?: Object): boolean; - isConditional(opts?: Object): boolean; - isLoop(opts?: Object): boolean; - isWhile(opts?: Object): boolean; - isExpressionWrapper(opts?: Object): boolean; - isFor(opts?: Object): boolean; - isForXStatement(opts?: Object): boolean; - isFunction(opts?: Object): boolean; - isFunctionParent(opts?: Object): boolean; - isPureish(opts?: Object): boolean; - isDeclaration(opts?: Object): boolean; - isLVal(opts?: Object): boolean; - isLiteral(opts?: Object): boolean; - isImmutable(opts?: Object): boolean; - isUserWhitespacable(opts?: Object): boolean; - isMethod(opts?: Object): boolean; - isObjectMember(opts?: Object): boolean; - isProperty(opts?: Object): boolean; - isUnaryLike(opts?: Object): boolean; - isPattern(opts?: Object): boolean; - isClass(opts?: Object): boolean; - isModuleDeclaration(opts?: Object): boolean; - isExportDeclaration(opts?: Object): boolean; - isModuleSpecifier(opts?: Object): boolean; - isFlow(opts?: Object): boolean; - isFlowBaseAnnotation(opts?: Object): boolean; - isFlowDeclaration(opts?: Object): boolean; - isJSX(opts?: Object): boolean; - isNumberLiteral(opts?: Object): boolean; - isRegexLiteral(opts?: Object): boolean; - isReferencedIdentifier(opts?: Object): boolean; - isReferencedMemberExpression(opts?: Object): boolean; - isBindingIdentifier(opts?: Object): boolean; - isScope(opts?: Object): boolean; - isReferenced(opts?: Object): boolean; - isBlockScoped(opts?: Object): boolean; - isVar(opts?: Object): boolean; - isUser(opts?: Object): boolean; - isGenerated(opts?: Object): boolean; - isPure(opts?: Object): boolean; - - // ------------------------- assertXXX ------------------------- - assertArrayExpression(opts?: Object): void; - assertAssignmentExpression(opts?: Object): void; - assertBinaryExpression(opts?: Object): void; - assertDirective(opts?: Object): void; - assertDirectiveLiteral(opts?: Object): void; - assertBlockStatement(opts?: Object): void; - assertBreakStatement(opts?: Object): void; - assertCallExpression(opts?: Object): void; - assertCatchClause(opts?: Object): void; - assertConditionalExpression(opts?: Object): void; - assertContinueStatement(opts?: Object): void; - assertDebuggerStatement(opts?: Object): void; - assertDoWhileStatement(opts?: Object): void; - assertEmptyStatement(opts?: Object): void; - assertExpressionStatement(opts?: Object): void; - assertFile(opts?: Object): void; - assertForInStatement(opts?: Object): void; - assertForStatement(opts?: Object): void; - assertFunctionDeclaration(opts?: Object): void; - assertFunctionExpression(opts?: Object): void; - assertIdentifier(opts?: Object): void; - assertIfStatement(opts?: Object): void; - assertLabeledStatement(opts?: Object): void; - assertStringLiteral(opts?: Object): void; - assertNumericLiteral(opts?: Object): void; - assertNullLiteral(opts?: Object): void; - assertBooleanLiteral(opts?: Object): void; - assertRegExpLiteral(opts?: Object): void; - assertLogicalExpression(opts?: Object): void; - assertMemberExpression(opts?: Object): void; - assertNewExpression(opts?: Object): void; - assertProgram(opts?: Object): void; - assertObjectExpression(opts?: Object): void; - assertObjectMethod(opts?: Object): void; - assertObjectProperty(opts?: Object): void; - assertRestElement(opts?: Object): void; - assertReturnStatement(opts?: Object): void; - assertSequenceExpression(opts?: Object): void; - assertSwitchCase(opts?: Object): void; - assertSwitchStatement(opts?: Object): void; - assertThisExpression(opts?: Object): void; - assertThrowStatement(opts?: Object): void; - assertTryStatement(opts?: Object): void; - assertUnaryExpression(opts?: Object): void; - assertUpdateExpression(opts?: Object): void; - assertVariableDeclaration(opts?: Object): void; - assertVariableDeclarator(opts?: Object): void; - assertWhileStatement(opts?: Object): void; - assertWithStatement(opts?: Object): void; - assertAssignmentPattern(opts?: Object): void; - assertArrayPattern(opts?: Object): void; - assertArrowFunctionExpression(opts?: Object): void; - assertClassBody(opts?: Object): void; - assertClassDeclaration(opts?: Object): void; - assertClassExpression(opts?: Object): void; - assertExportAllDeclaration(opts?: Object): void; - assertExportDefaultDeclaration(opts?: Object): void; - assertExportNamedDeclaration(opts?: Object): void; - assertExportSpecifier(opts?: Object): void; - assertForOfStatement(opts?: Object): void; - assertImportDeclaration(opts?: Object): void; - assertImportDefaultSpecifier(opts?: Object): void; - assertImportNamespaceSpecifier(opts?: Object): void; - assertImportSpecifier(opts?: Object): void; - assertMetaProperty(opts?: Object): void; - assertClassMethod(opts?: Object): void; - assertObjectPattern(opts?: Object): void; - assertSpreadElement(opts?: Object): void; - assertSuper(opts?: Object): void; - assertTaggedTemplateExpression(opts?: Object): void; - assertTemplateElement(opts?: Object): void; - assertTemplateLiteral(opts?: Object): void; - assertYieldExpression(opts?: Object): void; - assertAnyTypeAnnotation(opts?: Object): void; - assertArrayTypeAnnotation(opts?: Object): void; - assertBooleanTypeAnnotation(opts?: Object): void; - assertBooleanLiteralTypeAnnotation(opts?: Object): void; - assertNullLiteralTypeAnnotation(opts?: Object): void; - assertClassImplements(opts?: Object): void; - assertClassProperty(opts?: Object): void; - assertDeclareClass(opts?: Object): void; - assertDeclareFunction(opts?: Object): void; - assertDeclareInterface(opts?: Object): void; - assertDeclareModule(opts?: Object): void; - assertDeclareTypeAlias(opts?: Object): void; - assertDeclareVariable(opts?: Object): void; - assertExistentialTypeParam(opts?: Object): void; - assertFunctionTypeAnnotation(opts?: Object): void; - assertFunctionTypeParam(opts?: Object): void; - assertGenericTypeAnnotation(opts?: Object): void; - assertInterfaceExtends(opts?: Object): void; - assertInterfaceDeclaration(opts?: Object): void; - assertIntersectionTypeAnnotation(opts?: Object): void; - assertMixedTypeAnnotation(opts?: Object): void; - assertNullableTypeAnnotation(opts?: Object): void; - assertNumericLiteralTypeAnnotation(opts?: Object): void; - assertNumberTypeAnnotation(opts?: Object): void; - assertStringLiteralTypeAnnotation(opts?: Object): void; - assertStringTypeAnnotation(opts?: Object): void; - assertThisTypeAnnotation(opts?: Object): void; - assertTupleTypeAnnotation(opts?: Object): void; - assertTypeofTypeAnnotation(opts?: Object): void; - assertTypeAlias(opts?: Object): void; - assertTypeAnnotation(opts?: Object): void; - assertTypeCastExpression(opts?: Object): void; - assertTypeParameterDeclaration(opts?: Object): void; - assertTypeParameterInstantiation(opts?: Object): void; - assertObjectTypeAnnotation(opts?: Object): void; - assertObjectTypeCallProperty(opts?: Object): void; - assertObjectTypeIndexer(opts?: Object): void; - assertObjectTypeProperty(opts?: Object): void; - assertQualifiedTypeIdentifier(opts?: Object): void; - assertUnionTypeAnnotation(opts?: Object): void; - assertVoidTypeAnnotation(opts?: Object): void; - assertJSXAttribute(opts?: Object): void; - assertJSXClosingElement(opts?: Object): void; - assertJSXElement(opts?: Object): void; - assertJSXEmptyExpression(opts?: Object): void; - assertJSXExpressionContainer(opts?: Object): void; - assertJSXIdentifier(opts?: Object): void; - assertJSXMemberExpression(opts?: Object): void; - assertJSXNamespacedName(opts?: Object): void; - assertJSXOpeningElement(opts?: Object): void; - assertJSXSpreadAttribute(opts?: Object): void; - assertJSXText(opts?: Object): void; - assertNoop(opts?: Object): void; - assertParenthesizedExpression(opts?: Object): void; - assertAwaitExpression(opts?: Object): void; - assertBindExpression(opts?: Object): void; - assertDecorator(opts?: Object): void; - assertDoExpression(opts?: Object): void; - assertExportDefaultSpecifier(opts?: Object): void; - assertExportNamespaceSpecifier(opts?: Object): void; - assertRestProperty(opts?: Object): void; - assertSpreadProperty(opts?: Object): void; - assertExpression(opts?: Object): void; - assertBinary(opts?: Object): void; - assertScopable(opts?: Object): void; - assertBlockParent(opts?: Object): void; - assertBlock(opts?: Object): void; - assertStatement(opts?: Object): void; - assertTerminatorless(opts?: Object): void; - assertCompletionStatement(opts?: Object): void; - assertConditional(opts?: Object): void; - assertLoop(opts?: Object): void; - assertWhile(opts?: Object): void; - assertExpressionWrapper(opts?: Object): void; - assertFor(opts?: Object): void; - assertForXStatement(opts?: Object): void; - assertFunction(opts?: Object): void; - assertFunctionParent(opts?: Object): void; - assertPureish(opts?: Object): void; - assertDeclaration(opts?: Object): void; - assertLVal(opts?: Object): void; - assertLiteral(opts?: Object): void; - assertImmutable(opts?: Object): void; - assertUserWhitespacable(opts?: Object): void; - assertMethod(opts?: Object): void; - assertObjectMember(opts?: Object): void; - assertProperty(opts?: Object): void; - assertUnaryLike(opts?: Object): void; - assertPattern(opts?: Object): void; - assertClass(opts?: Object): void; - assertModuleDeclaration(opts?: Object): void; - assertExportDeclaration(opts?: Object): void; - assertModuleSpecifier(opts?: Object): void; - assertFlow(opts?: Object): void; - assertFlowBaseAnnotation(opts?: Object): void; - assertFlowDeclaration(opts?: Object): void; - assertJSX(opts?: Object): void; - assertNumberLiteral(opts?: Object): void; - assertRegexLiteral(opts?: Object): void; - } - - export class Hub { - constructor(file: any, options: any); - file: any; - options: any; - } - - interface TraversalContext { - parentPath: NodePath; - scope: Scope; - state: any; - opts: any; - } +export interface TraverseOptions extends Visitor { + scope?: Scope; + noScope?: boolean; } + +export class Scope { + constructor(path: NodePath, parentScope?: Scope); + path: NodePath; + block: Node; + parentBlock: Node; + parent: Scope; + hub: Hub; + bindings: { [name: string]: Binding; }; + + /** Traverse node with current scope and path. */ + traverse(node: Node | Node[], opts?: TraverseOptions, state?: any): void; + + /** Generate a unique identifier and add it to the current scope. */ + generateDeclaredUidIdentifier(name?: string): t.Identifier; + + /** Generate a unique identifier. */ + generateUidIdentifier(name?: string): t.Identifier; + + /** Generate a unique `_id1` binding. */ + generateUid(name?: string): string; + + /** Generate a unique identifier based on a node. */ + generateUidIdentifierBasedOnNode(parent: Node, defaultName?: string): t.Identifier; + + /** + * Determine whether evaluating the specific input `node` is a consequenceless reference. ie. + * evaluating it wont result in potentially arbitrary code from being ran. The following are + * whitelisted and determined not to cause side effects: + * + * - `this` expressions + * - `super` expressions + * - Bound identifiers + */ + isStatic(node: Node): boolean; + + /** Possibly generate a memoised identifier if it is not static and has consequences. */ + maybeGenerateMemoised(node: Node, dontPush?: boolean): t.Identifier; + + checkBlockScopedCollisions(local: Node, kind: string, name: string, id: Object): void; + + rename(oldName: string, newName?: string, block?: Node): void; + + dump(): void; + + toArray(node: Node, i?: number): Node; + + registerDeclaration(path: NodePath): void; + + buildUndefinedNode(): Node; + + registerConstantViolation(path: NodePath): void; + + registerBinding(kind: string, path: NodePath, bindingPath?: NodePath): void; + + addGlobal(node: Node): void; + + hasUid(name: string): boolean; + + hasGlobal(name: string): boolean; + + hasReference(name: string): boolean; + + isPure(node: Node, constantsOnly?: boolean): boolean; + + setData(key: string, val: any): any; + + getData(key: string): any; + + removeData(key: string): void; + + push(opts: any): void; + + getProgramParent(): Scope; + + getFunctionParent(): Scope; + + getBlockParent(): Scope; + + /** Walks the scope tree and gathers **all** bindings. */ + getAllBindings(...kinds: string[]): Object; + + bindingIdentifierEquals(name: string, node: Node): boolean; + + getBinding(name: string): Binding; + + getOwnBinding(name: string): Binding; + + getBindingIdentifier(name: string): t.Identifier; + + getOwnBindingIdentifier(name: string): t.Identifier; + + hasOwnBinding(name: string): boolean; + + hasBinding(name: string, noGlobals?: boolean): boolean; + + parentHasBinding(name: string, noGlobals?: boolean): boolean; + + /** Move a binding of `name` to another `scope`. */ + moveBindingTo(name: string, scope: Scope): void; + + removeOwnBinding(name: string): void; + + removeBinding(name: string): void; +} + +export class Binding { + constructor(opts: { existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath; kind: 'var' | 'let' | 'const'; }); + identifier: t.Identifier; + scope: Scope; + path: NodePath; + kind: 'var' | 'let' | 'const'; + referenced: boolean; + references: number; + referencePaths: NodePath[]; + constant: boolean; + constantViolations: NodePath[]; +} + +export interface Visitor extends VisitNodeObject { + ArrayExpression?: VisitNode; + AssignmentExpression?: VisitNode; + LVal?: VisitNode; + Expression?: VisitNode; + BinaryExpression?: VisitNode; + Directive?: VisitNode; + DirectiveLiteral?: VisitNode; + BlockStatement?: VisitNode; + BreakStatement?: VisitNode; + Identifier?: VisitNode; + CallExpression?: VisitNode; + CatchClause?: VisitNode; + ConditionalExpression?: VisitNode; + ContinueStatement?: VisitNode; + DebuggerStatement?: VisitNode; + DoWhileStatement?: VisitNode; + Statement?: VisitNode; + EmptyStatement?: VisitNode; + ExpressionStatement?: VisitNode; + File?: VisitNode; + Program?: VisitNode; + ForInStatement?: VisitNode; + VariableDeclaration?: VisitNode; + ForStatement?: VisitNode; + FunctionDeclaration?: VisitNode; + FunctionExpression?: VisitNode; + IfStatement?: VisitNode; + LabeledStatement?: VisitNode; + StringLiteral?: VisitNode; + NumericLiteral?: VisitNode; + NullLiteral?: VisitNode; + BooleanLiteral?: VisitNode; + RegExpLiteral?: VisitNode; + LogicalExpression?: VisitNode; + MemberExpression?: VisitNode; + NewExpression?: VisitNode; + ObjectExpression?: VisitNode; + ObjectMethod?: VisitNode; + ObjectProperty?: VisitNode; + RestElement?: VisitNode; + ReturnStatement?: VisitNode; + SequenceExpression?: VisitNode; + SwitchCase?: VisitNode; + SwitchStatement?: VisitNode; + ThisExpression?: VisitNode; + ThrowStatement?: VisitNode; + TryStatement?: VisitNode; + UnaryExpression?: VisitNode; + UpdateExpression?: VisitNode; + VariableDeclarator?: VisitNode; + WhileStatement?: VisitNode; + WithStatement?: VisitNode; + AssignmentPattern?: VisitNode; + ArrayPattern?: VisitNode; + ArrowFunctionExpression?: VisitNode; + ClassBody?: VisitNode; + ClassDeclaration?: VisitNode; + ClassExpression?: VisitNode; + ExportAllDeclaration?: VisitNode; + ExportDefaultDeclaration?: VisitNode; + ExportNamedDeclaration?: VisitNode; + Declaration?: VisitNode; + ExportSpecifier?: VisitNode; + ForOfStatement?: VisitNode; + ImportDeclaration?: VisitNode; + ImportDefaultSpecifier?: VisitNode; + ImportNamespaceSpecifier?: VisitNode; + ImportSpecifier?: VisitNode; + MetaProperty?: VisitNode; + ClassMethod?: VisitNode; + ObjectPattern?: VisitNode; + SpreadElement?: VisitNode; + Super?: VisitNode; + TaggedTemplateExpression?: VisitNode; + TemplateLiteral?: VisitNode; + TemplateElement?: VisitNode; + YieldExpression?: VisitNode; + AnyTypeAnnotation?: VisitNode; + ArrayTypeAnnotation?: VisitNode; + BooleanTypeAnnotation?: VisitNode; + BooleanLiteralTypeAnnotation?: VisitNode; + NullLiteralTypeAnnotation?: VisitNode; + ClassImplements?: VisitNode; + ClassProperty?: VisitNode; + DeclareClass?: VisitNode; + DeclareFunction?: VisitNode; + DeclareInterface?: VisitNode; + DeclareModule?: VisitNode; + DeclareTypeAlias?: VisitNode; + DeclareVariable?: VisitNode; + ExistentialTypeParam?: VisitNode; + FunctionTypeAnnotation?: VisitNode; + FunctionTypeParam?: VisitNode; + GenericTypeAnnotation?: VisitNode; + InterfaceExtends?: VisitNode; + InterfaceDeclaration?: VisitNode; + IntersectionTypeAnnotation?: VisitNode; + MixedTypeAnnotation?: VisitNode; + NullableTypeAnnotation?: VisitNode; + NumericLiteralTypeAnnotation?: VisitNode; + NumberTypeAnnotation?: VisitNode; + StringLiteralTypeAnnotation?: VisitNode; + StringTypeAnnotation?: VisitNode; + ThisTypeAnnotation?: VisitNode; + TupleTypeAnnotation?: VisitNode; + TypeofTypeAnnotation?: VisitNode; + TypeAlias?: VisitNode; + TypeAnnotation?: VisitNode; + TypeCastExpression?: VisitNode; + TypeParameterDeclaration?: VisitNode; + TypeParameterInstantiation?: VisitNode; + ObjectTypeAnnotation?: VisitNode; + ObjectTypeCallProperty?: VisitNode; + ObjectTypeIndexer?: VisitNode; + ObjectTypeProperty?: VisitNode; + QualifiedTypeIdentifier?: VisitNode; + UnionTypeAnnotation?: VisitNode; + VoidTypeAnnotation?: VisitNode; + JSXAttribute?: VisitNode; + JSXIdentifier?: VisitNode; + JSXNamespacedName?: VisitNode; + JSXElement?: VisitNode; + JSXExpressionContainer?: VisitNode; + JSXClosingElement?: VisitNode; + JSXMemberExpression?: VisitNode; + JSXOpeningElement?: VisitNode; + JSXEmptyExpression?: VisitNode; + JSXSpreadAttribute?: VisitNode; + JSXText?: VisitNode; + Noop?: VisitNode; + ParenthesizedExpression?: VisitNode; + AwaitExpression?: VisitNode; + BindExpression?: VisitNode; + Decorator?: VisitNode; + DoExpression?: VisitNode; + ExportDefaultSpecifier?: VisitNode; + ExportNamespaceSpecifier?: VisitNode; + RestProperty?: VisitNode; + SpreadProperty?: VisitNode; + Binary?: VisitNode; + Scopable?: VisitNode; + BlockParent?: VisitNode; + Block?: VisitNode; + Terminatorless?: VisitNode; + CompletionStatement?: VisitNode; + Conditional?: VisitNode; + Loop?: VisitNode; + While?: VisitNode; + ExpressionWrapper?: VisitNode; + For?: VisitNode; + ForXStatement?: VisitNode; + Function?: VisitNode; + FunctionParent?: VisitNode; + Pureish?: VisitNode; + Literal?: VisitNode; + Immutable?: VisitNode; + UserWhitespacable?: VisitNode; + Method?: VisitNode; + ObjectMember?: VisitNode; + Property?: VisitNode; + UnaryLike?: VisitNode; + Pattern?: VisitNode; + Class?: VisitNode; + ModuleDeclaration?: VisitNode; + ExportDeclaration?: VisitNode; + ModuleSpecifier?: VisitNode; + Flow?: VisitNode; + FlowBaseAnnotation?: VisitNode; + FlowDeclaration?: VisitNode; + JSX?: VisitNode; +} + +export type VisitNode = VisitNodeFunction | VisitNodeObject; + +export type VisitNodeFunction = (path: NodePath, state: any) => void; + +export interface VisitNodeObject { + enter?(path: NodePath, state: any): void; + exit?(path: NodePath, state: any): void; +} + +export class NodePath { + constructor(hub: Hub, parent: Node); + parent: Node; + hub: Hub; + contexts: TraversalContext[]; + data: Object; + shouldSkip: boolean; + shouldStop: boolean; + removed: boolean; + state: any; + opts: Object; + skipKeys: Object; + parentPath: NodePath; + context: TraversalContext; + container: Object | Object[]; + listKey: string; + inList: boolean; + parentKey: string; + key: string; + node: T; + scope: Scope; + type: string; + typeAnnotation: Object; + + getScope(scope: Scope): Scope; + + setData(key: string, val: any): any; + + getData(key: string, def?: any): any; + + buildCodeFrameError(msg: string, Error: Error): Error; + + traverse(visitor: Visitor, state?: any): void; + + set(key: string, node: Node): void; + + getPathLocation(): string; + + debug(buildMessage: Function): void; + + // ------------------------- ancestry ------------------------- + /** + * Call the provided `callback` with the `NodePath`s of all the parents. + * When the `callback` returns a truthy value, we return that node path. + */ + findParent(callback: (path: NodePath) => boolean): NodePath; + + find(callback: (path: NodePath) => boolean): NodePath; + + /** Get the parent function of the current path. */ + getFunctionParent(): NodePath; + + /** Walk up the tree until we hit a parent node path in a list. */ + getStatementParent(): NodePath; + + /** + * Get the deepest common ancestor and then from it, get the earliest relationship path + * to that ancestor. + * + * Earliest is defined as being "before" all the other nodes in terms of list container + * position and visiting key. + */ + getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath; + + /** Get the earliest path in the tree where the provided `paths` intersect. */ + getDeepestCommonAncestorFrom(paths: NodePath[], filter?: Function): NodePath; + + /** + * Build an array of node paths containing the entire ancestry of the current node path. + * + * NOTE: The current node path is included in this. + */ + getAncestry(): NodePath[]; + + inType(...candidateTypes: string[]): boolean; + + // ------------------------- inference ------------------------- + /** Infer the type of the current `NodePath`. */ + getTypeAnnotation(): t.FlowTypeAnnotation; + + isBaseType(baseName: string, soft?: boolean): boolean; + + couldBeBaseType(name: string): boolean; + + baseTypeStrictlyMatches(right: NodePath): boolean; + + isGenericType(genericName: string): boolean; + + // ------------------------- replacement ------------------------- + /** + * Replace a node with an array of multiple. This method performs the following steps: + * + * - Inherit the comments of first provided node with that of the current node. + * - Insert the provided nodes after the current node. + * - Remove the current node. + */ + replaceWithMultiple(nodes: Node[]): void; + + /** + * Parse a string as an expression and replace the current node with the result. + * + * NOTE: This is typically not a good idea to use. Building source strings when + * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's + * easier to use, your transforms will be extremely brittle. + */ + replaceWithSourceString(replacement: any): void; + + /** Replace the current node with another. */ + replaceWith(replacement: Node | NodePath): void; + + /** + * This method takes an array of statements nodes and then explodes it + * into expressions. This method retains completion records which is + * extremely important to retain original semantics. + */ + replaceExpressionWithStatements(nodes: Node[]): Node; + + replaceInline(nodes: Node | Node[]): void; + + // ------------------------- evaluation ------------------------- + /** + * Walk the input `node` and statically evaluate if it's truthy. + * + * Returning `true` when we're sure that the expression will evaluate to a + * truthy value, `false` if we're sure that it will evaluate to a falsy + * value and `undefined` if we aren't sure. Because of this please do not + * rely on coercion when using this method and check with === if it's false. + */ + evaluateTruthy(): boolean; + + /** + * Walk the input `node` and statically evaluate it. + * + * Returns an object in the form `{ confident, value }`. `confident` indicates + * whether or not we had to drop out of evaluating the expression because of + * hitting an unknown node that we couldn't confidently find the value of. + * + * Example: + * + * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } + * t.evaluate(parse("!true")) // { confident: true, value: false } + * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined } + */ + evaluate(): { confident: boolean; value: any }; + + // ------------------------- introspection ------------------------- + /** + * Match the current node if it matches the provided `pattern`. + * + * For example, given the match `React.createClass` it would match the + * parsed nodes of `React.createClass` and `React["createClass"]`. + */ + matchesPattern(pattern: string, allowPartial?: boolean): boolean; + + /** + * Check whether we have the input `key`. If the `key` references an array then we check + * if the array has any items, otherwise we just check if it's falsy. + */ + has(key: string): boolean; + + isStatic(): boolean; + + /** Alias of `has`. */ + is(key: string): boolean; + + /** Opposite of `has`. */ + isnt(key: string): boolean; + + /** Check whether the path node `key` strict equals `value`. */ + equals(key: string, value: any): boolean; + + /** + * Check the type against our stored internal type of the node. This is handy when a node has + * been removed yet we still internally know the type and need it to calculate node replacement. + */ + isNodeType(type: string): boolean; + + /** + * This checks whether or not we're in one of the following positions: + * + * for (KEY in right); + * for (KEY;;); + * + * This is because these spots allow VariableDeclarations AND normal expressions so we need + * to tell the path replacement that it's ok to replace this with an expression. + */ + canHaveVariableDeclarationOrExpression(): boolean; + + /** + * This checks whether we are swapping an arrow function's body between an + * expression and a block statement (or vice versa). + * + * This is because arrow functions may implicitly return an expression, which + * is the same as containing a block statement. + */ + canSwapBetweenExpressionAndStatement(replacement: Node): boolean; + + /** Check whether the current path references a completion record */ + isCompletionRecord(allowInsideFunction?: boolean): boolean; + + /** + * Check whether or not the current `key` allows either a single statement or block statement + * so we can explode it if necessary. + */ + isStatementOrBlock(): boolean; + + /** Check if the currently assigned path references the `importName` of `moduleSource`. */ + referencesImport(moduleSource: string, importName: string): boolean; + + /** Get the source code associated with this node. */ + getSource(): string; + + // ------------------------- context ------------------------- + call(key: string): boolean; + + isBlacklisted(): boolean; + + visit(): boolean; + + skip(): void; + + skipKey(key: string): void; + + stop(): void; + + setScope(): void; + + setContext(context: TraversalContext): NodePath; + + popContext(): void; + + pushContext(context: TraversalContext): void; + + // ------------------------- removal ------------------------- + remove(): void; + + // ------------------------- modification ------------------------- + /** Insert the provided nodes before the current one. */ + insertBefore(nodes: Node | Node[]): any; + + /** + * Insert the provided nodes after the current one. When inserting nodes after an + * expression, ensure that the completion record is correct by pushing the current node. + */ + insertAfter(nodes: Node | Node[]): any; + + /** Update all sibling node paths after `fromIndex` by `incrementBy`. */ + updateSiblingKeys(fromIndex: number, incrementBy: number): void; + + /** Hoist the current node to the highest scope possible and return a UID referencing it. */ + hoist(scope: Scope): void; + + // ------------------------- family ------------------------- + getStatementParent(): NodePath; + + getOpposite(): NodePath; + + getCompletionRecords(): NodePath[]; + + getSibling(key: string): NodePath; + + get(key: string, context?: boolean | TraversalContext): NodePath; + + getBindingIdentifiers(duplicates?: boolean): Node[]; + + getOuterBindingIdentifiers(duplicates?: boolean): Node[]; + + // ------------------------- comments ------------------------- + /** Share comments amongst siblings. */ + shareCommentsWithSiblings(): void; + + addComment(type: string, content: string, line?: boolean): void; + + /** Give node `comments` of the specified `type`. */ + addComments(type: string, comments: any[]): void; + + // ------------------------- isXXX ------------------------- + isArrayExpression(opts?: Object): boolean; + isAssignmentExpression(opts?: Object): boolean; + isBinaryExpression(opts?: Object): boolean; + isDirective(opts?: Object): boolean; + isDirectiveLiteral(opts?: Object): boolean; + isBlockStatement(opts?: Object): boolean; + isBreakStatement(opts?: Object): boolean; + isCallExpression(opts?: Object): boolean; + isCatchClause(opts?: Object): boolean; + isConditionalExpression(opts?: Object): boolean; + isContinueStatement(opts?: Object): boolean; + isDebuggerStatement(opts?: Object): boolean; + isDoWhileStatement(opts?: Object): boolean; + isEmptyStatement(opts?: Object): boolean; + isExpressionStatement(opts?: Object): boolean; + isFile(opts?: Object): boolean; + isForInStatement(opts?: Object): boolean; + isForStatement(opts?: Object): boolean; + isFunctionDeclaration(opts?: Object): boolean; + isFunctionExpression(opts?: Object): boolean; + isIdentifier(opts?: Object): boolean; + isIfStatement(opts?: Object): boolean; + isLabeledStatement(opts?: Object): boolean; + isStringLiteral(opts?: Object): boolean; + isNumericLiteral(opts?: Object): boolean; + isNullLiteral(opts?: Object): boolean; + isBooleanLiteral(opts?: Object): boolean; + isRegExpLiteral(opts?: Object): boolean; + isLogicalExpression(opts?: Object): boolean; + isMemberExpression(opts?: Object): boolean; + isNewExpression(opts?: Object): boolean; + isProgram(opts?: Object): boolean; + isObjectExpression(opts?: Object): boolean; + isObjectMethod(opts?: Object): boolean; + isObjectProperty(opts?: Object): boolean; + isRestElement(opts?: Object): boolean; + isReturnStatement(opts?: Object): boolean; + isSequenceExpression(opts?: Object): boolean; + isSwitchCase(opts?: Object): boolean; + isSwitchStatement(opts?: Object): boolean; + isThisExpression(opts?: Object): boolean; + isThrowStatement(opts?: Object): boolean; + isTryStatement(opts?: Object): boolean; + isUnaryExpression(opts?: Object): boolean; + isUpdateExpression(opts?: Object): boolean; + isVariableDeclaration(opts?: Object): boolean; + isVariableDeclarator(opts?: Object): boolean; + isWhileStatement(opts?: Object): boolean; + isWithStatement(opts?: Object): boolean; + isAssignmentPattern(opts?: Object): boolean; + isArrayPattern(opts?: Object): boolean; + isArrowFunctionExpression(opts?: Object): boolean; + isClassBody(opts?: Object): boolean; + isClassDeclaration(opts?: Object): boolean; + isClassExpression(opts?: Object): boolean; + isExportAllDeclaration(opts?: Object): boolean; + isExportDefaultDeclaration(opts?: Object): boolean; + isExportNamedDeclaration(opts?: Object): boolean; + isExportSpecifier(opts?: Object): boolean; + isForOfStatement(opts?: Object): boolean; + isImportDeclaration(opts?: Object): boolean; + isImportDefaultSpecifier(opts?: Object): boolean; + isImportNamespaceSpecifier(opts?: Object): boolean; + isImportSpecifier(opts?: Object): boolean; + isMetaProperty(opts?: Object): boolean; + isClassMethod(opts?: Object): boolean; + isObjectPattern(opts?: Object): boolean; + isSpreadElement(opts?: Object): boolean; + isSuper(opts?: Object): boolean; + isTaggedTemplateExpression(opts?: Object): boolean; + isTemplateElement(opts?: Object): boolean; + isTemplateLiteral(opts?: Object): boolean; + isYieldExpression(opts?: Object): boolean; + isAnyTypeAnnotation(opts?: Object): boolean; + isArrayTypeAnnotation(opts?: Object): boolean; + isBooleanTypeAnnotation(opts?: Object): boolean; + isBooleanLiteralTypeAnnotation(opts?: Object): boolean; + isNullLiteralTypeAnnotation(opts?: Object): boolean; + isClassImplements(opts?: Object): boolean; + isClassProperty(opts?: Object): boolean; + isDeclareClass(opts?: Object): boolean; + isDeclareFunction(opts?: Object): boolean; + isDeclareInterface(opts?: Object): boolean; + isDeclareModule(opts?: Object): boolean; + isDeclareTypeAlias(opts?: Object): boolean; + isDeclareVariable(opts?: Object): boolean; + isExistentialTypeParam(opts?: Object): boolean; + isFunctionTypeAnnotation(opts?: Object): boolean; + isFunctionTypeParam(opts?: Object): boolean; + isGenericTypeAnnotation(opts?: Object): boolean; + isInterfaceExtends(opts?: Object): boolean; + isInterfaceDeclaration(opts?: Object): boolean; + isIntersectionTypeAnnotation(opts?: Object): boolean; + isMixedTypeAnnotation(opts?: Object): boolean; + isNullableTypeAnnotation(opts?: Object): boolean; + isNumericLiteralTypeAnnotation(opts?: Object): boolean; + isNumberTypeAnnotation(opts?: Object): boolean; + isStringLiteralTypeAnnotation(opts?: Object): boolean; + isStringTypeAnnotation(opts?: Object): boolean; + isThisTypeAnnotation(opts?: Object): boolean; + isTupleTypeAnnotation(opts?: Object): boolean; + isTypeofTypeAnnotation(opts?: Object): boolean; + isTypeAlias(opts?: Object): boolean; + isTypeAnnotation(opts?: Object): boolean; + isTypeCastExpression(opts?: Object): boolean; + isTypeParameterDeclaration(opts?: Object): boolean; + isTypeParameterInstantiation(opts?: Object): boolean; + isObjectTypeAnnotation(opts?: Object): boolean; + isObjectTypeCallProperty(opts?: Object): boolean; + isObjectTypeIndexer(opts?: Object): boolean; + isObjectTypeProperty(opts?: Object): boolean; + isQualifiedTypeIdentifier(opts?: Object): boolean; + isUnionTypeAnnotation(opts?: Object): boolean; + isVoidTypeAnnotation(opts?: Object): boolean; + isJSXAttribute(opts?: Object): boolean; + isJSXClosingElement(opts?: Object): boolean; + isJSXElement(opts?: Object): boolean; + isJSXEmptyExpression(opts?: Object): boolean; + isJSXExpressionContainer(opts?: Object): boolean; + isJSXIdentifier(opts?: Object): boolean; + isJSXMemberExpression(opts?: Object): boolean; + isJSXNamespacedName(opts?: Object): boolean; + isJSXOpeningElement(opts?: Object): boolean; + isJSXSpreadAttribute(opts?: Object): boolean; + isJSXText(opts?: Object): boolean; + isNoop(opts?: Object): boolean; + isParenthesizedExpression(opts?: Object): boolean; + isAwaitExpression(opts?: Object): boolean; + isBindExpression(opts?: Object): boolean; + isDecorator(opts?: Object): boolean; + isDoExpression(opts?: Object): boolean; + isExportDefaultSpecifier(opts?: Object): boolean; + isExportNamespaceSpecifier(opts?: Object): boolean; + isRestProperty(opts?: Object): boolean; + isSpreadProperty(opts?: Object): boolean; + isExpression(opts?: Object): boolean; + isBinary(opts?: Object): boolean; + isScopable(opts?: Object): boolean; + isBlockParent(opts?: Object): boolean; + isBlock(opts?: Object): boolean; + isStatement(opts?: Object): boolean; + isTerminatorless(opts?: Object): boolean; + isCompletionStatement(opts?: Object): boolean; + isConditional(opts?: Object): boolean; + isLoop(opts?: Object): boolean; + isWhile(opts?: Object): boolean; + isExpressionWrapper(opts?: Object): boolean; + isFor(opts?: Object): boolean; + isForXStatement(opts?: Object): boolean; + isFunction(opts?: Object): boolean; + isFunctionParent(opts?: Object): boolean; + isPureish(opts?: Object): boolean; + isDeclaration(opts?: Object): boolean; + isLVal(opts?: Object): boolean; + isLiteral(opts?: Object): boolean; + isImmutable(opts?: Object): boolean; + isUserWhitespacable(opts?: Object): boolean; + isMethod(opts?: Object): boolean; + isObjectMember(opts?: Object): boolean; + isProperty(opts?: Object): boolean; + isUnaryLike(opts?: Object): boolean; + isPattern(opts?: Object): boolean; + isClass(opts?: Object): boolean; + isModuleDeclaration(opts?: Object): boolean; + isExportDeclaration(opts?: Object): boolean; + isModuleSpecifier(opts?: Object): boolean; + isFlow(opts?: Object): boolean; + isFlowBaseAnnotation(opts?: Object): boolean; + isFlowDeclaration(opts?: Object): boolean; + isJSX(opts?: Object): boolean; + isNumberLiteral(opts?: Object): boolean; + isRegexLiteral(opts?: Object): boolean; + isReferencedIdentifier(opts?: Object): boolean; + isReferencedMemberExpression(opts?: Object): boolean; + isBindingIdentifier(opts?: Object): boolean; + isScope(opts?: Object): boolean; + isReferenced(opts?: Object): boolean; + isBlockScoped(opts?: Object): boolean; + isVar(opts?: Object): boolean; + isUser(opts?: Object): boolean; + isGenerated(opts?: Object): boolean; + isPure(opts?: Object): boolean; + + // ------------------------- assertXXX ------------------------- + assertArrayExpression(opts?: Object): void; + assertAssignmentExpression(opts?: Object): void; + assertBinaryExpression(opts?: Object): void; + assertDirective(opts?: Object): void; + assertDirectiveLiteral(opts?: Object): void; + assertBlockStatement(opts?: Object): void; + assertBreakStatement(opts?: Object): void; + assertCallExpression(opts?: Object): void; + assertCatchClause(opts?: Object): void; + assertConditionalExpression(opts?: Object): void; + assertContinueStatement(opts?: Object): void; + assertDebuggerStatement(opts?: Object): void; + assertDoWhileStatement(opts?: Object): void; + assertEmptyStatement(opts?: Object): void; + assertExpressionStatement(opts?: Object): void; + assertFile(opts?: Object): void; + assertForInStatement(opts?: Object): void; + assertForStatement(opts?: Object): void; + assertFunctionDeclaration(opts?: Object): void; + assertFunctionExpression(opts?: Object): void; + assertIdentifier(opts?: Object): void; + assertIfStatement(opts?: Object): void; + assertLabeledStatement(opts?: Object): void; + assertStringLiteral(opts?: Object): void; + assertNumericLiteral(opts?: Object): void; + assertNullLiteral(opts?: Object): void; + assertBooleanLiteral(opts?: Object): void; + assertRegExpLiteral(opts?: Object): void; + assertLogicalExpression(opts?: Object): void; + assertMemberExpression(opts?: Object): void; + assertNewExpression(opts?: Object): void; + assertProgram(opts?: Object): void; + assertObjectExpression(opts?: Object): void; + assertObjectMethod(opts?: Object): void; + assertObjectProperty(opts?: Object): void; + assertRestElement(opts?: Object): void; + assertReturnStatement(opts?: Object): void; + assertSequenceExpression(opts?: Object): void; + assertSwitchCase(opts?: Object): void; + assertSwitchStatement(opts?: Object): void; + assertThisExpression(opts?: Object): void; + assertThrowStatement(opts?: Object): void; + assertTryStatement(opts?: Object): void; + assertUnaryExpression(opts?: Object): void; + assertUpdateExpression(opts?: Object): void; + assertVariableDeclaration(opts?: Object): void; + assertVariableDeclarator(opts?: Object): void; + assertWhileStatement(opts?: Object): void; + assertWithStatement(opts?: Object): void; + assertAssignmentPattern(opts?: Object): void; + assertArrayPattern(opts?: Object): void; + assertArrowFunctionExpression(opts?: Object): void; + assertClassBody(opts?: Object): void; + assertClassDeclaration(opts?: Object): void; + assertClassExpression(opts?: Object): void; + assertExportAllDeclaration(opts?: Object): void; + assertExportDefaultDeclaration(opts?: Object): void; + assertExportNamedDeclaration(opts?: Object): void; + assertExportSpecifier(opts?: Object): void; + assertForOfStatement(opts?: Object): void; + assertImportDeclaration(opts?: Object): void; + assertImportDefaultSpecifier(opts?: Object): void; + assertImportNamespaceSpecifier(opts?: Object): void; + assertImportSpecifier(opts?: Object): void; + assertMetaProperty(opts?: Object): void; + assertClassMethod(opts?: Object): void; + assertObjectPattern(opts?: Object): void; + assertSpreadElement(opts?: Object): void; + assertSuper(opts?: Object): void; + assertTaggedTemplateExpression(opts?: Object): void; + assertTemplateElement(opts?: Object): void; + assertTemplateLiteral(opts?: Object): void; + assertYieldExpression(opts?: Object): void; + assertAnyTypeAnnotation(opts?: Object): void; + assertArrayTypeAnnotation(opts?: Object): void; + assertBooleanTypeAnnotation(opts?: Object): void; + assertBooleanLiteralTypeAnnotation(opts?: Object): void; + assertNullLiteralTypeAnnotation(opts?: Object): void; + assertClassImplements(opts?: Object): void; + assertClassProperty(opts?: Object): void; + assertDeclareClass(opts?: Object): void; + assertDeclareFunction(opts?: Object): void; + assertDeclareInterface(opts?: Object): void; + assertDeclareModule(opts?: Object): void; + assertDeclareTypeAlias(opts?: Object): void; + assertDeclareVariable(opts?: Object): void; + assertExistentialTypeParam(opts?: Object): void; + assertFunctionTypeAnnotation(opts?: Object): void; + assertFunctionTypeParam(opts?: Object): void; + assertGenericTypeAnnotation(opts?: Object): void; + assertInterfaceExtends(opts?: Object): void; + assertInterfaceDeclaration(opts?: Object): void; + assertIntersectionTypeAnnotation(opts?: Object): void; + assertMixedTypeAnnotation(opts?: Object): void; + assertNullableTypeAnnotation(opts?: Object): void; + assertNumericLiteralTypeAnnotation(opts?: Object): void; + assertNumberTypeAnnotation(opts?: Object): void; + assertStringLiteralTypeAnnotation(opts?: Object): void; + assertStringTypeAnnotation(opts?: Object): void; + assertThisTypeAnnotation(opts?: Object): void; + assertTupleTypeAnnotation(opts?: Object): void; + assertTypeofTypeAnnotation(opts?: Object): void; + assertTypeAlias(opts?: Object): void; + assertTypeAnnotation(opts?: Object): void; + assertTypeCastExpression(opts?: Object): void; + assertTypeParameterDeclaration(opts?: Object): void; + assertTypeParameterInstantiation(opts?: Object): void; + assertObjectTypeAnnotation(opts?: Object): void; + assertObjectTypeCallProperty(opts?: Object): void; + assertObjectTypeIndexer(opts?: Object): void; + assertObjectTypeProperty(opts?: Object): void; + assertQualifiedTypeIdentifier(opts?: Object): void; + assertUnionTypeAnnotation(opts?: Object): void; + assertVoidTypeAnnotation(opts?: Object): void; + assertJSXAttribute(opts?: Object): void; + assertJSXClosingElement(opts?: Object): void; + assertJSXElement(opts?: Object): void; + assertJSXEmptyExpression(opts?: Object): void; + assertJSXExpressionContainer(opts?: Object): void; + assertJSXIdentifier(opts?: Object): void; + assertJSXMemberExpression(opts?: Object): void; + assertJSXNamespacedName(opts?: Object): void; + assertJSXOpeningElement(opts?: Object): void; + assertJSXSpreadAttribute(opts?: Object): void; + assertJSXText(opts?: Object): void; + assertNoop(opts?: Object): void; + assertParenthesizedExpression(opts?: Object): void; + assertAwaitExpression(opts?: Object): void; + assertBindExpression(opts?: Object): void; + assertDecorator(opts?: Object): void; + assertDoExpression(opts?: Object): void; + assertExportDefaultSpecifier(opts?: Object): void; + assertExportNamespaceSpecifier(opts?: Object): void; + assertRestProperty(opts?: Object): void; + assertSpreadProperty(opts?: Object): void; + assertExpression(opts?: Object): void; + assertBinary(opts?: Object): void; + assertScopable(opts?: Object): void; + assertBlockParent(opts?: Object): void; + assertBlock(opts?: Object): void; + assertStatement(opts?: Object): void; + assertTerminatorless(opts?: Object): void; + assertCompletionStatement(opts?: Object): void; + assertConditional(opts?: Object): void; + assertLoop(opts?: Object): void; + assertWhile(opts?: Object): void; + assertExpressionWrapper(opts?: Object): void; + assertFor(opts?: Object): void; + assertForXStatement(opts?: Object): void; + assertFunction(opts?: Object): void; + assertFunctionParent(opts?: Object): void; + assertPureish(opts?: Object): void; + assertDeclaration(opts?: Object): void; + assertLVal(opts?: Object): void; + assertLiteral(opts?: Object): void; + assertImmutable(opts?: Object): void; + assertUserWhitespacable(opts?: Object): void; + assertMethod(opts?: Object): void; + assertObjectMember(opts?: Object): void; + assertProperty(opts?: Object): void; + assertUnaryLike(opts?: Object): void; + assertPattern(opts?: Object): void; + assertClass(opts?: Object): void; + assertModuleDeclaration(opts?: Object): void; + assertExportDeclaration(opts?: Object): void; + assertModuleSpecifier(opts?: Object): void; + assertFlow(opts?: Object): void; + assertFlowBaseAnnotation(opts?: Object): void; + assertFlowDeclaration(opts?: Object): void; + assertJSX(opts?: Object): void; + assertNumberLiteral(opts?: Object): void; + assertRegexLiteral(opts?: Object): void; +} + +export class Hub { + constructor(file: any, options: any); + file: any; + options: any; +} + +interface TraversalContext { + parentPath: NodePath; + scope: Scope; + state: any; + opts: any; +} + diff --git a/babel-types/index.d.ts b/babel-types/index.d.ts index d10302370a..b3b0f966c6 100644 --- a/babel-types/index.d.ts +++ b/babel-types/index.d.ts @@ -3,1401 +3,1399 @@ // Definitions by: Troy Gerwien // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "babel-types" { - - export interface Comment { - value: string; - start: number; - end: number; - loc: SourceLocation; - } - - export interface CommentBlock extends Comment { - type: "CommentBlock"; - } - - export interface CommentLine extends Comment { - type: "CommentLine"; - } - - export interface SourceLocation { - start: { - line: number; - column: number; - }; - - end: { - line: number; - column: number; - }; - } - - export interface Node { - type: string; - leadingComments?: Array; - innerComments?: Array; - trailingComments?: Array; - start: number; - end: number; - loc: SourceLocation; - } - - export interface ArrayExpression extends Node { - type: "ArrayExpression"; - elements: Array; - } - - export interface AssignmentExpression extends Node { - type: "AssignmentExpression"; - operator: "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&="; - left: LVal; - right: Expression; - } - - export interface BinaryExpression extends Node { - type: "BinaryExpression"; - operator: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<="; - left: Expression; - right: Expression; - } - - export interface Directive extends Node { - type: "Directive"; - value: DirectiveLiteral; - } - - export interface DirectiveLiteral extends Node { - type: "DirectiveLiteral"; - value: string; - } - - export interface BlockStatement extends Node { - type: "BlockStatement"; - directives?: Directive[]; - body: Statement[]; - } - - export interface BreakStatement extends Node { - type: "BreakStatement"; - label: Identifier; - } - - export interface CallExpression extends Node { - type: "CallExpression"; - callee: Expression | Super; - arguments: Array; - } - - export interface CatchClause extends Node { - type: "CatchClause"; - param: Pattern; - body: BlockStatement; - } - - export interface ConditionalExpression extends Node { - type: "ConditionalExpression"; - test: Expression; - consequent: Expression; - alternate: Expression; - } - - export interface ContinueStatement extends Node { - type: "ContinueStatement"; - label: Identifier; - } - - export interface DebuggerStatement extends Node { - type: "DebuggerStatement"; - } - - export interface DoWhileStatement extends Node { - type: "DoWhileStatement"; - test: Expression; - body: Statement; - } - - export interface EmptyStatement extends Node { - type: "EmptyStatement"; - } - - export interface ExpressionStatement extends Node { - type: "ExpressionStatement"; - expression: Expression; - } - - export interface File extends Node { - type: "File"; - program: Program; - comments: Comment[]; - tokens: any[]; - } - - export interface ForInStatement extends Node { - type: "ForInStatement"; - left: VariableDeclaration | LVal; - right: Expression; - body: Statement; - } - - export interface ForStatement extends Node { - type: "ForStatement"; - init: VariableDeclaration | Expression; - test: Expression; - update: Expression; - body: Statement; - } - - export interface FunctionDeclaration extends Node { - type: "FunctionDeclaration"; - id: Identifier; - params: Pattern[]; - body: BlockStatement; - generator: boolean; - async: boolean; - returnType?: TypeAnnotation; - typeParameters?: TypeParameterDeclaration; - } - - export interface FunctionExpression extends Node { - type: "FunctionExpression"; - id: Identifier; - params: Pattern[]; - body: BlockStatement; - generator: boolean; - async: boolean; - returnType?: TypeAnnotation; - typeParameters?: TypeParameterDeclaration; - } - - export interface Identifier extends Node { - type: "Identifier"; - name: string; - typeAnnotation?: TypeAnnotation; - } - - export interface IfStatement extends Node { - type: "IfStatement"; - test: Expression; - consequent: Statement; - alternate: Statement; - } - - export interface LabeledStatement extends Node { - type: "LabeledStatement"; - label: Identifier; - body: Statement; - } - - export interface StringLiteral extends Node { - type: "StringLiteral"; - value: string; - } - - export interface NumericLiteral extends Node { - type: "NumericLiteral"; - value: number; - } - - export interface NullLiteral extends Node { - type: "NullLiteral"; - } - - export interface BooleanLiteral extends Node { - type: "BooleanLiteral"; - value: boolean; - } - - export interface RegExpLiteral extends Node { - type: "RegExpLiteral"; - pattern: string; - flags?: string; - } - - export interface LogicalExpression extends Node { - type: "LogicalExpression"; - operator: "||" | "&&"; - left: Expression; - right: Expression; - } - - export interface MemberExpression extends Node { - type: "MemberExpression"; - object: Expression | Super; - property: Expression; - computed: boolean; - } - - export interface NewExpression extends Node { - type: "NewExpression"; - callee: Expression | Super; - arguments: Array; - } - - export interface Program extends Node { - type: "Program"; - sourceType: "script" | "module"; - directives?: Directive[]; - body: Array; - } - - export interface ObjectExpression extends Node { - type: "ObjectExpression"; - properties: Array; - } - - export interface ObjectMethod extends Node { - type: "ObjectMethod"; - key: Expression; - kind: "get" | "set" | "method"; - shorthand: boolean; - computed: boolean; - value: Expression; - decorators?: Decorator[]; - id: Identifier; - params: Pattern[]; - body: BlockStatement; - generator: boolean; - async: boolean; - returnType?: TypeAnnotation; - typeParameters?: TypeParameterDeclaration; - } - - export interface ObjectProperty extends Node { - type: "ObjectProperty"; - key: Expression; - computed: boolean; - value: Expression; - decorators?: Decorator[]; - shorthand: boolean; - } - - export interface RestElement extends Node { - type: "RestElement"; - argument: LVal; - typeAnnotation?: TypeAnnotation; - } - - export interface ReturnStatement extends Node { - type: "ReturnStatement"; - argument: Expression; - } - - export interface SequenceExpression extends Node { - type: "SequenceExpression"; - expressions: Expression[]; - } - - export interface SwitchCase extends Node { - type: "SwitchCase"; - test: Expression; - consequent: Statement[]; - } - - export interface SwitchStatement extends Node { - type: "SwitchStatement"; - discriminant: Expression; - cases: SwitchCase[]; - } - - export interface ThisExpression extends Node { - type: "ThisExpression"; - } - - export interface ThrowStatement extends Node { - type: "ThrowStatement"; - argument: Expression; - } - - export interface TryStatement extends Node { - type: "TryStatement"; - block: BlockStatement; - handler: CatchClause; - finalizer: BlockStatement; - } - - export interface UnaryExpression extends Node { - type: "UnaryExpression"; - operator: "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; - prefix: boolean; - argument: Expression; - } - - export interface UpdateExpression extends Node { - type: "UpdateExpression"; - operator: "++" | "--"; - prefix: boolean; - argument: Expression; - } - - export interface VariableDeclaration extends Node { - type: "VariableDeclaration"; - declarations: VariableDeclarator[]; - kind: "var" | "let" | "const"; - } - - export interface VariableDeclarator extends Node { - type: "VariableDeclarator"; - id: LVal; - init: Expression; - } - - export interface WhileStatement extends Node { - type: "WhileStatement"; - test: Expression; - body: Statement; - } - - export interface WithStatement extends Node { - type: "WithStatement"; - object: Expression; - body: BlockStatement | Statement; - } - - export interface AssignmentPattern extends Node { - type: "AssignmentPattern"; - left: Pattern; - right: Expression; - } - - export interface ArrayPattern extends Node { - type: "ArrayPattern"; - elements: Array; - typeAnnotation?: TypeAnnotation; - } - - export interface ArrowFunctionExpression extends Node { - type: "ArrowFunctionExpression"; - id: Identifier; - params: Pattern[]; - body: BlockStatement | Expression; - generator: boolean; - async: boolean; - expression: boolean; - returnType?: TypeAnnotation; - typeParameters?: TypeParameterDeclaration; - } - - export interface ClassBody extends Node { - type: "ClassBody"; - body: Array; - } - - export interface ClassDeclaration extends Node { - type: "ClassDeclaration"; - id: Identifier; - superClass: Expression; - body: ClassBody; - decorators?: Decorator[]; - implements?: ClassImplements[]; - mixins?: any[]; - typeParameters?: TypeParameterDeclaration; - superTypeParameters?: TypeParameterInstantiation; - } - - export interface ClassExpression extends Node { - type: "ClassExpression"; - id: Identifier; - superClass: Expression; - body: ClassBody; - decorators?: Decorator[]; - implements?: ClassImplements[]; - mixins?: any[]; - typeParameters?: TypeParameterDeclaration; - superTypeParameters?: TypeParameterInstantiation; - } - - export interface ExportAllDeclaration extends Node { - type: "ExportAllDeclaration"; - source: StringLiteral; - } - - export interface ExportDefaultDeclaration extends Node { - type: "ExportDefaultDeclaration"; - declaration: Declaration | Expression; - } - - export interface ExportNamedDeclaration extends Node { - type: "ExportNamedDeclaration"; - declaration: Declaration; - specifiers: ExportSpecifier[]; - source: StringLiteral; - } - - export interface ExportSpecifier extends Node { - type: "ExportSpecifier"; - local: Identifier; - imported: Identifier; - exported: Identifier; - } - - export interface ForOfStatement extends Node { - type: "ForOfStatement"; - left: VariableDeclaration | LVal; - right: Expression; - body: Statement; - } - - export interface ImportDeclaration extends Node { - type: "ImportDeclaration"; - specifiers: Array; - source: StringLiteral; - } - - export interface ImportDefaultSpecifier extends Node { - type: "ImportDefaultSpecifier"; - local: Identifier; - } - - export interface ImportNamespaceSpecifier extends Node { - type: "ImportNamespaceSpecifier"; - local: Identifier; - } - - export interface ImportSpecifier extends Node { - type: "ImportSpecifier"; - local: Identifier; - imported: Identifier; - } - - export interface MetaProperty extends Node { - type: "MetaProperty"; - meta: Identifier; - property: Identifier; - } - - export interface ClassMethod extends Node { - type: "ClassMethod"; - key: Expression; - value?: FunctionExpression; - kind: "constructor" | "method" | "get" | "set"; - computed: boolean; - static: boolean; - decorators?: Decorator[]; - id: Identifier; - params: Pattern[]; - body: BlockStatement; - generator: boolean; - async: boolean; - expression: boolean; - returnType?: TypeAnnotation; - typeParameters?: TypeParameterDeclaration; - } - - // See: https://github.com/babel/babel/blob/master/doc/ast/spec.md#objectpattern - export interface AssignmentProperty extends Node { - type: "ObjectProperty"; - key: Expression; - computed: boolean; - value: Pattern; - decorators?: Decorator[]; - shorthand: boolean; - } - - export interface ObjectPattern extends Node { - type: "ObjectPattern"; - properties: Array; - typeAnnotation?: TypeAnnotation; - } - - export interface SpreadElement extends Node { - type: "SpreadElement"; - argument: Expression; - } - - export interface Super extends Node { - type: "Super"; - } - - export interface TaggedTemplateExpression extends Node { - type: "TaggedTemplateExpression"; - tag: Expression; - quasi: TemplateLiteral; - } - - export interface TemplateElement extends Node { - type: "TemplateElement"; - tail: boolean; - value: { - cooked: string; - raw: string; - }; - } - - export interface TemplateLiteral extends Node { - type: "TemplateLiteral"; - quasis: TemplateElement[]; - expressions: Expression[]; - } - - export interface YieldExpression extends Node { - type: "YieldExpression"; - argument: Expression; - delegate: boolean; - } - - export interface AnyTypeAnnotation extends Node { - type: "AnyTypeAnnotation"; - } - - export interface ArrayTypeAnnotation extends Node { - type: "ArrayTypeAnnotation"; - elementType: FlowTypeAnnotation; - } - - export interface BooleanTypeAnnotation extends Node { - type: "BooleanTypeAnnotation"; - } - - export interface BooleanLiteralTypeAnnotation extends Node { - type: "BooleanLiteralTypeAnnotation"; - } - - export interface NullLiteralTypeAnnotation extends Node { - type: "NullLiteralTypeAnnotation"; - } - - export interface ClassImplements extends Node { - type: "ClassImplements"; - id: Identifier; - typeParameters: TypeParameterInstantiation; - } - - export interface ClassProperty extends Node { - type: "ClassProperty"; - key: Identifier; - value: Expression; - decorators?: Decorator[]; - typeAnnotation?: TypeAnnotation; - } - - export interface DeclareClass extends Node { - type: "DeclareClass"; - id: Identifier; - typeParameters: TypeParameterDeclaration; - extends: InterfaceExtends[]; - body: ObjectTypeAnnotation; - } - - export interface DeclareFunction extends Node { - type: "DeclareFunction"; - id: Identifier; - } - - export interface DeclareInterface extends Node { - type: "DeclareInterface"; - id: Identifier; - typeParameters: TypeParameterDeclaration; - extends: InterfaceExtends[]; - body: ObjectTypeAnnotation; - } - - export interface DeclareModule extends Node { - type: "DeclareModule"; - id: StringLiteral | Identifier; - body: BlockStatement; - } - - export interface DeclareTypeAlias extends Node { - type: "DeclareTypeAlias"; - id: Identifier; - typeParameters: TypeParameterDeclaration; - right: FlowTypeAnnotation; - } - - export interface DeclareVariable extends Node { - type: "DeclareVariable"; - id: Identifier; - } - - export interface ExistentialTypeParam extends Node { - type: "ExistentialTypeParam"; - } - - export interface FunctionTypeAnnotation extends Node { - type: "FunctionTypeAnnotation"; - typeParameters: TypeParameterDeclaration; - params: FunctionTypeParam[]; - rest: FunctionTypeParam; - returnType: FlowTypeAnnotation; - } - - export interface FunctionTypeParam extends Node { - type: "FunctionTypeParam"; - name: Identifier; - typeAnnotation: FlowTypeAnnotation; - } - - export interface GenericTypeAnnotation extends Node { - type: "GenericTypeAnnotation"; - id: Identifier; - typeParameters: TypeParameterInstantiation; - } - - export interface InterfaceExtends extends Node { - type: "InterfaceExtends"; - id: Identifier; - typeParameters: TypeParameterInstantiation; - } - - export interface InterfaceDeclaration extends Node { - type: "InterfaceDeclaration"; - id: Identifier; - typeParameters: TypeParameterDeclaration; - extends: InterfaceExtends[]; - mixins?: any[]; - body: ObjectTypeAnnotation; - } - - export interface IntersectionTypeAnnotation extends Node { - type: "IntersectionTypeAnnotation"; - types: FlowTypeAnnotation[]; - } - - export interface MixedTypeAnnotation extends Node { - type: "MixedTypeAnnotation"; - } - - export interface NullableTypeAnnotation extends Node { - type: "NullableTypeAnnotation"; - typeAnnotation: FlowTypeAnnotation; - } - - export interface NumericLiteralTypeAnnotation extends Node { - type: "NumericLiteralTypeAnnotation"; - } - - export interface NumberTypeAnnotation extends Node { - type: "NumberTypeAnnotation"; - } - - export interface StringLiteralTypeAnnotation extends Node { - type: "StringLiteralTypeAnnotation"; - } - - export interface StringTypeAnnotation extends Node { - type: "StringTypeAnnotation"; - } - - export interface ThisTypeAnnotation extends Node { - type: "ThisTypeAnnotation"; - } - - export interface TupleTypeAnnotation extends Node { - type: "TupleTypeAnnotation"; - types: FlowTypeAnnotation[]; - } - - export interface TypeofTypeAnnotation extends Node { - type: "TypeofTypeAnnotation"; - argument: FlowTypeAnnotation; - } - - export interface TypeAlias extends Node { - type: "TypeAlias"; - id: Identifier; - typeParameters: TypeParameterDeclaration; - right: FlowTypeAnnotation; - } - - export interface TypeAnnotation extends Node { - type: "TypeAnnotation"; - typeAnnotation: FlowTypeAnnotation; - } - - export interface TypeCastExpression extends Node { - type: "TypeCastExpression"; - expression: Expression; - typeAnnotation: FlowTypeAnnotation; - } - - export interface TypeParameterDeclaration extends Node { - type: "TypeParameterDeclaration"; - params: Identifier[]; - } - - export interface TypeParameterInstantiation extends Node { - type: "TypeParameterInstantiation"; - params: FlowTypeAnnotation[]; - } - - export interface ObjectTypeAnnotation extends Node { - type: "ObjectTypeAnnotation"; - properties: ObjectTypeProperty[]; - indexers: ObjectTypeIndexer[]; - callProperties: ObjectTypeCallProperty[]; - } - - export interface ObjectTypeCallProperty extends Node { - type: "ObjectTypeCallProperty"; - value: FlowTypeAnnotation; - } - - export interface ObjectTypeIndexer extends Node { - type: "ObjectTypeIndexer"; - id: Expression; - key: FlowTypeAnnotation; - value: FlowTypeAnnotation; - } - - export interface ObjectTypeProperty extends Node { - type: "ObjectTypeProperty"; - key: Expression; - value: FlowTypeAnnotation; - } - - export interface QualifiedTypeIdentifier extends Node { - type: "QualifiedTypeIdentifier"; - id: Identifier; - qualification: Identifier | QualifiedTypeIdentifier; - } - - export interface UnionTypeAnnotation extends Node { - type: "UnionTypeAnnotation"; - types: FlowTypeAnnotation[]; - } - - export interface VoidTypeAnnotation extends Node { - type: "VoidTypeAnnotation"; - } - - export interface JSXAttribute extends Node { - type: "JSXAttribute"; - name: JSXIdentifier | JSXNamespacedName; - value: JSXElement | StringLiteral | JSXExpressionContainer; - } - - export interface JSXClosingElement extends Node { - type: "JSXClosingElement"; - name: JSXIdentifier | JSXMemberExpression; - } - - export interface JSXElement extends Node { - type: "JSXElement"; - openingElement: JSXOpeningElement; - closingElement: JSXClosingElement; - children: Array; - selfClosing?: boolean; - } - - export interface JSXEmptyExpression extends Node { - type: "JSXEmptyExpression"; - } - - export interface JSXExpressionContainer extends Node { - type: "JSXExpressionContainer"; - expression: Expression; - } - - export interface JSXIdentifier extends Node { - type: "JSXIdentifier"; - name: string; - } - - export interface JSXMemberExpression extends Node { - type: "JSXMemberExpression"; - object: JSXMemberExpression | JSXIdentifier; - property: JSXIdentifier; - } - - export interface JSXNamespacedName extends Node { - type: "JSXNamespacedName"; - namespace: JSXIdentifier; - name: JSXIdentifier; - } - - export interface JSXOpeningElement extends Node { - type: "JSXOpeningElement"; - name: JSXIdentifier | JSXMemberExpression; - selfClosing: boolean; - attributes: JSXAttribute[]; - } - - export interface JSXSpreadAttribute extends Node { - type: "JSXSpreadAttribute"; - argument: Expression; - } - - export interface JSXText extends Node { - type: "JSXText"; - value: string; - } - - export interface Noop extends Node { - type: "Noop"; - } - - export interface ParenthesizedExpression extends Node { - type: "ParenthesizedExpression"; - expression: Expression; - } - - export interface AwaitExpression extends Node { - type: "AwaitExpression"; - argument: Expression; - } - - export interface BindExpression extends Node { - type: "BindExpression"; - object: Expression; - callee: Expression; - } - - export interface Decorator extends Node { - type: "Decorator"; - expression: Expression; - } - - export interface DoExpression extends Node { - type: "DoExpression"; - body: BlockStatement; - } - - export interface ExportDefaultSpecifier extends Node { - type: "ExportDefaultSpecifier"; - exported: Identifier; - } - - export interface ExportNamespaceSpecifier extends Node { - type: "ExportNamespaceSpecifier"; - exported: Identifier; - } - - export interface RestProperty extends Node { - type: "RestProperty"; - argument: LVal; - } - - export interface SpreadProperty extends Node { - type: "SpreadProperty"; - argument: Expression; - } - - export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; - export type Binary = BinaryExpression | LogicalExpression; - export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; - export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; - export type Block = BlockStatement | Program; - export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; - export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; - export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; - export type Conditional = ConditionalExpression | IfStatement; - export type Loop = DoWhileStatement | ForInStatement | ForStatement | WhileStatement | ForOfStatement; - export type While = DoWhileStatement | WhileStatement; - export type ExpressionWrapper = ExpressionStatement | TypeCastExpression | ParenthesizedExpression; - export type For = ForInStatement | ForStatement | ForOfStatement; - export type ForXStatement = ForInStatement | ForOfStatement; - export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; - export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; - export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; - export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; - export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; - export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral; - export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; - export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty; - export type Method = ObjectMethod | ClassMethod; - export type ObjectMember = ObjectMethod | ObjectProperty; - export type Property = ObjectProperty | ClassProperty; - export type UnaryLike = UnaryExpression | SpreadElement | RestProperty | SpreadProperty; - export type Pattern = AssignmentPattern | ArrayPattern | ObjectPattern; - export type Class = ClassDeclaration | ClassExpression; - export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; - export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; - export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; - export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; - export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; - export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; - export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; - export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; - - export function arrayExpression(elements?: Array): ArrayExpression; - export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; - export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; - export function directive(value?: DirectiveLiteral): Directive; - export function directiveLiteral(value?: string): DirectiveLiteral; - export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; - export function breakStatement(label?: Identifier): BreakStatement; - export function callExpression(callee?: Expression, _arguments?: Array): CallExpression; - export function catchClause(param?: Identifier, body?: BlockStatement): CatchClause; - export function conditionalExpression(test?: Expression, consequent?: Expression, alternate?: Expression): ConditionalExpression; - export function continueStatement(label?: Identifier): ContinueStatement; - export function debuggerStatement(): DebuggerStatement; - export function doWhileStatement(test?: Expression, body?: Statement): DoWhileStatement; - export function emptyStatement(): EmptyStatement; - export function expressionStatement(expression?: Expression): ExpressionStatement; - export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; - export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; - export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; - export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; - export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; - export function identifier(name?: string): Identifier; - export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; - export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; - export function stringLiteral(value?: string): StringLiteral; - export function numericLiteral(value?: number): NumericLiteral; - export function nullLiteral(): NullLiteral; - export function booleanLiteral(value?: boolean): BooleanLiteral; - export function regExpLiteral(pattern?: string, flags?: string): RegExpLiteral; - export function logicalExpression(operator?: "||" | "&&", left?: Expression, right?: Expression): LogicalExpression; - export function memberExpression(object?: Expression | Super, property?: Expression, computed?: boolean): MemberExpression; - export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; - export function program(body?: Array, directives?: Directive[]): Program; - export function objectExpression(properties?: Array): ObjectExpression; - export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod; - export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; - export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; - export function returnStatement(argument?: Expression): ReturnStatement; - export function sequenceExpression(expressions?: Expression[]): SequenceExpression; - export function switchCase(test?: Expression, consequent?: Statement[]): SwitchCase; - export function switchStatement(discriminant?: Expression, cases?: SwitchCase[]): SwitchStatement; - export function thisExpression(): ThisExpression; - export function throwStatement(argument?: Expression): ThrowStatement; - export function tryStatement(block?: BlockStatement, handler?: CatchClause, finalizer?: BlockStatement): TryStatement; - export function unaryExpression(operator?: "void" | "delete" | "!" | "+" | "-" | "++" | "--" | "~" | "typeof", argument?: Expression, prefix?: boolean): UnaryExpression; - export function updateExpression(operator?: "++" | "--", argument?: Expression, prefix?: boolean): UpdateExpression; - export function variableDeclaration(kind?: "var" | "let" | "const", declarations?: VariableDeclarator[]): VariableDeclaration; - export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclarator; - export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; - export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; - export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; - export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; - export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; - export function classBody(body?: Array): ClassBody; - export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; - export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; - export function exportAllDeclaration(source?: StringLiteral): ExportAllDeclaration; - export function exportDefaultDeclaration(declaration?: FunctionDeclaration | ClassDeclaration | Expression): ExportDefaultDeclaration; - export function exportNamedDeclaration(declaration?: Declaration, specifiers?: ExportSpecifier[], source?: StringLiteral): ExportNamedDeclaration; - export function exportSpecifier(local?: Identifier, exported?: Identifier): ExportSpecifier; - export function forOfStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForOfStatement; - export function importDeclaration(specifiers?: Array, source?: StringLiteral): ImportDeclaration; - export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifier; - export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; - export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; - export function metaProperty(meta?: string, property?: string): MetaProperty; - export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; - export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; - export function spreadElement(argument?: Expression): SpreadElement; - export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; - export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; - export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; - export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; - export function anyTypeAnnotation(): AnyTypeAnnotation; - export function arrayTypeAnnotation(elementType?: FlowTypeAnnotation): ArrayTypeAnnotation; - export function booleanTypeAnnotation(): BooleanTypeAnnotation; - export function booleanLiteralTypeAnnotation(): BooleanLiteralTypeAnnotation; - export function nullLiteralTypeAnnotation(): NullLiteralTypeAnnotation; - export function classImplements(id?: Identifier, typeParameters?: TypeParameterInstantiation): ClassImplements; - export function classProperty(key?: Identifier, value?: Expression, typeAnnotation?: TypeAnnotation, decorators?: Decorator[]): ClassProperty; - export function declareClass(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareClass; - export function declareFunction(id?: Identifier): DeclareFunction; - export function declareInterface(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareInterface; - export function declareModule(id?: StringLiteral | Identifier, body?: BlockStatement): DeclareModule; - export function declareTypeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): DeclareTypeAlias; - export function declareVariable(id?: Identifier): DeclareVariable; - export function existentialTypeParam(): ExistentialTypeParam; - export function functionTypeAnnotation(typeParameters?: TypeParameterDeclaration, params?: FunctionTypeParam[], rest?: FunctionTypeParam, returnType?: FlowTypeAnnotation): FunctionTypeAnnotation; - export function functionTypeParam(name?: Identifier, typeAnnotation?: FlowTypeAnnotation): FunctionTypeParam; - export function genericTypeAnnotation(id?: Identifier, typeParameters?: TypeParameterInstantiation): GenericTypeAnnotation; - export function interfaceExtends(id?: Identifier, typeParameters?: TypeParameterInstantiation): InterfaceExtends; - export function interfaceDeclaration(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): InterfaceDeclaration; - export function intersectionTypeAnnotation(types?: FlowTypeAnnotation[]): IntersectionTypeAnnotation; - export function mixedTypeAnnotation(): MixedTypeAnnotation; - export function nullableTypeAnnotation(typeAnnotation?: FlowTypeAnnotation): NullableTypeAnnotation; - export function numericLiteralTypeAnnotation(): NumericLiteralTypeAnnotation; - export function numberTypeAnnotation(): NumberTypeAnnotation; - export function stringLiteralTypeAnnotation(): StringLiteralTypeAnnotation; - export function stringTypeAnnotation(): StringTypeAnnotation; - export function thisTypeAnnotation(): ThisTypeAnnotation; - export function tupleTypeAnnotation(types?: FlowTypeAnnotation[]): TupleTypeAnnotation; - export function typeofTypeAnnotation(argument?: FlowTypeAnnotation): TypeofTypeAnnotation; - export function typeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): TypeAlias; - export function typeAnnotation(typeAnnotation?: FlowTypeAnnotation): TypeAnnotation; - export function typeCastExpression(expression?: Expression, typeAnnotation?: FlowTypeAnnotation): TypeCastExpression; - export function typeParameterDeclaration(params?: Identifier[]): TypeParameterDeclaration; - export function typeParameterInstantiation(params?: FlowTypeAnnotation[]): TypeParameterInstantiation; - export function objectTypeAnnotation(properties?: ObjectTypeProperty[], indexers?: ObjectTypeIndexer[], callProperties?: ObjectTypeCallProperty[]): ObjectTypeAnnotation; - export function objectTypeCallProperty(value?: FlowTypeAnnotation): ObjectTypeCallProperty; - export function objectTypeIndexer(id?: Expression, key?: FlowTypeAnnotation, value?: FlowTypeAnnotation): ObjectTypeIndexer; - export function objectTypeProperty(key?: Expression, value?: FlowTypeAnnotation): ObjectTypeProperty; - export function qualifiedTypeIdentifier(id?: Identifier, qualification?: Identifier | QualifiedTypeIdentifier): QualifiedTypeIdentifier; - export function unionTypeAnnotation(types?: FlowTypeAnnotation[]): UnionTypeAnnotation; - export function voidTypeAnnotation(): VoidTypeAnnotation; - export function jSXAttribute(name?: JSXIdentifier | JSXNamespacedName, value?: JSXElement | StringLiteral | JSXExpressionContainer): JSXAttribute; - export function jSXClosingElement(name?: JSXIdentifier | JSXMemberExpression): JSXClosingElement; - export function jSXElement(openingElement?: JSXOpeningElement, closingElement?: JSXClosingElement, children?: Array, selfClosing?: boolean): JSXElement; - export function jSXEmptyExpression(): JSXEmptyExpression; - export function jSXExpressionContainer(expression?: Expression): JSXExpressionContainer; - export function jSXIdentifier(name?: string): JSXIdentifier; - export function jSXMemberExpression(object?: JSXMemberExpression | JSXIdentifier, property?: JSXIdentifier): JSXMemberExpression; - export function jSXNamespacedName(namespace?: JSXIdentifier, name?: JSXIdentifier): JSXNamespacedName; - export function jSXOpeningElement(name?: JSXIdentifier | JSXMemberExpression, attributes?: JSXAttribute[], selfClosing?: boolean): JSXOpeningElement; - export function jSXSpreadAttribute(argument?: Expression): JSXSpreadAttribute; - export function jSXText(value?: string): JSXText; - export function noop(): Noop; - export function parenthesizedExpression(expression?: Expression): ParenthesizedExpression; - export function awaitExpression(argument?: Expression): AwaitExpression; - export function bindExpression(object?: Expression, callee?: Expression): BindExpression; - export function decorator(expression?: Expression): Decorator; - export function doExpression(body?: BlockStatement): DoExpression; - export function exportDefaultSpecifier(exported?: Identifier): ExportDefaultSpecifier; - export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespaceSpecifier; - export function restProperty(argument?: LVal): RestProperty; - export function spreadProperty(argument?: Expression): SpreadProperty; - - export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; - export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; - export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; - export function isDirective(node: Object, opts?: Object): node is Directive; - export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; - export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; - export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; - export function isCallExpression(node: Object, opts?: Object): node is CallExpression; - export function isCatchClause(node: Object, opts?: Object): node is CatchClause; - export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; - export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; - export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; - export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; - export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; - export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; - export function isFile(node: Object, opts?: Object): node is File; - export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; - export function isForStatement(node: Object, opts?: Object): node is ForStatement; - export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; - export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; - export function isIdentifier(node: Object, opts?: Object): node is Identifier; - export function isIfStatement(node: Object, opts?: Object): node is IfStatement; - export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; - export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; - export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; - export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; - export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; - export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; - export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; - export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; - export function isNewExpression(node: Object, opts?: Object): node is NewExpression; - export function isProgram(node: Object, opts?: Object): node is Program; - export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; - export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; - export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; - export function isRestElement(node: Object, opts?: Object): node is RestElement; - export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; - export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; - export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; - export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; - export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; - export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; - export function isTryStatement(node: Object, opts?: Object): node is TryStatement; - export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; - export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; - export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; - export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; - export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; - export function isWithStatement(node: Object, opts?: Object): node is WithStatement; - export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; - export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; - export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; - export function isClassBody(node: Object, opts?: Object): node is ClassBody; - export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; - export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; - export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; - export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; - export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; - export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; - export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; - export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; - export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; - export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; - export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; - export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; - export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; - export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; - export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; - export function isSuper(node: Object, opts?: Object): node is Super; - export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; - export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; - export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; - export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; - export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; - export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; - export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; - export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; - export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; - export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; - export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; - export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; - export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; - export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; - export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; - export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; - export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; - export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; - export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; - export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; - export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; - export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; - export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; - export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; - export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; - export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; - export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; - export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; - export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; - export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; - export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; - export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; - export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; - export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; - export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; - export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; - export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; - export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; - export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; - export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; - export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; - export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; - export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; - export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; - export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; - export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; - export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; - export function isJSXElement(node: Object, opts?: Object): node is JSXElement; - export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; - export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; - export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; - export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; - export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; - export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; - export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; - export function isJSXText(node: Object, opts?: Object): node is JSXText; - export function isNoop(node: Object, opts?: Object): node is Noop; - export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; - export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; - export function isBindExpression(node: Object, opts?: Object): node is BindExpression; - export function isDecorator(node: Object, opts?: Object): node is Decorator; - export function isDoExpression(node: Object, opts?: Object): node is DoExpression; - export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; - export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; - export function isRestProperty(node: Object, opts?: Object): node is RestProperty; - export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; - export function isExpression(node: Object, opts?: Object): node is Expression; - export function isBinary(node: Object, opts?: Object): node is Binary; - export function isScopable(node: Object, opts?: Object): node is Scopable; - export function isBlockParent(node: Object, opts?: Object): node is BlockParent; - export function isBlock(node: Object, opts?: Object): node is Block; - export function isStatement(node: Object, opts?: Object): node is Statement; - export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; - export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; - export function isConditional(node: Object, opts?: Object): node is Conditional; - export function isLoop(node: Object, opts?: Object): node is Loop; - export function isWhile(node: Object, opts?: Object): node is While; - export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; - export function isFor(node: Object, opts?: Object): node is For; - export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; - export function isFunction(node: Object, opts?: Object): node is Function; - export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; - export function isPureish(node: Object, opts?: Object): node is Pureish; - export function isDeclaration(node: Object, opts?: Object): node is Declaration; - export function isLVal(node: Object, opts?: Object): node is LVal; - export function isLiteral(node: Object, opts?: Object): node is Literal; - export function isImmutable(node: Object, opts?: Object): node is Immutable; - export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; - export function isMethod(node: Object, opts?: Object): node is Method; - export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; - export function isProperty(node: Object, opts?: Object): node is Property; - export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; - export function isPattern(node: Object, opts?: Object): node is Pattern; - export function isClass(node: Object, opts?: Object): node is Class; - export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; - export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; - export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; - export function isFlow(node: Object, opts?: Object): node is Flow; - export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; - export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; - export function isJSX(node: Object, opts?: Object): node is JSX; - export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; - export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; - - export function isReferencedIdentifier(node: Object, opts?: Object): boolean; - export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; - export function isBindingIdentifier(node: Object, opts?: Object): boolean; - export function isScope(node: Object, opts?: Object): boolean; - export function isReferenced(node: Object, opts?: Object): boolean; - export function isBlockScoped(node: Object, opts?: Object): boolean; - export function isVar(node: Object, opts?: Object): boolean; - export function isUser(node: Object, opts?: Object): boolean; - export function isGenerated(node: Object, opts?: Object): boolean; - export function isPure(node: Object, opts?: Object): boolean; - - export function assertArrayExpression(node: Object, opts?: Object): void; - export function assertAssignmentExpression(node: Object, opts?: Object): void; - export function assertBinaryExpression(node: Object, opts?: Object): void; - export function assertDirective(node: Object, opts?: Object): void; - export function assertDirectiveLiteral(node: Object, opts?: Object): void; - export function assertBlockStatement(node: Object, opts?: Object): void; - export function assertBreakStatement(node: Object, opts?: Object): void; - export function assertCallExpression(node: Object, opts?: Object): void; - export function assertCatchClause(node: Object, opts?: Object): void; - export function assertConditionalExpression(node: Object, opts?: Object): void; - export function assertContinueStatement(node: Object, opts?: Object): void; - export function assertDebuggerStatement(node: Object, opts?: Object): void; - export function assertDoWhileStatement(node: Object, opts?: Object): void; - export function assertEmptyStatement(node: Object, opts?: Object): void; - export function assertExpressionStatement(node: Object, opts?: Object): void; - export function assertFile(node: Object, opts?: Object): void; - export function assertForInStatement(node: Object, opts?: Object): void; - export function assertForStatement(node: Object, opts?: Object): void; - export function assertFunctionDeclaration(node: Object, opts?: Object): void; - export function assertFunctionExpression(node: Object, opts?: Object): void; - export function assertIdentifier(node: Object, opts?: Object): void; - export function assertIfStatement(node: Object, opts?: Object): void; - export function assertLabeledStatement(node: Object, opts?: Object): void; - export function assertStringLiteral(node: Object, opts?: Object): void; - export function assertNumericLiteral(node: Object, opts?: Object): void; - export function assertNullLiteral(node: Object, opts?: Object): void; - export function assertBooleanLiteral(node: Object, opts?: Object): void; - export function assertRegExpLiteral(node: Object, opts?: Object): void; - export function assertLogicalExpression(node: Object, opts?: Object): void; - export function assertMemberExpression(node: Object, opts?: Object): void; - export function assertNewExpression(node: Object, opts?: Object): void; - export function assertProgram(node: Object, opts?: Object): void; - export function assertObjectExpression(node: Object, opts?: Object): void; - export function assertObjectMethod(node: Object, opts?: Object): void; - export function assertObjectProperty(node: Object, opts?: Object): void; - export function assertRestElement(node: Object, opts?: Object): void; - export function assertReturnStatement(node: Object, opts?: Object): void; - export function assertSequenceExpression(node: Object, opts?: Object): void; - export function assertSwitchCase(node: Object, opts?: Object): void; - export function assertSwitchStatement(node: Object, opts?: Object): void; - export function assertThisExpression(node: Object, opts?: Object): void; - export function assertThrowStatement(node: Object, opts?: Object): void; - export function assertTryStatement(node: Object, opts?: Object): void; - export function assertUnaryExpression(node: Object, opts?: Object): void; - export function assertUpdateExpression(node: Object, opts?: Object): void; - export function assertVariableDeclaration(node: Object, opts?: Object): void; - export function assertVariableDeclarator(node: Object, opts?: Object): void; - export function assertWhileStatement(node: Object, opts?: Object): void; - export function assertWithStatement(node: Object, opts?: Object): void; - export function assertAssignmentPattern(node: Object, opts?: Object): void; - export function assertArrayPattern(node: Object, opts?: Object): void; - export function assertArrowFunctionExpression(node: Object, opts?: Object): void; - export function assertClassBody(node: Object, opts?: Object): void; - export function assertClassDeclaration(node: Object, opts?: Object): void; - export function assertClassExpression(node: Object, opts?: Object): void; - export function assertExportAllDeclaration(node: Object, opts?: Object): void; - export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; - export function assertExportNamedDeclaration(node: Object, opts?: Object): void; - export function assertExportSpecifier(node: Object, opts?: Object): void; - export function assertForOfStatement(node: Object, opts?: Object): void; - export function assertImportDeclaration(node: Object, opts?: Object): void; - export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; - export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; - export function assertImportSpecifier(node: Object, opts?: Object): void; - export function assertMetaProperty(node: Object, opts?: Object): void; - export function assertClassMethod(node: Object, opts?: Object): void; - export function assertObjectPattern(node: Object, opts?: Object): void; - export function assertSpreadElement(node: Object, opts?: Object): void; - export function assertSuper(node: Object, opts?: Object): void; - export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; - export function assertTemplateElement(node: Object, opts?: Object): void; - export function assertTemplateLiteral(node: Object, opts?: Object): void; - export function assertYieldExpression(node: Object, opts?: Object): void; - export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; - export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; - export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; - export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; - export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; - export function assertClassImplements(node: Object, opts?: Object): void; - export function assertClassProperty(node: Object, opts?: Object): void; - export function assertDeclareClass(node: Object, opts?: Object): void; - export function assertDeclareFunction(node: Object, opts?: Object): void; - export function assertDeclareInterface(node: Object, opts?: Object): void; - export function assertDeclareModule(node: Object, opts?: Object): void; - export function assertDeclareTypeAlias(node: Object, opts?: Object): void; - export function assertDeclareVariable(node: Object, opts?: Object): void; - export function assertExistentialTypeParam(node: Object, opts?: Object): void; - export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; - export function assertFunctionTypeParam(node: Object, opts?: Object): void; - export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; - export function assertInterfaceExtends(node: Object, opts?: Object): void; - export function assertInterfaceDeclaration(node: Object, opts?: Object): void; - export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; - export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; - export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; - export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; - export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; - export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; - export function assertStringTypeAnnotation(node: Object, opts?: Object): void; - export function assertThisTypeAnnotation(node: Object, opts?: Object): void; - export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; - export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; - export function assertTypeAlias(node: Object, opts?: Object): void; - export function assertTypeAnnotation(node: Object, opts?: Object): void; - export function assertTypeCastExpression(node: Object, opts?: Object): void; - export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; - export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; - export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; - export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; - export function assertObjectTypeIndexer(node: Object, opts?: Object): void; - export function assertObjectTypeProperty(node: Object, opts?: Object): void; - export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; - export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; - export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; - export function assertJSXAttribute(node: Object, opts?: Object): void; - export function assertJSXClosingElement(node: Object, opts?: Object): void; - export function assertJSXElement(node: Object, opts?: Object): void; - export function assertJSXEmptyExpression(node: Object, opts?: Object): void; - export function assertJSXExpressionContainer(node: Object, opts?: Object): void; - export function assertJSXIdentifier(node: Object, opts?: Object): void; - export function assertJSXMemberExpression(node: Object, opts?: Object): void; - export function assertJSXNamespacedName(node: Object, opts?: Object): void; - export function assertJSXOpeningElement(node: Object, opts?: Object): void; - export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; - export function assertJSXText(node: Object, opts?: Object): void; - export function assertNoop(node: Object, opts?: Object): void; - export function assertParenthesizedExpression(node: Object, opts?: Object): void; - export function assertAwaitExpression(node: Object, opts?: Object): void; - export function assertBindExpression(node: Object, opts?: Object): void; - export function assertDecorator(node: Object, opts?: Object): void; - export function assertDoExpression(node: Object, opts?: Object): void; - export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; - export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; - export function assertRestProperty(node: Object, opts?: Object): void; - export function assertSpreadProperty(node: Object, opts?: Object): void; - export function assertExpression(node: Object, opts?: Object): void; - export function assertBinary(node: Object, opts?: Object): void; - export function assertScopable(node: Object, opts?: Object): void; - export function assertBlockParent(node: Object, opts?: Object): void; - export function assertBlock(node: Object, opts?: Object): void; - export function assertStatement(node: Object, opts?: Object): void; - export function assertTerminatorless(node: Object, opts?: Object): void; - export function assertCompletionStatement(node: Object, opts?: Object): void; - export function assertConditional(node: Object, opts?: Object): void; - export function assertLoop(node: Object, opts?: Object): void; - export function assertWhile(node: Object, opts?: Object): void; - export function assertExpressionWrapper(node: Object, opts?: Object): void; - export function assertFor(node: Object, opts?: Object): void; - export function assertForXStatement(node: Object, opts?: Object): void; - export function assertFunction(node: Object, opts?: Object): void; - export function assertFunctionParent(node: Object, opts?: Object): void; - export function assertPureish(node: Object, opts?: Object): void; - export function assertDeclaration(node: Object, opts?: Object): void; - export function assertLVal(node: Object, opts?: Object): void; - export function assertLiteral(node: Object, opts?: Object): void; - export function assertImmutable(node: Object, opts?: Object): void; - export function assertUserWhitespacable(node: Object, opts?: Object): void; - export function assertMethod(node: Object, opts?: Object): void; - export function assertObjectMember(node: Object, opts?: Object): void; - export function assertProperty(node: Object, opts?: Object): void; - export function assertUnaryLike(node: Object, opts?: Object): void; - export function assertPattern(node: Object, opts?: Object): void; - export function assertClass(node: Object, opts?: Object): void; - export function assertModuleDeclaration(node: Object, opts?: Object): void; - export function assertExportDeclaration(node: Object, opts?: Object): void; - export function assertModuleSpecifier(node: Object, opts?: Object): void; - export function assertFlow(node: Object, opts?: Object): void; - export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; - export function assertFlowDeclaration(node: Object, opts?: Object): void; - export function assertJSX(node: Object, opts?: Object): void; - export function assertNumberLiteral(node: Object, opts?: Object): void; - export function assertRegexLiteral(node: Object, opts?: Object): void; +export interface Comment { + value: string; + start: number; + end: number; + loc: SourceLocation; } + +export interface CommentBlock extends Comment { + type: "CommentBlock"; +} + +export interface CommentLine extends Comment { + type: "CommentLine"; +} + +export interface SourceLocation { + start: { + line: number; + column: number; + }; + + end: { + line: number; + column: number; + }; +} + +export interface Node { + type: string; + leadingComments?: Array; + innerComments?: Array; + trailingComments?: Array; + start: number; + end: number; + loc: SourceLocation; +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression"; + elements: Array; +} + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression"; + operator: "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&="; + left: LVal; + right: Expression; +} + +export interface BinaryExpression extends Node { + type: "BinaryExpression"; + operator: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<="; + left: Expression; + right: Expression; +} + +export interface Directive extends Node { + type: "Directive"; + value: DirectiveLiteral; +} + +export interface DirectiveLiteral extends Node { + type: "DirectiveLiteral"; + value: string; +} + +export interface BlockStatement extends Node { + type: "BlockStatement"; + directives?: Directive[]; + body: Statement[]; +} + +export interface BreakStatement extends Node { + type: "BreakStatement"; + label: Identifier; +} + +export interface CallExpression extends Node { + type: "CallExpression"; + callee: Expression | Super; + arguments: Array; +} + +export interface CatchClause extends Node { + type: "CatchClause"; + param: Pattern; + body: BlockStatement; +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression"; + test: Expression; + consequent: Expression; + alternate: Expression; +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement"; + label: Identifier; +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement"; +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement"; + test: Expression; + body: Statement; +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement"; +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface File extends Node { + type: "File"; + program: Program; + comments: Comment[]; + tokens: any[]; +} + +export interface ForInStatement extends Node { + type: "ForInStatement"; + left: VariableDeclaration | LVal; + right: Expression; + body: Statement; +} + +export interface ForStatement extends Node { + type: "ForStatement"; + init: VariableDeclaration | Expression; + test: Expression; + update: Expression; + body: Statement; +} + +export interface FunctionDeclaration extends Node { + type: "FunctionDeclaration"; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface FunctionExpression extends Node { + type: "FunctionExpression"; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface Identifier extends Node { + type: "Identifier"; + name: string; + typeAnnotation?: TypeAnnotation; +} + +export interface IfStatement extends Node { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate: Statement; +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface StringLiteral extends Node { + type: "StringLiteral"; + value: string; +} + +export interface NumericLiteral extends Node { + type: "NumericLiteral"; + value: number; +} + +export interface NullLiteral extends Node { + type: "NullLiteral"; +} + +export interface BooleanLiteral extends Node { + type: "BooleanLiteral"; + value: boolean; +} + +export interface RegExpLiteral extends Node { + type: "RegExpLiteral"; + pattern: string; + flags?: string; +} + +export interface LogicalExpression extends Node { + type: "LogicalExpression"; + operator: "||" | "&&"; + left: Expression; + right: Expression; +} + +export interface MemberExpression extends Node { + type: "MemberExpression"; + object: Expression | Super; + property: Expression; + computed: boolean; +} + +export interface NewExpression extends Node { + type: "NewExpression"; + callee: Expression | Super; + arguments: Array; +} + +export interface Program extends Node { + type: "Program"; + sourceType: "script" | "module"; + directives?: Directive[]; + body: Array; +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression"; + properties: Array; +} + +export interface ObjectMethod extends Node { + type: "ObjectMethod"; + key: Expression; + kind: "get" | "set" | "method"; + shorthand: boolean; + computed: boolean; + value: Expression; + decorators?: Decorator[]; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface ObjectProperty extends Node { + type: "ObjectProperty"; + key: Expression; + computed: boolean; + value: Expression; + decorators?: Decorator[]; + shorthand: boolean; +} + +export interface RestElement extends Node { + type: "RestElement"; + argument: LVal; + typeAnnotation?: TypeAnnotation; +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement"; + argument: Expression; +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface SwitchCase extends Node { + type: "SwitchCase"; + test: Expression; + consequent: Statement[]; +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ThisExpression extends Node { + type: "ThisExpression"; +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends Node { + type: "TryStatement"; + block: BlockStatement; + handler: CatchClause; + finalizer: BlockStatement; +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression"; + operator: "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + prefix: boolean; + argument: Expression; +} + +export interface UpdateExpression extends Node { + type: "UpdateExpression"; + operator: "++" | "--"; + prefix: boolean; + argument: Expression; +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const"; +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator"; + id: LVal; + init: Expression; +} + +export interface WhileStatement extends Node { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface WithStatement extends Node { + type: "WithStatement"; + object: Expression; + body: BlockStatement | Statement; +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern"; + elements: Array; + typeAnnotation?: TypeAnnotation; +} + +export interface ArrowFunctionExpression extends Node { + type: "ArrowFunctionExpression"; + id: Identifier; + params: Pattern[]; + body: BlockStatement | Expression; + generator: boolean; + async: boolean; + expression: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface ClassBody extends Node { + type: "ClassBody"; + body: Array; +} + +export interface ClassDeclaration extends Node { + type: "ClassDeclaration"; + id: Identifier; + superClass: Expression; + body: ClassBody; + decorators?: Decorator[]; + implements?: ClassImplements[]; + mixins?: any[]; + typeParameters?: TypeParameterDeclaration; + superTypeParameters?: TypeParameterInstantiation; +} + +export interface ClassExpression extends Node { + type: "ClassExpression"; + id: Identifier; + superClass: Expression; + body: ClassBody; + decorators?: Decorator[]; + implements?: ClassImplements[]; + mixins?: any[]; + typeParameters?: TypeParameterDeclaration; + superTypeParameters?: TypeParameterInstantiation; +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration"; + source: StringLiteral; +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration"; + declaration: Declaration | Expression; +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration"; + declaration: Declaration; + specifiers: ExportSpecifier[]; + source: StringLiteral; +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier"; + local: Identifier; + imported: Identifier; + exported: Identifier; +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement"; + left: VariableDeclaration | LVal; + right: Expression; + body: Statement; +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration"; + specifiers: Array; + source: StringLiteral; +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier"; + local: Identifier; +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier"; + local: Identifier; +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier"; + local: Identifier; + imported: Identifier; +} + +export interface MetaProperty extends Node { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export interface ClassMethod extends Node { + type: "ClassMethod"; + key: Expression; + value?: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; + decorators?: Decorator[]; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + expression: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +// See: https://github.com/babel/babel/blob/master/doc/ast/spec.md#objectpattern +export interface AssignmentProperty extends Node { + type: "ObjectProperty"; + key: Expression; + computed: boolean; + value: Pattern; + decorators?: Decorator[]; + shorthand: boolean; +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern"; + properties: Array; + typeAnnotation?: TypeAnnotation; +} + +export interface SpreadElement extends Node { + type: "SpreadElement"; + argument: Expression; +} + +export interface Super extends Node { + type: "Super"; +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends Node { + type: "TemplateElement"; + tail: boolean; + value: { + cooked: string; + raw: string; + }; +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface YieldExpression extends Node { + type: "YieldExpression"; + argument: Expression; + delegate: boolean; +} + +export interface AnyTypeAnnotation extends Node { + type: "AnyTypeAnnotation"; +} + +export interface ArrayTypeAnnotation extends Node { + type: "ArrayTypeAnnotation"; + elementType: FlowTypeAnnotation; +} + +export interface BooleanTypeAnnotation extends Node { + type: "BooleanTypeAnnotation"; +} + +export interface BooleanLiteralTypeAnnotation extends Node { + type: "BooleanLiteralTypeAnnotation"; +} + +export interface NullLiteralTypeAnnotation extends Node { + type: "NullLiteralTypeAnnotation"; +} + +export interface ClassImplements extends Node { + type: "ClassImplements"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface ClassProperty extends Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + decorators?: Decorator[]; + typeAnnotation?: TypeAnnotation; +} + +export interface DeclareClass extends Node { + type: "DeclareClass"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; +} + +export interface DeclareFunction extends Node { + type: "DeclareFunction"; + id: Identifier; +} + +export interface DeclareInterface extends Node { + type: "DeclareInterface"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; +} + +export interface DeclareModule extends Node { + type: "DeclareModule"; + id: StringLiteral | Identifier; + body: BlockStatement; +} + +export interface DeclareTypeAlias extends Node { + type: "DeclareTypeAlias"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + right: FlowTypeAnnotation; +} + +export interface DeclareVariable extends Node { + type: "DeclareVariable"; + id: Identifier; +} + +export interface ExistentialTypeParam extends Node { + type: "ExistentialTypeParam"; +} + +export interface FunctionTypeAnnotation extends Node { + type: "FunctionTypeAnnotation"; + typeParameters: TypeParameterDeclaration; + params: FunctionTypeParam[]; + rest: FunctionTypeParam; + returnType: FlowTypeAnnotation; +} + +export interface FunctionTypeParam extends Node { + type: "FunctionTypeParam"; + name: Identifier; + typeAnnotation: FlowTypeAnnotation; +} + +export interface GenericTypeAnnotation extends Node { + type: "GenericTypeAnnotation"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface InterfaceExtends extends Node { + type: "InterfaceExtends"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface InterfaceDeclaration extends Node { + type: "InterfaceDeclaration"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + mixins?: any[]; + body: ObjectTypeAnnotation; +} + +export interface IntersectionTypeAnnotation extends Node { + type: "IntersectionTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface MixedTypeAnnotation extends Node { + type: "MixedTypeAnnotation"; +} + +export interface NullableTypeAnnotation extends Node { + type: "NullableTypeAnnotation"; + typeAnnotation: FlowTypeAnnotation; +} + +export interface NumericLiteralTypeAnnotation extends Node { + type: "NumericLiteralTypeAnnotation"; +} + +export interface NumberTypeAnnotation extends Node { + type: "NumberTypeAnnotation"; +} + +export interface StringLiteralTypeAnnotation extends Node { + type: "StringLiteralTypeAnnotation"; +} + +export interface StringTypeAnnotation extends Node { + type: "StringTypeAnnotation"; +} + +export interface ThisTypeAnnotation extends Node { + type: "ThisTypeAnnotation"; +} + +export interface TupleTypeAnnotation extends Node { + type: "TupleTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface TypeofTypeAnnotation extends Node { + type: "TypeofTypeAnnotation"; + argument: FlowTypeAnnotation; +} + +export interface TypeAlias extends Node { + type: "TypeAlias"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + right: FlowTypeAnnotation; +} + +export interface TypeAnnotation extends Node { + type: "TypeAnnotation"; + typeAnnotation: FlowTypeAnnotation; +} + +export interface TypeCastExpression extends Node { + type: "TypeCastExpression"; + expression: Expression; + typeAnnotation: FlowTypeAnnotation; +} + +export interface TypeParameterDeclaration extends Node { + type: "TypeParameterDeclaration"; + params: Identifier[]; +} + +export interface TypeParameterInstantiation extends Node { + type: "TypeParameterInstantiation"; + params: FlowTypeAnnotation[]; +} + +export interface ObjectTypeAnnotation extends Node { + type: "ObjectTypeAnnotation"; + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; +} + +export interface ObjectTypeCallProperty extends Node { + type: "ObjectTypeCallProperty"; + value: FlowTypeAnnotation; +} + +export interface ObjectTypeIndexer extends Node { + type: "ObjectTypeIndexer"; + id: Expression; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; +} + +export interface ObjectTypeProperty extends Node { + type: "ObjectTypeProperty"; + key: Expression; + value: FlowTypeAnnotation; +} + +export interface QualifiedTypeIdentifier extends Node { + type: "QualifiedTypeIdentifier"; + id: Identifier; + qualification: Identifier | QualifiedTypeIdentifier; +} + +export interface UnionTypeAnnotation extends Node { + type: "UnionTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface VoidTypeAnnotation extends Node { + type: "VoidTypeAnnotation"; +} + +export interface JSXAttribute extends Node { + type: "JSXAttribute"; + name: JSXIdentifier | JSXNamespacedName; + value: JSXElement | StringLiteral | JSXExpressionContainer; +} + +export interface JSXClosingElement extends Node { + type: "JSXClosingElement"; + name: JSXIdentifier | JSXMemberExpression; +} + +export interface JSXElement extends Node { + type: "JSXElement"; + openingElement: JSXOpeningElement; + closingElement: JSXClosingElement; + children: Array; + selfClosing?: boolean; +} + +export interface JSXEmptyExpression extends Node { + type: "JSXEmptyExpression"; +} + +export interface JSXExpressionContainer extends Node { + type: "JSXExpressionContainer"; + expression: Expression; +} + +export interface JSXIdentifier extends Node { + type: "JSXIdentifier"; + name: string; +} + +export interface JSXMemberExpression extends Node { + type: "JSXMemberExpression"; + object: JSXMemberExpression | JSXIdentifier; + property: JSXIdentifier; +} + +export interface JSXNamespacedName extends Node { + type: "JSXNamespacedName"; + namespace: JSXIdentifier; + name: JSXIdentifier; +} + +export interface JSXOpeningElement extends Node { + type: "JSXOpeningElement"; + name: JSXIdentifier | JSXMemberExpression; + selfClosing: boolean; + attributes: JSXAttribute[]; +} + +export interface JSXSpreadAttribute extends Node { + type: "JSXSpreadAttribute"; + argument: Expression; +} + +export interface JSXText extends Node { + type: "JSXText"; + value: string; +} + +export interface Noop extends Node { + type: "Noop"; +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression"; + expression: Expression; +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression"; + argument: Expression; +} + +export interface BindExpression extends Node { + type: "BindExpression"; + object: Expression; + callee: Expression; +} + +export interface Decorator extends Node { + type: "Decorator"; + expression: Expression; +} + +export interface DoExpression extends Node { + type: "DoExpression"; + body: BlockStatement; +} + +export interface ExportDefaultSpecifier extends Node { + type: "ExportDefaultSpecifier"; + exported: Identifier; +} + +export interface ExportNamespaceSpecifier extends Node { + type: "ExportNamespaceSpecifier"; + exported: Identifier; +} + +export interface RestProperty extends Node { + type: "RestProperty"; + argument: LVal; +} + +export interface SpreadProperty extends Node { + type: "SpreadProperty"; + argument: Expression; +} + +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Binary = BinaryExpression | LogicalExpression; +export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; +export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; +export type Block = BlockStatement | Program; +export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; +export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; +export type Conditional = ConditionalExpression | IfStatement; +export type Loop = DoWhileStatement | ForInStatement | ForStatement | WhileStatement | ForOfStatement; +export type While = DoWhileStatement | WhileStatement; +export type ExpressionWrapper = ExpressionStatement | TypeCastExpression | ParenthesizedExpression; +export type For = ForInStatement | ForStatement | ForOfStatement; +export type ForXStatement = ForInStatement | ForOfStatement; +export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; +export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; +export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; +export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral; +export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; +export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty; +export type Method = ObjectMethod | ClassMethod; +export type ObjectMember = ObjectMethod | ObjectProperty; +export type Property = ObjectProperty | ClassProperty; +export type UnaryLike = UnaryExpression | SpreadElement | RestProperty | SpreadProperty; +export type Pattern = AssignmentPattern | ArrayPattern | ObjectPattern; +export type Class = ClassDeclaration | ClassExpression; +export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; +export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; +export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; +export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; +export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; +export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; +export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; + +export function arrayExpression(elements?: Array): ArrayExpression; +export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; +export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; +export function directive(value?: DirectiveLiteral): Directive; +export function directiveLiteral(value?: string): DirectiveLiteral; +export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; +export function breakStatement(label?: Identifier): BreakStatement; +export function callExpression(callee?: Expression, _arguments?: Array): CallExpression; +export function catchClause(param?: Identifier, body?: BlockStatement): CatchClause; +export function conditionalExpression(test?: Expression, consequent?: Expression, alternate?: Expression): ConditionalExpression; +export function continueStatement(label?: Identifier): ContinueStatement; +export function debuggerStatement(): DebuggerStatement; +export function doWhileStatement(test?: Expression, body?: Statement): DoWhileStatement; +export function emptyStatement(): EmptyStatement; +export function expressionStatement(expression?: Expression): ExpressionStatement; +export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; +export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; +export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; +export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function identifier(name?: string): Identifier; +export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; +export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; +export function stringLiteral(value?: string): StringLiteral; +export function numericLiteral(value?: number): NumericLiteral; +export function nullLiteral(): NullLiteral; +export function booleanLiteral(value?: boolean): BooleanLiteral; +export function regExpLiteral(pattern?: string, flags?: string): RegExpLiteral; +export function logicalExpression(operator?: "||" | "&&", left?: Expression, right?: Expression): LogicalExpression; +export function memberExpression(object?: Expression | Super, property?: Expression, computed?: boolean): MemberExpression; +export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; +export function program(body?: Array, directives?: Directive[]): Program; +export function objectExpression(properties?: Array): ObjectExpression; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; +export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; +export function returnStatement(argument?: Expression): ReturnStatement; +export function sequenceExpression(expressions?: Expression[]): SequenceExpression; +export function switchCase(test?: Expression, consequent?: Statement[]): SwitchCase; +export function switchStatement(discriminant?: Expression, cases?: SwitchCase[]): SwitchStatement; +export function thisExpression(): ThisExpression; +export function throwStatement(argument?: Expression): ThrowStatement; +export function tryStatement(block?: BlockStatement, handler?: CatchClause, finalizer?: BlockStatement): TryStatement; +export function unaryExpression(operator?: "void" | "delete" | "!" | "+" | "-" | "++" | "--" | "~" | "typeof", argument?: Expression, prefix?: boolean): UnaryExpression; +export function updateExpression(operator?: "++" | "--", argument?: Expression, prefix?: boolean): UpdateExpression; +export function variableDeclaration(kind?: "var" | "let" | "const", declarations?: VariableDeclarator[]): VariableDeclaration; +export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclarator; +export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; +export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; +export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; +export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function classBody(body?: Array): ClassBody; +export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; +export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; +export function exportAllDeclaration(source?: StringLiteral): ExportAllDeclaration; +export function exportDefaultDeclaration(declaration?: FunctionDeclaration | ClassDeclaration | Expression): ExportDefaultDeclaration; +export function exportNamedDeclaration(declaration?: Declaration, specifiers?: ExportSpecifier[], source?: StringLiteral): ExportNamedDeclaration; +export function exportSpecifier(local?: Identifier, exported?: Identifier): ExportSpecifier; +export function forOfStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForOfStatement; +export function importDeclaration(specifiers?: Array, source?: StringLiteral): ImportDeclaration; +export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifier; +export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; +export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; +export function metaProperty(meta?: string, property?: string): MetaProperty; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; +export function spreadElement(argument?: Expression): SpreadElement; +export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; +export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; +export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; +export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; +export function anyTypeAnnotation(): AnyTypeAnnotation; +export function arrayTypeAnnotation(elementType?: FlowTypeAnnotation): ArrayTypeAnnotation; +export function booleanTypeAnnotation(): BooleanTypeAnnotation; +export function booleanLiteralTypeAnnotation(): BooleanLiteralTypeAnnotation; +export function nullLiteralTypeAnnotation(): NullLiteralTypeAnnotation; +export function classImplements(id?: Identifier, typeParameters?: TypeParameterInstantiation): ClassImplements; +export function classProperty(key?: Identifier, value?: Expression, typeAnnotation?: TypeAnnotation, decorators?: Decorator[]): ClassProperty; +export function declareClass(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareClass; +export function declareFunction(id?: Identifier): DeclareFunction; +export function declareInterface(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareInterface; +export function declareModule(id?: StringLiteral | Identifier, body?: BlockStatement): DeclareModule; +export function declareTypeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): DeclareTypeAlias; +export function declareVariable(id?: Identifier): DeclareVariable; +export function existentialTypeParam(): ExistentialTypeParam; +export function functionTypeAnnotation(typeParameters?: TypeParameterDeclaration, params?: FunctionTypeParam[], rest?: FunctionTypeParam, returnType?: FlowTypeAnnotation): FunctionTypeAnnotation; +export function functionTypeParam(name?: Identifier, typeAnnotation?: FlowTypeAnnotation): FunctionTypeParam; +export function genericTypeAnnotation(id?: Identifier, typeParameters?: TypeParameterInstantiation): GenericTypeAnnotation; +export function interfaceExtends(id?: Identifier, typeParameters?: TypeParameterInstantiation): InterfaceExtends; +export function interfaceDeclaration(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): InterfaceDeclaration; +export function intersectionTypeAnnotation(types?: FlowTypeAnnotation[]): IntersectionTypeAnnotation; +export function mixedTypeAnnotation(): MixedTypeAnnotation; +export function nullableTypeAnnotation(typeAnnotation?: FlowTypeAnnotation): NullableTypeAnnotation; +export function numericLiteralTypeAnnotation(): NumericLiteralTypeAnnotation; +export function numberTypeAnnotation(): NumberTypeAnnotation; +export function stringLiteralTypeAnnotation(): StringLiteralTypeAnnotation; +export function stringTypeAnnotation(): StringTypeAnnotation; +export function thisTypeAnnotation(): ThisTypeAnnotation; +export function tupleTypeAnnotation(types?: FlowTypeAnnotation[]): TupleTypeAnnotation; +export function typeofTypeAnnotation(argument?: FlowTypeAnnotation): TypeofTypeAnnotation; +export function typeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): TypeAlias; +export function typeAnnotation(typeAnnotation?: FlowTypeAnnotation): TypeAnnotation; +export function typeCastExpression(expression?: Expression, typeAnnotation?: FlowTypeAnnotation): TypeCastExpression; +export function typeParameterDeclaration(params?: Identifier[]): TypeParameterDeclaration; +export function typeParameterInstantiation(params?: FlowTypeAnnotation[]): TypeParameterInstantiation; +export function objectTypeAnnotation(properties?: ObjectTypeProperty[], indexers?: ObjectTypeIndexer[], callProperties?: ObjectTypeCallProperty[]): ObjectTypeAnnotation; +export function objectTypeCallProperty(value?: FlowTypeAnnotation): ObjectTypeCallProperty; +export function objectTypeIndexer(id?: Expression, key?: FlowTypeAnnotation, value?: FlowTypeAnnotation): ObjectTypeIndexer; +export function objectTypeProperty(key?: Expression, value?: FlowTypeAnnotation): ObjectTypeProperty; +export function qualifiedTypeIdentifier(id?: Identifier, qualification?: Identifier | QualifiedTypeIdentifier): QualifiedTypeIdentifier; +export function unionTypeAnnotation(types?: FlowTypeAnnotation[]): UnionTypeAnnotation; +export function voidTypeAnnotation(): VoidTypeAnnotation; +export function jSXAttribute(name?: JSXIdentifier | JSXNamespacedName, value?: JSXElement | StringLiteral | JSXExpressionContainer): JSXAttribute; +export function jSXClosingElement(name?: JSXIdentifier | JSXMemberExpression): JSXClosingElement; +export function jSXElement(openingElement?: JSXOpeningElement, closingElement?: JSXClosingElement, children?: Array, selfClosing?: boolean): JSXElement; +export function jSXEmptyExpression(): JSXEmptyExpression; +export function jSXExpressionContainer(expression?: Expression): JSXExpressionContainer; +export function jSXIdentifier(name?: string): JSXIdentifier; +export function jSXMemberExpression(object?: JSXMemberExpression | JSXIdentifier, property?: JSXIdentifier): JSXMemberExpression; +export function jSXNamespacedName(namespace?: JSXIdentifier, name?: JSXIdentifier): JSXNamespacedName; +export function jSXOpeningElement(name?: JSXIdentifier | JSXMemberExpression, attributes?: JSXAttribute[], selfClosing?: boolean): JSXOpeningElement; +export function jSXSpreadAttribute(argument?: Expression): JSXSpreadAttribute; +export function jSXText(value?: string): JSXText; +export function noop(): Noop; +export function parenthesizedExpression(expression?: Expression): ParenthesizedExpression; +export function awaitExpression(argument?: Expression): AwaitExpression; +export function bindExpression(object?: Expression, callee?: Expression): BindExpression; +export function decorator(expression?: Expression): Decorator; +export function doExpression(body?: BlockStatement): DoExpression; +export function exportDefaultSpecifier(exported?: Identifier): ExportDefaultSpecifier; +export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespaceSpecifier; +export function restProperty(argument?: LVal): RestProperty; +export function spreadProperty(argument?: Expression): SpreadProperty; + +export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; +export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; +export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; +export function isDirective(node: Object, opts?: Object): node is Directive; +export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; +export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; +export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; +export function isCallExpression(node: Object, opts?: Object): node is CallExpression; +export function isCatchClause(node: Object, opts?: Object): node is CatchClause; +export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; +export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; +export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; +export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; +export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; +export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; +export function isFile(node: Object, opts?: Object): node is File; +export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; +export function isForStatement(node: Object, opts?: Object): node is ForStatement; +export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; +export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; +export function isIdentifier(node: Object, opts?: Object): node is Identifier; +export function isIfStatement(node: Object, opts?: Object): node is IfStatement; +export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; +export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; +export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; +export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; +export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; +export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; +export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; +export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; +export function isNewExpression(node: Object, opts?: Object): node is NewExpression; +export function isProgram(node: Object, opts?: Object): node is Program; +export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; +export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; +export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; +export function isRestElement(node: Object, opts?: Object): node is RestElement; +export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; +export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; +export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; +export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; +export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; +export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; +export function isTryStatement(node: Object, opts?: Object): node is TryStatement; +export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; +export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; +export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; +export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; +export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; +export function isWithStatement(node: Object, opts?: Object): node is WithStatement; +export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; +export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; +export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; +export function isClassBody(node: Object, opts?: Object): node is ClassBody; +export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; +export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; +export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; +export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; +export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; +export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; +export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; +export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; +export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; +export function isSuper(node: Object, opts?: Object): node is Super; +export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; +export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; +export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; +export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; +export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; +export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; +export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; +export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; +export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; +export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; +export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; +export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; +export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; +export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; +export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; +export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; +export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; +export function isJSXElement(node: Object, opts?: Object): node is JSXElement; +export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; +export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; +export function isJSXText(node: Object, opts?: Object): node is JSXText; +export function isNoop(node: Object, opts?: Object): node is Noop; +export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; +export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; +export function isBindExpression(node: Object, opts?: Object): node is BindExpression; +export function isDecorator(node: Object, opts?: Object): node is Decorator; +export function isDoExpression(node: Object, opts?: Object): node is DoExpression; +export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: Object, opts?: Object): node is RestProperty; +export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; +export function isExpression(node: Object, opts?: Object): node is Expression; +export function isBinary(node: Object, opts?: Object): node is Binary; +export function isScopable(node: Object, opts?: Object): node is Scopable; +export function isBlockParent(node: Object, opts?: Object): node is BlockParent; +export function isBlock(node: Object, opts?: Object): node is Block; +export function isStatement(node: Object, opts?: Object): node is Statement; +export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; +export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; +export function isConditional(node: Object, opts?: Object): node is Conditional; +export function isLoop(node: Object, opts?: Object): node is Loop; +export function isWhile(node: Object, opts?: Object): node is While; +export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; +export function isFor(node: Object, opts?: Object): node is For; +export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; +export function isFunction(node: Object, opts?: Object): node is Function; +export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; +export function isPureish(node: Object, opts?: Object): node is Pureish; +export function isDeclaration(node: Object, opts?: Object): node is Declaration; +export function isLVal(node: Object, opts?: Object): node is LVal; +export function isLiteral(node: Object, opts?: Object): node is Literal; +export function isImmutable(node: Object, opts?: Object): node is Immutable; +export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; +export function isMethod(node: Object, opts?: Object): node is Method; +export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; +export function isProperty(node: Object, opts?: Object): node is Property; +export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; +export function isPattern(node: Object, opts?: Object): node is Pattern; +export function isClass(node: Object, opts?: Object): node is Class; +export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; +export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; +export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; +export function isFlow(node: Object, opts?: Object): node is Flow; +export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; +export function isJSX(node: Object, opts?: Object): node is JSX; +export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; +export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; + +export function isReferencedIdentifier(node: Object, opts?: Object): boolean; +export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; +export function isBindingIdentifier(node: Object, opts?: Object): boolean; +export function isScope(node: Object, opts?: Object): boolean; +export function isReferenced(node: Object, opts?: Object): boolean; +export function isBlockScoped(node: Object, opts?: Object): boolean; +export function isVar(node: Object, opts?: Object): boolean; +export function isUser(node: Object, opts?: Object): boolean; +export function isGenerated(node: Object, opts?: Object): boolean; +export function isPure(node: Object, opts?: Object): boolean; + +export function assertArrayExpression(node: Object, opts?: Object): void; +export function assertAssignmentExpression(node: Object, opts?: Object): void; +export function assertBinaryExpression(node: Object, opts?: Object): void; +export function assertDirective(node: Object, opts?: Object): void; +export function assertDirectiveLiteral(node: Object, opts?: Object): void; +export function assertBlockStatement(node: Object, opts?: Object): void; +export function assertBreakStatement(node: Object, opts?: Object): void; +export function assertCallExpression(node: Object, opts?: Object): void; +export function assertCatchClause(node: Object, opts?: Object): void; +export function assertConditionalExpression(node: Object, opts?: Object): void; +export function assertContinueStatement(node: Object, opts?: Object): void; +export function assertDebuggerStatement(node: Object, opts?: Object): void; +export function assertDoWhileStatement(node: Object, opts?: Object): void; +export function assertEmptyStatement(node: Object, opts?: Object): void; +export function assertExpressionStatement(node: Object, opts?: Object): void; +export function assertFile(node: Object, opts?: Object): void; +export function assertForInStatement(node: Object, opts?: Object): void; +export function assertForStatement(node: Object, opts?: Object): void; +export function assertFunctionDeclaration(node: Object, opts?: Object): void; +export function assertFunctionExpression(node: Object, opts?: Object): void; +export function assertIdentifier(node: Object, opts?: Object): void; +export function assertIfStatement(node: Object, opts?: Object): void; +export function assertLabeledStatement(node: Object, opts?: Object): void; +export function assertStringLiteral(node: Object, opts?: Object): void; +export function assertNumericLiteral(node: Object, opts?: Object): void; +export function assertNullLiteral(node: Object, opts?: Object): void; +export function assertBooleanLiteral(node: Object, opts?: Object): void; +export function assertRegExpLiteral(node: Object, opts?: Object): void; +export function assertLogicalExpression(node: Object, opts?: Object): void; +export function assertMemberExpression(node: Object, opts?: Object): void; +export function assertNewExpression(node: Object, opts?: Object): void; +export function assertProgram(node: Object, opts?: Object): void; +export function assertObjectExpression(node: Object, opts?: Object): void; +export function assertObjectMethod(node: Object, opts?: Object): void; +export function assertObjectProperty(node: Object, opts?: Object): void; +export function assertRestElement(node: Object, opts?: Object): void; +export function assertReturnStatement(node: Object, opts?: Object): void; +export function assertSequenceExpression(node: Object, opts?: Object): void; +export function assertSwitchCase(node: Object, opts?: Object): void; +export function assertSwitchStatement(node: Object, opts?: Object): void; +export function assertThisExpression(node: Object, opts?: Object): void; +export function assertThrowStatement(node: Object, opts?: Object): void; +export function assertTryStatement(node: Object, opts?: Object): void; +export function assertUnaryExpression(node: Object, opts?: Object): void; +export function assertUpdateExpression(node: Object, opts?: Object): void; +export function assertVariableDeclaration(node: Object, opts?: Object): void; +export function assertVariableDeclarator(node: Object, opts?: Object): void; +export function assertWhileStatement(node: Object, opts?: Object): void; +export function assertWithStatement(node: Object, opts?: Object): void; +export function assertAssignmentPattern(node: Object, opts?: Object): void; +export function assertArrayPattern(node: Object, opts?: Object): void; +export function assertArrowFunctionExpression(node: Object, opts?: Object): void; +export function assertClassBody(node: Object, opts?: Object): void; +export function assertClassDeclaration(node: Object, opts?: Object): void; +export function assertClassExpression(node: Object, opts?: Object): void; +export function assertExportAllDeclaration(node: Object, opts?: Object): void; +export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; +export function assertExportNamedDeclaration(node: Object, opts?: Object): void; +export function assertExportSpecifier(node: Object, opts?: Object): void; +export function assertForOfStatement(node: Object, opts?: Object): void; +export function assertImportDeclaration(node: Object, opts?: Object): void; +export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; +export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; +export function assertImportSpecifier(node: Object, opts?: Object): void; +export function assertMetaProperty(node: Object, opts?: Object): void; +export function assertClassMethod(node: Object, opts?: Object): void; +export function assertObjectPattern(node: Object, opts?: Object): void; +export function assertSpreadElement(node: Object, opts?: Object): void; +export function assertSuper(node: Object, opts?: Object): void; +export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; +export function assertTemplateElement(node: Object, opts?: Object): void; +export function assertTemplateLiteral(node: Object, opts?: Object): void; +export function assertYieldExpression(node: Object, opts?: Object): void; +export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; +export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; +export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; +export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertClassImplements(node: Object, opts?: Object): void; +export function assertClassProperty(node: Object, opts?: Object): void; +export function assertDeclareClass(node: Object, opts?: Object): void; +export function assertDeclareFunction(node: Object, opts?: Object): void; +export function assertDeclareInterface(node: Object, opts?: Object): void; +export function assertDeclareModule(node: Object, opts?: Object): void; +export function assertDeclareTypeAlias(node: Object, opts?: Object): void; +export function assertDeclareVariable(node: Object, opts?: Object): void; +export function assertExistentialTypeParam(node: Object, opts?: Object): void; +export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; +export function assertFunctionTypeParam(node: Object, opts?: Object): void; +export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; +export function assertInterfaceExtends(node: Object, opts?: Object): void; +export function assertInterfaceDeclaration(node: Object, opts?: Object): void; +export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; +export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; +export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; +export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; +export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertStringTypeAnnotation(node: Object, opts?: Object): void; +export function assertThisTypeAnnotation(node: Object, opts?: Object): void; +export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeAlias(node: Object, opts?: Object): void; +export function assertTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeCastExpression(node: Object, opts?: Object): void; +export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; +export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; +export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; +export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; +export function assertObjectTypeIndexer(node: Object, opts?: Object): void; +export function assertObjectTypeProperty(node: Object, opts?: Object): void; +export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; +export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; +export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; +export function assertJSXAttribute(node: Object, opts?: Object): void; +export function assertJSXClosingElement(node: Object, opts?: Object): void; +export function assertJSXElement(node: Object, opts?: Object): void; +export function assertJSXEmptyExpression(node: Object, opts?: Object): void; +export function assertJSXExpressionContainer(node: Object, opts?: Object): void; +export function assertJSXIdentifier(node: Object, opts?: Object): void; +export function assertJSXMemberExpression(node: Object, opts?: Object): void; +export function assertJSXNamespacedName(node: Object, opts?: Object): void; +export function assertJSXOpeningElement(node: Object, opts?: Object): void; +export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; +export function assertJSXText(node: Object, opts?: Object): void; +export function assertNoop(node: Object, opts?: Object): void; +export function assertParenthesizedExpression(node: Object, opts?: Object): void; +export function assertAwaitExpression(node: Object, opts?: Object): void; +export function assertBindExpression(node: Object, opts?: Object): void; +export function assertDecorator(node: Object, opts?: Object): void; +export function assertDoExpression(node: Object, opts?: Object): void; +export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; +export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; +export function assertRestProperty(node: Object, opts?: Object): void; +export function assertSpreadProperty(node: Object, opts?: Object): void; +export function assertExpression(node: Object, opts?: Object): void; +export function assertBinary(node: Object, opts?: Object): void; +export function assertScopable(node: Object, opts?: Object): void; +export function assertBlockParent(node: Object, opts?: Object): void; +export function assertBlock(node: Object, opts?: Object): void; +export function assertStatement(node: Object, opts?: Object): void; +export function assertTerminatorless(node: Object, opts?: Object): void; +export function assertCompletionStatement(node: Object, opts?: Object): void; +export function assertConditional(node: Object, opts?: Object): void; +export function assertLoop(node: Object, opts?: Object): void; +export function assertWhile(node: Object, opts?: Object): void; +export function assertExpressionWrapper(node: Object, opts?: Object): void; +export function assertFor(node: Object, opts?: Object): void; +export function assertForXStatement(node: Object, opts?: Object): void; +export function assertFunction(node: Object, opts?: Object): void; +export function assertFunctionParent(node: Object, opts?: Object): void; +export function assertPureish(node: Object, opts?: Object): void; +export function assertDeclaration(node: Object, opts?: Object): void; +export function assertLVal(node: Object, opts?: Object): void; +export function assertLiteral(node: Object, opts?: Object): void; +export function assertImmutable(node: Object, opts?: Object): void; +export function assertUserWhitespacable(node: Object, opts?: Object): void; +export function assertMethod(node: Object, opts?: Object): void; +export function assertObjectMember(node: Object, opts?: Object): void; +export function assertProperty(node: Object, opts?: Object): void; +export function assertUnaryLike(node: Object, opts?: Object): void; +export function assertPattern(node: Object, opts?: Object): void; +export function assertClass(node: Object, opts?: Object): void; +export function assertModuleDeclaration(node: Object, opts?: Object): void; +export function assertExportDeclaration(node: Object, opts?: Object): void; +export function assertModuleSpecifier(node: Object, opts?: Object): void; +export function assertFlow(node: Object, opts?: Object): void; +export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; +export function assertFlowDeclaration(node: Object, opts?: Object): void; +export function assertJSX(node: Object, opts?: Object): void; +export function assertNumberLiteral(node: Object, opts?: Object): void; +export function assertRegexLiteral(node: Object, opts?: Object): void; + diff --git a/babylon/index.d.ts b/babylon/index.d.ts index 8469ad28c1..112e6be7be 100644 --- a/babylon/index.d.ts +++ b/babylon/index.d.ts @@ -5,44 +5,43 @@ /// -declare module "babylon" { - import * as t from 'babel-types'; - type Node = t.Node; +import * as t from 'babel-types'; +type Node = t.Node; - export function parse(code: string, opts?: BabylonOptions): Node; +export function parse(code: string, opts?: BabylonOptions): Node; - export interface BabylonOptions { - /** - * By default, import and export declarations can only appear at a program's top level. - * Setting this option to true allows them anywhere where a statement is allowed. - */ - allowImportExportEverywhere?: boolean; +export interface BabylonOptions { + /** + * By default, import and export declarations can only appear at a program's top level. + * Setting this option to true allows them anywhere where a statement is allowed. + */ + allowImportExportEverywhere?: boolean; - /** - * By default, a return statement at the top level raises an error. Set this to true to accept such code. - */ - allowReturnOutsideFunction?: boolean; + /** + * By default, a return statement at the top level raises an error. Set this to true to accept such code. + */ + allowReturnOutsideFunction?: boolean; - allowSuperOutsideMethod?: boolean; + allowSuperOutsideMethod?: boolean; - /** - * Indicate the mode the code should be parsed in. Can be either "script" or "module". - */ - sourceType?: 'script' | 'module'; + /** + * Indicate the mode the code should be parsed in. Can be either "script" or "module". + */ + sourceType?: 'script' | 'module'; - /** - * Correlate output AST nodes with their source filename. Useful when - * generating code and source maps from the ASTs of multiple input files. - */ - sourceFilename?: string; + /** + * Correlate output AST nodes with their source filename. Useful when + * generating code and source maps from the ASTs of multiple input files. + */ + sourceFilename?: string; - /** - * Array containing the plugins that you want to enable. - */ - plugins?: PluginName[]; - } - - export type PluginName = 'jsx' | 'flow' | 'asyncFunctions' | 'classConstructorCall' | 'doExpressions' - | 'trailingFunctionCommas' | 'objectRestSpread' | 'decorators' | 'classProperties' | 'exportExtensions' - | 'exponentiationOperator' | 'asyncGenerators' | 'functionBind' | 'functionSent'; + /** + * Array containing the plugins that you want to enable. + */ + plugins?: PluginName[]; } + +export type PluginName = 'jsx' | 'flow' | 'asyncFunctions' | 'classConstructorCall' | 'doExpressions' + | 'trailingFunctionCommas' | 'objectRestSpread' | 'decorators' | 'classProperties' | 'exportExtensions' + | 'exponentiationOperator' | 'asyncGenerators' | 'functionBind' | 'functionSent'; + diff --git a/base-x/base-x-tests.ts b/base-x/base-x-tests.ts index 29676ae791..44e302d2d5 100644 --- a/base-x/base-x-tests.ts +++ b/base-x/base-x-tests.ts @@ -1,8 +1,7 @@ - import * as basex from 'base-x'; -let bs16: BaseX.BaseConverter = basex('0123456789ABCDEF'); +let bs16 = basex('0123456789ABCDEF'); { let encoded: string; diff --git a/base-x/index.d.ts b/base-x/index.d.ts index b6b764befe..19af3aa993 100644 --- a/base-x/index.d.ts +++ b/base-x/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Ilya Mochalov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var base: BaseX.Base; +export = base; + declare namespace BaseX { interface EncodeBuffer { [index: number]: number; @@ -18,11 +21,3 @@ declare namespace BaseX { (ALPHABET: string): BaseX.BaseConverter } } - -declare module "base-x" { - namespace base {} - - let base: BaseX.Base; - - export = base; -} diff --git a/bignum/index.d.ts b/bignum/index.d.ts index 4899cc3b71..ae556d00fe 100644 --- a/bignum/index.d.ts +++ b/bignum/index.d.ts @@ -5,6 +5,8 @@ /// +export = BigNum; + declare class BigNum { /** Create a new BigNum from n. */ constructor(n: number|BigNum); @@ -263,7 +265,3 @@ declare namespace BigNum { /** Return the number of bits used to represent the current BigNum. */ export function bitLength(n: BigNumCompatible): number; } - -declare module "bignum" { - export = BigNum; -} diff --git a/bip21/bip21-tests.ts b/bip21/bip21-tests.ts index ac8ad44b67..ef200719a8 100644 --- a/bip21/bip21-tests.ts +++ b/bip21/bip21-tests.ts @@ -1,3 +1,4 @@ +import bip21 = require('bip21'); let decoded:any = bip21.decode('bitcoin:1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH?amount=20.3&label=Foobar'); let encoded:string = bip21.encode('1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH', { diff --git a/bip21/index.d.ts b/bip21/index.d.ts index 7dc6223164..06e61a6944 100644 --- a/bip21/index.d.ts +++ b/bip21/index.d.ts @@ -8,6 +8,4 @@ declare namespace bip21 { export function encode(address:string,options?:any) : string; } -declare module "bip21" { - export = bip21; -} +export = bip21; diff --git a/blob-stream/index.d.ts b/blob-stream/index.d.ts index e087375c45..c7452a3242 100644 --- a/blob-stream/index.d.ts +++ b/blob-stream/index.d.ts @@ -15,6 +15,4 @@ declare namespace BlobStream { } } -declare module "blob-stream" { - export = BlobStream; -} +export = BlobStream; \ No newline at end of file diff --git a/bookshelf/index.d.ts b/bookshelf/index.d.ts index 2f1629c082..34a94dd3e8 100644 --- a/bookshelf/index.d.ts +++ b/bookshelf/index.d.ts @@ -6,308 +6,307 @@ /// /// -declare module 'bookshelf' { - import knex = require('knex'); - import Promise = require('bluebird'); - import Lodash = require('lodash'); +import knex = require('knex'); +import Promise = require('bluebird'); +import Lodash = require('lodash'); - interface Bookshelf extends Bookshelf.Events { - VERSION : string; - knex : knex; - Model : typeof Bookshelf.Model; - Collection : typeof Bookshelf.Collection; +interface Bookshelf extends Bookshelf.Events { + VERSION : string; + knex : knex; + Model : typeof Bookshelf.Model; + Collection : typeof Bookshelf.Collection; - plugin(name: string | string[] | Function, options?: any) : Bookshelf; - transaction(callback : (transaction : knex.Transaction) => T) : Promise; - } - - function Bookshelf(knex : knex) : Bookshelf; - - namespace Bookshelf { - abstract class Events { - on(event? : string, callback? : EventFunction, context? : any) : void; - off(event? : string) : void; - trigger(event? : string, ...args : any[]) : void; - triggerThen(name : string, ...args : any[]) : Promise; - once(event : string, callback : EventFunction, context? : any) : void; - } - - interface IModelBase { - /** Should be declared as a getter instead of a plain property. */ - hasTimestamps? : boolean|string[]; - /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ - tableName? : string; - } - - abstract class ModelBase> extends Events> implements IModelBase { - /** If overriding, must use a getter instead of a plain property. */ - idAttribute : string; - - constructor(attributes? : any, options? : ModelOptions); - - clear() : T; - clone() : T; - escape(attribute : string) : string; - format(attributes : any) : any; - get(attribute : string) : any; - has(attribute : string) : boolean; - hasChanged(attribute? : string) : boolean; - isNew() : boolean; - parse(response : any) : any; - previousAttributes() : any; - previous(attribute : string) : any; - related>(relation : string) : R | Collection; - serialize(options? : SerializeOptions) : any; - set(attribute?: {[key : string] : any}, options? : SetOptions) : T; - set(attribute : string, value? : any, options? : SetOptions) : T; - timestamp(options? : TimestampOptions) : any; - toJSON(options? : SerializeOptions) : any; - unset(attribute : string) : T; - - // lodash methods - invert() : R; - keys() : string[]; - omit(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - omit(...attributes : string[]) : R; - pairs() : any[][]; - pick(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - pick(...attributes : string[]) : R; - values() : any[]; - } - - class Model> extends ModelBase { - static collection>(models? : T[], options? : CollectionOptions) : Collection; - static count(column? : string, options? : SyncOptions) : Promise; - /** @deprecated use Typescript classes */ - static extend>(prototypeProperties? : any, classProperties? : any) : Function; // should return a type - static fetchAll>() : Promise>; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; - count(column? : string, options? : SyncOptions) : Promise; - destroy(options? : SyncOptions) : Promise; - fetch(options? : FetchOptions) : Promise; - fetchAll(options? : FetchAllOptions) : Promise>; - hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; - hasOne>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - load(relations : string|string[], options? : LoadOptions) : Promise; - morphMany>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : Collection; - morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; - morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; - morphTo(name : string, ...target : typeof Model[]) : T; - query(...query : string[]) : T; - query(query : {[key : string] : any}) : T; - query(callback : (qb : knex.QueryBuilder) => void) : T; - query() : knex.QueryBuilder; - refresh(options? : FetchOptions) : Promise; - resetQuery() : T; - save(key? : string, val? : string, options? : SaveOptions) : Promise; - save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - where(properties : {[key : string] : any}) : T; - where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; - } - - abstract class CollectionBase> extends Events { - add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; - at(index : number) : T; - clone() : Collection; - fetch(options? : CollectionFetchOptions) : Promise>; - findWhere(match : {[key : string] : any}) : T; - get(id : any) : T; - invokeThen(name : string, ...args : any[]) : Promise; - parse(response : any) : any; - pluck(attribute : string) : any[]; - pop() : void; - push(model : any) : Collection; - reduceThen(iterator : (prev : R, cur : T, idx : number, array : T[]) => R, initialValue : R, context : any) : Promise; - remove(model : T, options? : EventOptions) : T; - remove(model : T[], options? : EventOptions) : T[]; - reset(model : any[], options? : CollectionAddOptions) : T[]; - serialize(options? : SerializeOptions) : any; - set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; - shift(options? : EventOptions) : void; - slice(begin? : number, end? : number) : void; - toJSON(options? : SerializeOptions) : any; - unshift(model : any, options? : CollectionAddOptions) : void; - where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; - - // lodash methods - all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - all(predicate? : R) : boolean; - any(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - any(predicate? : R) : boolean; - chain() : Lodash.LoDashExplicitObjectWrapper; - collect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - collect(predicate? : R) : T[]; - contains(value : any, fromIndex? : number) : boolean; - countBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - countBy(predicate? : R) : Lodash.Dictionary; - detect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - detect(predicate? : R) : T; - difference(...values : T[]) : T[]; - drop(n? : number) : T[]; - each(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - each(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - each(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - every(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - every(predicate? : R) : boolean; - filter(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - filter(predicate? : R) : T[]; - find(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - find(predicate? : R) : T; - first() : T; - foldl(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - foldr(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - forEach(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - forEach(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - forEach(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - groupBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - groupBy(predicate? : R) : Lodash.Dictionary; - head() : T; - include(value : any, fromIndex? : number) : boolean; - indexOf(value : any, fromIndex? : number) : number; - initial() : T[]; - inject(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - invoke(methodName : string|Function, ...args : any[]) : any; - isEmpty() : boolean; - keys() : string[]; - last() : T; - lastIndexOf(value : any, fromIndex? : number) : number; - map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - map(predicate? : R) : T[]; - max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - max(predicate? : R) : T; - min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - min(predicate? : R) : T; - reduce(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reduceRight(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reject(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - reject(predicate? : R) : T[]; - rest() : T[]; - select(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - select(predicate? : R) : T[]; - shuffle() : T[]; - size() : number; - some(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - some(predicate? : R) : boolean; - sortBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - sortBy(predicate? : R) : T[]; - tail() : T[]; - take(n? : number) : T[]; - toArray() : T[]; - without(...values : any[]) : T[]; - } - - class Collection> extends CollectionBase { - /** @deprecated use Typescript classes */ - static extend(prototypeProperties? : any, classProperties? : any) : Function; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - attach(ids : any[], options? : SyncOptions) : Promise>; - count(column? : string, options? : SyncOptions) : Promise; - create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; - detach(ids : any[], options? : SyncOptions) : Promise; - fetchOne(options? : CollectionFetchOneOptions) : Promise; - load(relations : string|string[], options? : SyncOptions) : Promise>; - query(...query : string[]) : Collection; - query(query : {[key : string] : any}) : Collection; - query(callback : (qb : knex.QueryBuilder) => void) : Collection; - query() : knex.QueryBuilder; - resetQuery() : Collection; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - updatePivot(attributes : any, options? : PivotOptions) : Promise; - withPivot(columns : string[]) : Collection; - } - - interface ModelOptions { - tableName? : string; - hasTimestamps? : boolean; - parse? : boolean; - } - - interface LoadOptions extends SyncOptions { - withRelated: string|any|any[]; - } - - interface FetchOptions extends SyncOptions { - require? : boolean; - columns? : string|string[]; - withRelated? : string|any|any[]; - } - - interface FetchAllOptions extends SyncOptions { - require? : boolean; - } - - interface SaveOptions extends SyncOptions { - method? : string; - defaults? : string; - patch? : boolean; - require? : boolean; - } - - interface SerializeOptions { - shallow? : boolean; - omitPivot? : boolean; - } - - interface SetOptions { - unset? : boolean; - } - - interface TimestampOptions { - method? : string; - } - - interface SyncOptions { - transacting? : knex.Transaction; - debug? : boolean; - } - - interface CollectionOptions { - comparator? : boolean|string|((a : T, b : T) => number); - } - - interface CollectionAddOptions extends EventOptions { - at? : number; - merge? : boolean; - } - - interface CollectionFetchOptions { - require? : boolean; - withRelated? : string|string[]; - } - - interface CollectionFetchOneOptions { - require? : boolean; - columns? : string|string[]; - } - - interface CollectionSetOptions extends EventOptions { - add? : boolean; - remove? : boolean; - merge?: boolean; - } - - interface PivotOptions { - query? : Function|any; - require? : boolean; - } - - interface EventOptions { - silent? : boolean; - } - - interface EventFunction { - (model: T, attrs: any, options: any) : Promise|void; - } - - interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} - } - - export = Bookshelf; + plugin(name: string | string[] | Function, options?: any) : Bookshelf; + transaction(callback : (transaction : knex.Transaction) => T) : Promise; } + +declare function Bookshelf(knex : knex) : Bookshelf; + +declare namespace Bookshelf { + abstract class Events { + on(event? : string, callback? : EventFunction, context? : any) : void; + off(event? : string) : void; + trigger(event? : string, ...args : any[]) : void; + triggerThen(name : string, ...args : any[]) : Promise; + once(event : string, callback : EventFunction, context? : any) : void; + } + + interface IModelBase { + /** Should be declared as a getter instead of a plain property. */ + hasTimestamps? : boolean|string[]; + /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ + tableName? : string; + } + + abstract class ModelBase> extends Events> implements IModelBase { + /** If overriding, must use a getter instead of a plain property. */ + idAttribute : string; + + constructor(attributes? : any, options? : ModelOptions); + + clear() : T; + clone() : T; + escape(attribute : string) : string; + format(attributes : any) : any; + get(attribute : string) : any; + has(attribute : string) : boolean; + hasChanged(attribute? : string) : boolean; + isNew() : boolean; + parse(response : any) : any; + previousAttributes() : any; + previous(attribute : string) : any; + related>(relation : string) : R | Collection; + serialize(options? : SerializeOptions) : any; + set(attribute?: {[key : string] : any}, options? : SetOptions) : T; + set(attribute : string, value? : any, options? : SetOptions) : T; + timestamp(options? : TimestampOptions) : any; + toJSON(options? : SerializeOptions) : any; + unset(attribute : string) : T; + + // lodash methods + invert() : R; + keys() : string[]; + omit(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; + omit(...attributes : string[]) : R; + pairs() : any[][]; + pick(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; + pick(...attributes : string[]) : R; + values() : any[]; + } + + class Model> extends ModelBase { + static collection>(models? : T[], options? : CollectionOptions) : Collection; + static count(column? : string, options? : SyncOptions) : Promise; + /** @deprecated use Typescript classes */ + static extend>(prototypeProperties? : any, classProperties? : any) : Function; // should return a type + static fetchAll>() : Promise>; + /** @deprecated should use `new` objects instead. */ + static forge(attributes? : any, options? : ModelOptions) : T; + + belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; + belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; + count(column? : string, options? : SyncOptions) : Promise; + destroy(options? : SyncOptions) : Promise; + fetch(options? : FetchOptions) : Promise; + fetchAll(options? : FetchAllOptions) : Promise>; + hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; + hasOne>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; + load(relations : string|string[], options? : LoadOptions) : Promise; + morphMany>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : Collection; + morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; + morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; + morphTo(name : string, ...target : typeof Model[]) : T; + query(...query : string[]) : T; + query(query : {[key : string] : any}) : T; + query(callback : (qb : knex.QueryBuilder) => void) : T; + query() : knex.QueryBuilder; + refresh(options? : FetchOptions) : Promise; + resetQuery() : T; + save(key? : string, val? : string, options? : SaveOptions) : Promise; + save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + where(properties : {[key : string] : any}) : T; + where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; + } + + abstract class CollectionBase> extends Events { + add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; + at(index : number) : T; + clone() : Collection; + fetch(options? : CollectionFetchOptions) : Promise>; + findWhere(match : {[key : string] : any}) : T; + get(id : any) : T; + invokeThen(name : string, ...args : any[]) : Promise; + parse(response : any) : any; + pluck(attribute : string) : any[]; + pop() : void; + push(model : any) : Collection; + reduceThen(iterator : (prev : R, cur : T, idx : number, array : T[]) => R, initialValue : R, context : any) : Promise; + remove(model : T, options? : EventOptions) : T; + remove(model : T[], options? : EventOptions) : T[]; + reset(model : any[], options? : CollectionAddOptions) : T[]; + serialize(options? : SerializeOptions) : any; + set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; + shift(options? : EventOptions) : void; + slice(begin? : number, end? : number) : void; + toJSON(options? : SerializeOptions) : any; + unshift(model : any, options? : CollectionAddOptions) : void; + where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; + + // lodash methods + all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + all(predicate? : R) : boolean; + any(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + any(predicate? : R) : boolean; + chain() : Lodash.LoDashExplicitObjectWrapper; + collect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + collect(predicate? : R) : T[]; + contains(value : any, fromIndex? : number) : boolean; + countBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; + countBy(predicate? : R) : Lodash.Dictionary; + detect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; + detect(predicate? : R) : T; + difference(...values : T[]) : T[]; + drop(n? : number) : T[]; + each(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; + each(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; + each(callback? : Lodash.ObjectIterator, thisArg? : any) : T; + every(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + every(predicate? : R) : boolean; + filter(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + filter(predicate? : R) : T[]; + find(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; + find(predicate? : R) : T; + first() : T; + foldl(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + foldr(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + forEach(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; + forEach(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; + forEach(callback? : Lodash.ObjectIterator, thisArg? : any) : T; + groupBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; + groupBy(predicate? : R) : Lodash.Dictionary; + head() : T; + include(value : any, fromIndex? : number) : boolean; + indexOf(value : any, fromIndex? : number) : number; + initial() : T[]; + inject(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + invoke(methodName : string|Function, ...args : any[]) : any; + isEmpty() : boolean; + keys() : string[]; + last() : T; + lastIndexOf(value : any, fromIndex? : number) : number; + map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + map(predicate? : R) : T[]; + max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; + max(predicate? : R) : T; + min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; + min(predicate? : R) : T; + reduce(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + reduceRight(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + reject(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + reject(predicate? : R) : T[]; + rest() : T[]; + select(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + select(predicate? : R) : T[]; + shuffle() : T[]; + size() : number; + some(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + some(predicate? : R) : boolean; + sortBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + sortBy(predicate? : R) : T[]; + tail() : T[]; + take(n? : number) : T[]; + toArray() : T[]; + without(...values : any[]) : T[]; + } + + class Collection> extends CollectionBase { + /** @deprecated use Typescript classes */ + static extend(prototypeProperties? : any, classProperties? : any) : Function; + /** @deprecated should use `new` objects instead. */ + static forge(attributes? : any, options? : ModelOptions) : T; + + attach(ids : any[], options? : SyncOptions) : Promise>; + count(column? : string, options? : SyncOptions) : Promise; + create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; + detach(ids : any[], options? : SyncOptions) : Promise; + fetchOne(options? : CollectionFetchOneOptions) : Promise; + load(relations : string|string[], options? : SyncOptions) : Promise>; + query(...query : string[]) : Collection; + query(query : {[key : string] : any}) : Collection; + query(callback : (qb : knex.QueryBuilder) => void) : Collection; + query() : knex.QueryBuilder; + resetQuery() : Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + updatePivot(attributes : any, options? : PivotOptions) : Promise; + withPivot(columns : string[]) : Collection; + } + + interface ModelOptions { + tableName? : string; + hasTimestamps? : boolean; + parse? : boolean; + } + + interface LoadOptions extends SyncOptions { + withRelated: string|any|any[]; + } + + interface FetchOptions extends SyncOptions { + require? : boolean; + columns? : string|string[]; + withRelated? : string|any|any[]; + } + + interface FetchAllOptions extends SyncOptions { + require? : boolean; + } + + interface SaveOptions extends SyncOptions { + method? : string; + defaults? : string; + patch? : boolean; + require? : boolean; + } + + interface SerializeOptions { + shallow? : boolean; + omitPivot? : boolean; + } + + interface SetOptions { + unset? : boolean; + } + + interface TimestampOptions { + method? : string; + } + + interface SyncOptions { + transacting? : knex.Transaction; + debug? : boolean; + } + + interface CollectionOptions { + comparator? : boolean|string|((a : T, b : T) => number); + } + + interface CollectionAddOptions extends EventOptions { + at? : number; + merge? : boolean; + } + + interface CollectionFetchOptions { + require? : boolean; + withRelated? : string|string[]; + } + + interface CollectionFetchOneOptions { + require? : boolean; + columns? : string|string[]; + } + + interface CollectionSetOptions extends EventOptions { + add? : boolean; + remove? : boolean; + merge?: boolean; + } + + interface PivotOptions { + query? : Function|any; + require? : boolean; + } + + interface EventOptions { + silent? : boolean; + } + + interface EventFunction { + (model: T, attrs: any, options: any) : Promise|void; + } + + interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} +} + +export = Bookshelf; + diff --git a/boom/index.d.ts b/boom/index.d.ts index c7ccc1734f..6945673678 100644 --- a/boom/index.d.ts +++ b/boom/index.d.ts @@ -5,6 +5,8 @@ /// +export = Boom; + declare namespace Boom { export interface BoomError { @@ -53,7 +55,3 @@ declare namespace Boom { export function gatewayTimeout(message?: string, data?: any): BoomError; export function badImplementation(message?: string, data?: any): BoomError; } - -declare module "boom" { - export = Boom; -} diff --git a/bowser/index.d.ts b/bowser/index.d.ts index 2bf1b3d510..1a9fa4bf70 100644 --- a/bowser/index.d.ts +++ b/bowser/index.d.ts @@ -3,10 +3,9 @@ // Definitions by: Paulo Cesar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'bowser' { - var def: BowserModule.IBowser; - export = def; -} +declare var def: BowserModule.IBowser; +export = def; +export as namespace bowser; declare namespace BowserModule { diff --git a/business-rules-engine/business-rules-engine-tests.ts b/business-rules-engine/business-rules-engine-tests.ts index 1aecba7f9f..2a8180ce6b 100644 --- a/business-rules-engine/business-rules-engine-tests.ts +++ b/business-rules-engine/business-rules-engine-tests.ts @@ -1,5 +1,6 @@ /// import * as Validators from './node-validators'; +import Validation = require("business-rules-engine"); export interface IPerson{ Checked:boolean; diff --git a/business-rules-engine/index.d.ts b/business-rules-engine/index.d.ts index 929e24f335..197c4fd23f 100644 --- a/business-rules-engine/index.d.ts +++ b/business-rules-engine/index.d.ts @@ -239,4 +239,5 @@ declare namespace Validation { static GetValidationMessage(validator: any): string; } } -declare module "business-rules-engine" {export = Validation;} +export = Validation; +export as namespace Validation; diff --git a/business-rules-engine/node-validators.d.ts b/business-rules-engine/node-validators.d.ts index 5439fd1165..715acbb243 100644 --- a/business-rules-engine/node-validators.d.ts +++ b/business-rules-engine/node-validators.d.ts @@ -6,7 +6,7 @@ /// /// - +import Validation = require("business-rules-engine"); export as namespace Validators; import * as moment from 'moment'; diff --git a/bytebuffer/index.d.ts b/bytebuffer/index.d.ts index 7ad0c86f30..ed5677dd05 100644 --- a/bytebuffer/index.d.ts +++ b/bytebuffer/index.d.ts @@ -610,7 +610,6 @@ declare class ByteBuffer writeVarint64ZigZag( value: number | Long, offset?: number ): ByteBuffer | number; } -declare module 'bytebuffer' { - namespace ByteBuffer {} - export = ByteBuffer; -} +declare namespace ByteBuffer {} +export = ByteBuffer; +export as namespace ByteBuffer; diff --git a/chalk/index.d.ts b/chalk/index.d.ts index 1ead986818..97c7f7427a 100644 --- a/chalk/index.d.ts +++ b/chalk/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Diullei Gomes , Bart van der Schoor , Nico Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Chalk; + declare namespace Chalk { export var enabled: boolean; @@ -116,7 +118,3 @@ declare namespace Chalk { } } -declare module "chalk" { - export = Chalk; -} - diff --git a/chartist/chartist-tests.ts b/chartist/chartist-tests.ts index 94c43874f7..2a4a362e7e 100644 --- a/chartist/chartist-tests.ts +++ b/chartist/chartist-tests.ts @@ -1,3 +1,4 @@ +import Chartist = require("chartist"); Chartist.escapingMap = { '&': '&', '<': '<', diff --git a/chartist/index.d.ts b/chartist/index.d.ts index 6c679dc1d8..117f0914ae 100644 --- a/chartist/index.d.ts +++ b/chartist/index.d.ts @@ -558,6 +558,5 @@ declare namespace Chartist { declare var Chartist: Chartist.ChartistStatic; -declare module 'chartist' { - export = Chartist; -} +export = Chartist; +export as namespace Chartist; diff --git a/codemirror/codemirror-tests.ts b/codemirror/codemirror-tests.ts index 4bda62ccf2..c7b4e32ac6 100644 --- a/codemirror/codemirror-tests.ts +++ b/codemirror/codemirror-tests.ts @@ -1,4 +1,4 @@ - +import CodeMirror = require('codemirror'); var myCodeMirror: CodeMirror.Editor = CodeMirror(document.body); diff --git a/codemirror/index.d.ts b/codemirror/index.d.ts index bade422821..6108df1fdc 100644 --- a/codemirror/index.d.ts +++ b/codemirror/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: mihailik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = CodeMirror; +export as namespace CodeMirror; + declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; @@ -1127,6 +1130,3 @@ declare namespace CodeMirror { } } -declare module "codemirror" { - export = CodeMirror; -} diff --git a/commander/commander-tests.ts b/commander/commander-tests.ts index bf57f1897c..f6f3918f6a 100644 --- a/commander/commander-tests.ts +++ b/commander/commander-tests.ts @@ -1,14 +1,5 @@ // NOTE: import statement can not use in TypeScript 1.0.1 -var program:commander.IExportedCommand = require('commander'); - -declare namespace commander { - interface IExportedCommand { - peppers:boolean; - pineapple:boolean; - bbq:boolean; - cheese:string; - } -} +import program = require('commander'); program .version('0.0.1') @@ -19,10 +10,10 @@ program .parse(process.argv); console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineapple'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); +if (program['peppers']) console.log(' - peppers'); +if (program['pineapple']) console.log(' - pineapple'); +if (program['bbq']) console.log(' - bbq'); +console.log(' - %s cheese', program['cheese']); function range(val:string) { return val.split('..').map(Number); @@ -41,18 +32,6 @@ function increaseVerbosity(v:any, total:number) { return total + 1; } -declare namespace commander { - interface IExportedCommand { - integer:number; - float:number; - optional:string; - range:number[]; - list:string[]; - collect:string[]; - verbose:number; - } -} - program .version('0.0.1') .usage('[options] ') @@ -65,15 +44,15 @@ program .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) .parse(process.argv); -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' collect: %j', program.collect); -console.log(' verbosity: %j', program.verbose); -console.log(' args: %j', program.args); +console.log(' int: %j', program['integer']); +console.log(' float: %j', program['float']); +console.log(' optional: %j', program['optional']); +program['range'] = program['range'] || []; +console.log(' range: %j..%j', program['range'][0], program['range'][1]); +console.log(' list: %j', program['list']); +console.log(' collect: %j', program['collect']); +console.log(' verbosity: %j', program['verbose']); +console.log(' args: %j', program['args']); program diff --git a/commander/index.d.ts b/commander/index.d.ts index 9debd6ccd7..6edbd987b0 100644 --- a/commander/index.d.ts +++ b/commander/index.d.ts @@ -5,6 +5,9 @@ /// +declare var _tmp: commander.IExportedCommand; +export = _tmp; + declare namespace commander { interface ICommandStatic { /** @@ -403,10 +406,6 @@ declare namespace commander { interface IExportedCommand extends ICommand { Command: commander.ICommandStatic; Option: commander.IOptionStatic; + [key: string]: any; } } - -declare module "commander" { - var _tmp:commander.IExportedCommand; - export = _tmp; -} diff --git a/commonmark/index.d.ts b/commonmark/index.d.ts index 84a76c47f6..bba8cd7e36 100644 --- a/commonmark/index.d.ts +++ b/commonmark/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Nico Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = commonmark; +export as namespace commonmark; declare namespace commonmark { @@ -208,7 +210,3 @@ declare namespace commonmark { } } - -declare module 'commonmark' { - export = commonmark; -} diff --git a/content-type/index.d.ts b/content-type/index.d.ts index 6e901e7f86..086e1b9d4f 100644 --- a/content-type/index.d.ts +++ b/content-type/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var x: ContentType.MediaTypeStatic; +export = x; + declare namespace ContentType { interface MediaType { type: string; @@ -25,8 +28,3 @@ declare namespace ContentType { mediaCmp(a: MediaType, b: MediaType): number; } } - -declare module "content-type" { - var x: ContentType.MediaTypeStatic; - export = x; -} diff --git a/cookiejs/cookiejs-tests.ts b/cookiejs/cookiejs-tests.ts index 5bea7256bb..d1f382e193 100644 --- a/cookiejs/cookiejs-tests.ts +++ b/cookiejs/cookiejs-tests.ts @@ -2,6 +2,8 @@ // Based on https://github.com/js-coder/cookie.js/blob/gh-pages/tests/spec.js +import cookie = require("cookiejs"); + cookie.set({a: '1', b: '2', c: '3'}); cookie; diff --git a/cookiejs/index.d.ts b/cookiejs/index.d.ts index 77b8973aed..ba7f0ee4f1 100644 --- a/cookiejs/index.d.ts +++ b/cookiejs/index.d.ts @@ -5,6 +5,10 @@ /** * Shortcut for cookie.get() */ + +export = cookie; +export as namespace cookie; + declare function cookie(key : string, fallback?: string) : string; declare function cookie(keys : string[], fallback?: string) : string; @@ -44,7 +48,3 @@ declare namespace cookie { */ export function enabled() : boolean; } - -declare module "cookiejs" { - export = cookie; -} diff --git a/cropperjs/index.d.ts b/cropperjs/index.d.ts index f2f8e861e5..0759f97732 100644 --- a/cropperjs/index.d.ts +++ b/cropperjs/index.d.ts @@ -4,6 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare const Cropper: typeof cropperjs.Cropper; +export = Cropper; +export as namespace Cropper; + declare module cropperjs { export enum CropperViewMods { CropBoxIsJustWithInTheContainer = 0, @@ -446,7 +450,3 @@ declare module cropperjs { } } -declare module "cropperjs" { - const Cropper: typeof cropperjs.Cropper; - export = Cropper; -} diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index 19ea3cd196..875cb018bc 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import hashes = CryptoJS.hashes; +export = hashes; +export as namespace CryptoJS; + declare namespace CryptoJS { type Hash = (message: string, key?: string, ...options: any[]) => string; @@ -61,7 +66,3 @@ declare namespace CryptoJS { export var hashes: Hashes; } -declare module 'crypto-js' { - import hashes = CryptoJS.hashes; - export = hashes; -} diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index 33618ea63f..720c81251f 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -1,4 +1,4 @@ - +import cucumber = require("cucumber"); function StepSample() { type Callback = cucumber.CallbackStepDefinition; diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index d0e742d9c2..1d27bc28f6 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Abraão Alves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = cucumber; + declare namespace cucumber { export interface CallbackStepDefinition{ @@ -49,7 +51,3 @@ declare namespace cucumber { registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; } } - -declare module 'cucumber'{ - export = cucumber; -} diff --git a/d3-dsv/index.d.ts b/d3-dsv/index.d.ts index ef963eeeaa..b798c4fcbe 100644 --- a/d3-dsv/index.d.ts +++ b/d3-dsv/index.d.ts @@ -4,18 +4,16 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -//commonjs loader -declare module "d3-dsv" { - /** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */ - var loader: ( - /** the symbol used to seperate cells in the row.*/ - delimiter: string, - /** example: "text/plain" */ - encoding?: string) => _d3dsv.D3Dsv; - export = loader; -} +declare var loader: ( + /** the symbol used to seperate cells in the row.*/ + delimiter: string, + /** example: "text/plain" */ + encoding?: string) => _d3dsv.D3Dsv; +export = loader; +export as namespace d3_dsv; + declare module _d3dsv { /** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */ diff --git a/debug/index.d.ts b/debug/index.d.ts index 80d7fc30c4..45d3ad02f3 100644 --- a/debug/index.d.ts +++ b/debug/index.d.ts @@ -5,10 +5,8 @@ declare var debug: debug.IDebug; -// Support AMD require -declare module 'debug' { - export = debug; -} +export = debug; +export as namespace debug; declare namespace debug { export interface IDebug { diff --git a/decorum/index.d.ts b/decorum/index.d.ts index 07660acf9f..d442e6d666 100644 --- a/decorum/index.d.ts +++ b/decorum/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Danil Flores // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'decorum' { - export = decorum; -} +export = decorum; +export as namespace decorum; declare namespace decorum { /** diff --git a/deep-freeze/index.d.ts b/deep-freeze/index.d.ts index 8ab079d6de..92f6c8db2f 100644 --- a/deep-freeze/index.d.ts +++ b/deep-freeze/index.d.ts @@ -3,13 +3,11 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var deepFreeze: DeepFreeze.DeepFreezeInterface; +export = deepFreeze; + declare namespace DeepFreeze { export interface DeepFreezeInterface { (obj: T): T; } } - -declare module "deep-freeze" { - let deepFreeze: DeepFreeze.DeepFreezeInterface; - export = deepFreeze; -} diff --git a/diff/index.d.ts b/diff/index.d.ts index b1f947300b..bd8acd078d 100644 --- a/diff/index.d.ts +++ b/diff/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = JsDiff; +export as namespace JsDiff; + declare namespace JsDiff { interface IDiffResult { value: string; @@ -54,7 +57,3 @@ declare namespace JsDiff { function convertChangesToDMP(changes:IDiffResult[]):{0: number; 1:string;}[]; } - -declare module "diff" { - export = JsDiff; -} diff --git a/docopt/index.d.ts b/docopt/index.d.ts index 8976c6fe36..05d0da4524 100644 --- a/docopt/index.d.ts +++ b/docopt/index.d.ts @@ -3,6 +3,13 @@ // Definitions by: Giovanni Bassi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * @param doc should be a string with the help message, written according to rules of the docopt language. + */ +declare function docopt(doc: string, options: DocoptOption): any; + +export = docopt; + interface DocoptOption { /** is an optional argument vector. It defaults to the arguments passed to your program (process.argv[2..]). You can also supply it with an array of strings, as with process.argv. For example: ['--verbose', '-o', 'hai.txt'] */ argv?: Array, @@ -15,9 +22,3 @@ interface DocoptOption { /** (default true) If set to false will cause docopt to throw exceptions instead of printing the error to console and terminating the application. This flag is mainly for testing purposes. */ exit?: boolean } -declare module "docopt" { - /** - * @param doc should be a string with the help message, written according to rules of the docopt language. - */ - export function docopt(doc: string, options: DocoptOption): any; -} diff --git a/domready/domready-tests.ts b/domready/domready-tests.ts index a59a590716..01be4213f4 100644 --- a/domready/domready-tests.ts +++ b/domready/domready-tests.ts @@ -1,4 +1,4 @@ - +import domready = require("domready"); domready(function () { // dom is loaded! diff --git a/domready/index.d.ts b/domready/index.d.ts index 80981b74a5..9548757894 100644 --- a/domready/index.d.ts +++ b/domready/index.d.ts @@ -5,6 +5,5 @@ declare function domready(callback: () => any) : void; -declare module "domready" { - export = domready; -} +export = domready; +export as namespace domready; \ No newline at end of file diff --git a/donna/index.d.ts b/donna/index.d.ts index 3971a0ef53..0b47420998 100644 --- a/donna/index.d.ts +++ b/donna/index.d.ts @@ -3,9 +3,7 @@ // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "donna" { - function generateMetadata(modules: string[]): DonnaTypes.Metadata; -} +export function generateMetadata(modules: string[]): DonnaTypes.Metadata; declare namespace DonnaTypes { interface Metadata { diff --git a/dotenv/index.d.ts b/dotenv/index.d.ts index b18e9bd03b..7391133781 100644 --- a/dotenv/index.d.ts +++ b/dotenv/index.d.ts @@ -3,12 +3,10 @@ // Definitions by: Jussi Kinnula // Definitions: https://github.com/jussikinnula/DefinitelyTyped +export function config(options?: dotenvOptions): boolean; + interface dotenvOptions { silent?: boolean; path?: string; encoding?: string; } - -declare module 'dotenv' { - export function config(options?: dotenvOptions): boolean; -} diff --git a/dragula/dragula-tests.ts b/dragula/dragula-tests.ts index 3f293f358e..d5b28e37dd 100644 --- a/dragula/dragula-tests.ts +++ b/dragula/dragula-tests.ts @@ -1,4 +1,4 @@ - +import dragula = require("dragula"); var d1 = dragula([document.querySelector('#left'), document.querySelector('#right')]); diff --git a/dragula/index.d.ts b/dragula/index.d.ts index a00929e8f3..98ff1f3108 100644 --- a/dragula/index.d.ts +++ b/dragula/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: Paul Welter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var dragula: dragula.Dragula; + +export = dragula; +export as namespace dragula; + declare namespace dragula { interface DragulaOptions { containers?: Element[]; @@ -38,9 +43,3 @@ declare namespace dragula { (): Drake; } } - -declare var dragula: dragula.Dragula; - -declare module "dragula" { - export = dragula; -} diff --git a/drop/drop-tests.ts b/drop/drop-tests.ts index 8aa98c69f4..b36573062a 100644 --- a/drop/drop-tests.ts +++ b/drop/drop-tests.ts @@ -1,4 +1,5 @@ /// +import Drop = require("drop"); var yellowBox = document.querySelector(".yellow"); var greenBox = document.querySelector(".green"); diff --git a/drop/index.d.ts b/drop/index.d.ts index 7244d9ed78..a16554ff48 100644 --- a/drop/index.d.ts +++ b/drop/index.d.ts @@ -5,6 +5,9 @@ /// +export = Drop; +export as namespace Drop; + // global Drop constructor declare class Drop { constructor(options: Drop.IDropOptions); @@ -50,7 +53,3 @@ declare namespace Drop { } } -declare module "drop" { - export = Drop; -} - diff --git a/dsv/index.d.ts b/dsv/index.d.ts index b8f268ee96..2fac461110 100644 --- a/dsv/index.d.ts +++ b/dsv/index.d.ts @@ -4,18 +4,15 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -//commonjs loader -declare module "dsv" { - /** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */ - var loader: ( - /** the symbol used to seperate cells in the row.*/ - delimiter: string, - /** example: "text/plain" */ - encoding?: string) => _dsv.Dsv; - export = loader; -} +declare var loader: ( + /** the symbol used to seperate cells in the row.*/ + delimiter: string, + /** example: "text/plain" */ + encoding?: string) => _dsv.Dsv; +export = loader; +export as namespace d3_dsv; declare module _dsv { /** A parser and formatter for DSV (CSV and TSV) files. diff --git a/easystarjs/index.d.ts b/easystarjs/index.d.ts index 6faec22d3b..c4da0c51a7 100644 --- a/easystarjs/index.d.ts +++ b/easystarjs/index.d.ts @@ -7,6 +7,8 @@ easystarjs.d.ts may be freely distributed under the MIT license. */ +export = easystarjs; + declare namespace easystarjs { class js @@ -30,8 +32,4 @@ declare namespace easystarjs x: number; y: number; } -} - -declare module "easystarjs" { - export = easystarjs; -} +} \ No newline at end of file diff --git a/electron-window-state/index.d.ts b/electron-window-state/index.d.ts index 5106df40e4..1ff10ed7d5 100644 --- a/electron-window-state/index.d.ts +++ b/electron-window-state/index.d.ts @@ -5,6 +5,12 @@ /// +/* + * Load the previous state with fallback to defaults + */ +declare function windowStateKeeper(opts: ElectronWindowState.WindowStateKeeperOptions): ElectronWindowState.WindowState; +export = windowStateKeeper; + declare namespace ElectronWindowState { interface WindowState { /* @@ -80,11 +86,3 @@ declare namespace ElectronWindowState { fullScreen?: boolean; } } - -declare module 'electron-window-state' { - /* - * Load the previous state with fallback to defaults - */ - function windowStateKeeper(opts: ElectronWindowState.WindowStateKeeperOptions): ElectronWindowState.WindowState; - export = windowStateKeeper; -} diff --git a/emissary/index.d.ts b/emissary/index.d.ts index 6547d35e51..fc9ee6e38d 100644 --- a/emissary/index.d.ts +++ b/emissary/index.d.ts @@ -52,10 +52,10 @@ declare namespace Emissary { } } -declare module "emissary" { - var Emitter:Emissary.IEmitterStatic; - var Subscriber:Emissary.ISubscriberStatic; - var Signal:Function; // TODO - var Behavior:Function; // TODO - var combine:Function; // TODO -} + +export var Emitter:Emissary.IEmitterStatic; +export var Subscriber:Emissary.ISubscriberStatic; +export var Signal:Function; // TODO +export var Behavior:Function; // TODO +export var combine:Function; // TODO + diff --git a/empower/empower-tests.ts b/empower/empower-tests.ts index 5e1c4f4c52..0ed1df04ef 100644 --- a/empower/empower-tests.ts +++ b/empower/empower-tests.ts @@ -1,4 +1,4 @@ - +import empower = require("empower"); var baseAssert:any; var fakeFormatter:any; diff --git a/empower/index.d.ts b/empower/index.d.ts index 56a9757be5..19e64045fa 100644 --- a/empower/index.d.ts +++ b/empower/index.d.ts @@ -5,6 +5,9 @@ declare function empower(originalAssert:any, formatter:any, options?:empower.Options):any; +export = empower; +export as namespace empower; + declare namespace empower { export interface Options { destructive?: boolean; @@ -13,7 +16,3 @@ declare namespace empower { patterns?: string[]; } } - -declare module "empower" { - export = empower; -} diff --git a/esprima/index.d.ts b/esprima/index.d.ts index a076c1dda3..150a917d86 100644 --- a/esprima/index.d.ts +++ b/esprima/index.d.ts @@ -5,6 +5,9 @@ /// +export = esprima; +export as namespace esprima; + declare namespace esprima { const version: string; @@ -100,7 +103,3 @@ declare namespace esprima { }; } - -declare module "esprima" { - export = esprima -} diff --git a/evaporate/evaporate-tests.ts b/evaporate/evaporate-tests.ts index 1ed6a7fce3..ea4a4ac9bf 100644 --- a/evaporate/evaporate-tests.ts +++ b/evaporate/evaporate-tests.ts @@ -1,4 +1,4 @@ - +import Evaporate = require("evaporate"); function test_upload() { var evaporate = new Evaporate({}); diff --git a/evaporate/index.d.ts b/evaporate/index.d.ts index 2a67455461..df34a35388 100644 --- a/evaporate/index.d.ts +++ b/evaporate/index.d.ts @@ -2,12 +2,11 @@ // Project: https://github.com/TTLabs/EvaporateJS // Definitions by: Andrew Kuklewicz , Chris Rhoden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Evaporate; + declare class Evaporate { cancel(id:string): boolean; constructor(config:any); add(config:any): string; } - -declare module 'evaporate' { - export = Evaporate; -} diff --git a/event-kit/index.d.ts b/event-kit/index.d.ts index d920a4f6ea..de4e7a485c 100644 --- a/event-kit/index.d.ts +++ b/event-kit/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Vadim Macagon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = AtomEventKit; + declare namespace AtomEventKit { interface IDisposable { dispose(): void; @@ -76,7 +78,3 @@ declare namespace AtomEventKit { /** A utility class for implementing event-based APIs. */ var Emitter: EmitterStatic; } - -declare module "event-kit" { - export = AtomEventKit; -} diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index fd4f41a25f..c0a532fc87 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -29,7 +29,7 @@ declare namespace Assume { let assume = Assume.assume; class EventEmitterTest { - v: EventEmitter3.EventEmitter; + v: any; constructor() { this.v = new EventEmitter(); @@ -54,40 +54,40 @@ class EventEmitterTest { on() { var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.on('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.on('click', fn, this); + var v1 = this.v.on('click', fn); + var v2 = this.v.on('click', fn, this); } once() { var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.once('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.once('click', fn, this); + var v1 = this.v.once('click', fn); + var v2 = this.v.once('click', fn, this); } removeListener() { var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.removeListener('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.removeListener('click', fn, true); + var v1 = this.v.removeListener('click', fn); + var v2 = this.v.removeListener('click', fn, true); } removeAllListeners() { - var v1: EventEmitter3.EventEmitter = this.v.removeAllListeners('click'); + var v1 = this.v.removeAllListeners('click'); } off() { var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.off('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.off('click', fn, true); + var v1 = this.v.off('click', fn); + var v2 = this.v.off('click', fn, true); } addListener() { var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.addListener('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.addListener('click', fn, this); + var v1 = this.v.addListener('click', fn); + var v2 = this.v.addListener('click', fn, this); } setMaxListeners() { - var v1: EventEmitter3.EventEmitter = this.v.setMaxListeners(); + var v1 = this.v.setMaxListeners(); } } @@ -255,7 +255,7 @@ describe('EventEmitter', function tests() { it('receives the emitted events', function (done) { var e = new EventEmitter(); - e.on('data', function (a: string, b: EventEmitter3.EventEmitter, c: Date, d: void, undef: void) { + e.on('data', function (a: string, b: any, c: Date, d: void, undef: void) { assume(a).equals('foo'); assume(b).equals(e); assume(c).is.instanceOf(Date); diff --git a/eventemitter3/index.d.ts b/eventemitter3/index.d.ts index 0d692b8247..63e1cd12e1 100644 --- a/eventemitter3/index.d.ts +++ b/eventemitter3/index.d.ts @@ -3,6 +3,12 @@ // Definitions by: Yuichi Murata , Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Expose the module. +// +declare var event_emitter3: EventEmitter3.EventEmitter3Static; +export = event_emitter3; + declare namespace EventEmitter3 { interface EventEmitter3Static { new (): EventEmitter; @@ -113,11 +119,3 @@ declare namespace EventEmitter3 { setMaxListeners(): EventEmitter; } } - -declare module 'eventemitter3' { - // - // Expose the module. - // - var EventEmitter3: EventEmitter3.EventEmitter3Static; - export = EventEmitter3; -} diff --git a/falcor-json-graph/index.d.ts b/falcor-json-graph/index.d.ts index 7c42b654df..d2bb47563b 100644 --- a/falcor-json-graph/index.d.ts +++ b/falcor-json-graph/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Quramy // Definitions: https://github.com/borisyankov/DefinitelyTyped +export = FalcorJsonGraph; + declare namespace FalcorJsonGraph { // NOTE: The following types are described at https://github.com/Netflix/falcor/tree/master/lib/typedefs . @@ -98,7 +100,3 @@ declare namespace FalcorJsonGraph { function pathInvalidation(path: string | FalcorJsonGraph.PathSet): FalcorJsonGraph.InvalidPath; } -declare module 'falcor-json-graph' { - export = FalcorJsonGraph; -} - diff --git a/falcor/index.d.ts b/falcor/index.d.ts index f16505a882..519c643fd4 100644 --- a/falcor/index.d.ts +++ b/falcor/index.d.ts @@ -5,6 +5,9 @@ /// +export = FalcorModel; +export as namespace falcor; + declare namespace FalcorModel { ///////////////////////////////////////////////////// @@ -271,7 +274,3 @@ declare namespace FalcorModel { catchException(handler: (exception: any) => boolean): Scheduler; } } - -declare module 'falcor' { - export = FalcorModel; -} diff --git a/ffi/index.d.ts b/ffi/index.d.ts index bd0f0fa31d..19107f373e 100644 --- a/ffi/index.d.ts +++ b/ffi/index.d.ts @@ -6,188 +6,187 @@ /// -declare module "ffi" { - import ref = require('ref'); - import StructType = require('ref-struct'); +import ref = require('ref'); +import StructType = require('ref-struct'); - /** Provides a friendly API on-top of `DynamicLibrary` and `ForeignFunction`. */ - export var Library: { - /** The extension to use on libraries. */ - EXT: string; - - /** - * @param libFile name of library - * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] - * @param lib hash that will be extended - */ - new (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; - - /** - * @param libFile name of library - * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] - * @param lib hash that will be extended - */ - (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; - }; - - /** Get value of errno. */ - export function errno(): number; - - export interface Function extends ref.Type { - /** The type of return value. */ - retType: ref.Type; - /** The type of arguments. */ - argTypes: ref.Type[]; - /** Is set for node-ffi functions. */ - ffi_type: Buffer; - abi: number; - - /** Get a `Callback` pointer of this function type. */ - toPointer(fn: (...args: any[]) => any): Buffer; - /** Get a `ForeignFunction` of this function type. */ - toFunction(buf: Buffer): ForeignFunction; - } - - /** Creates and returns a type for a C function pointer. */ - export var Function: { - new (retType: ref.Type, argTypes: any[], abi?: number): Function; - new (retType: string, argTypes: any[], abi?: number): Function; - (retType: ref.Type, argTypes: any[], abi?: number): Function; - (retType: string, argTypes: any[], abi?: number): Function; - }; - - export interface ForeignFunction { - (...args: any[]): any; - async(...args: any[]): void; - } +/** Provides a friendly API on-top of `DynamicLibrary` and `ForeignFunction`. */ +export var Library: { + /** The extension to use on libraries. */ + EXT: string; /** - * Represents a foreign function in another library. Manages all of the aspects - * of function execution, including marshalling the data parameters for the - * function into native types and also unmarshalling the return from function - * execution. + * @param libFile name of library + * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] + * @param lib hash that will be extended */ - export var ForeignFunction: { - new (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; - new (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; - (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; - (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; - } - - export interface VariadicForeignFunction { - /** - * What gets returned is another function that needs to be invoked with the rest - * of the variadic types that are being invoked from the function. - */ - (...args: any[]): ForeignFunction; - - /** - * Return type as a property of the function generator to - * allow for monkey patching the return value in the very rare case where the - * return type is variadic as well - */ - returnType: any; - } + new (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; /** - * For when you want to call to a C function with variable amount of arguments. - * i.e. `printf`. - * - * This function takes care of caching and reusing `ForeignFunction` instances that - * contain the same ffi_type argument signature. + * @param libFile name of library + * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] + * @param lib hash that will be extended */ - export var VariadicForeignFunction: { - new (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; - new (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; - (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; - (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; - }; + (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; +}; - export interface DynamicLibrary { - /** Close library, returns the result of the `dlclose` system function. */ - close(): number; - /** Get a symbol from this library. */ - get(symbol: string): Buffer; - /** Get the result of the `dlerror` system function. */ - error(): string; - } +/** Get value of errno. */ +export function errno(): number; - /** - * This class loads and fetches function pointers for dynamic libraries - * (.so, .dylib, etc). After the libray's function pointer is acquired, then you - * call `get(symbol)` to retreive a pointer to an exported symbol. You need to - * call `get___` on the pointer to dereference it into its actual value, or - * turn the pointer into a callable function with `ForeignFunction`. - */ - export var DynamicLibrary: { - FLAGS: { - RTLD_LAZY: number; - RTLD_NOW: number; - RTLD_LOCAL: number; - RTLD_GLOBAL: number; - RTLD_NOLOAD: number; - RTLD_NODELETE: number; - RTLD_NEXT: Buffer; - RTLD_DEFAUL: Buffer; - } +export interface Function extends ref.Type { + /** The type of return value. */ + retType: ref.Type; + /** The type of arguments. */ + argTypes: ref.Type[]; + /** Is set for node-ffi functions. */ + ffi_type: Buffer; + abi: number; - new (path?: string, mode?: number): DynamicLibrary; - (path?: string, mode?: number): DynamicLibrary; - }; - - /** - * Turns a JavaScript function into a C function pointer. - * The function pointer may be used in other C functions that - * accept C callback functions. - */ - export var Callback: { - new (retType: any, argTypes: any[], abi: number, fn: any): Buffer; - new (retType: any, argTypes: any[], fn: any): Buffer; - (retType: any, argTypes: any[], abi: number, fn: any): Buffer; - (retType: any, argTypes: any[], fn: any): Buffer; - } - - export var ffiType: { - /** Get a `ffi_type *` Buffer appropriate for the given type. */ - (type: ref.Type): Buffer - /** Get a `ffi_type *` Buffer appropriate for the given type. */ - (type: string): Buffer - FFI_TYPE: StructType; - } - - export var CIF: (retType: any, types: any[], abi?: any) => Buffer - export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => Buffer; - export var HAS_OBJC: boolean; - export var FFI_TYPES: {[key: string]: Buffer}; - export var FFI_OK: number; - export var FFI_BAD_TYPEDEF: number; - export var FFI_BAD_ABI: number; - export var FFI_DEFAULT_ABI: number; - export var FFI_FIRST_ABI: number; - export var FFI_LAST_ABI: number; - export var FFI_SYSV: number; - export var FFI_UNIX64: number; - export var RTLD_LAZY: number; - export var RTLD_NOW: number; - export var RTLD_LOCAL: number; - export var RTLD_GLOBAL: number; - export var RTLD_NOLOAD: number; - export var RTLD_NODELETE: number; - export var RTLD_NEXT: Buffer; - export var RTLD_DEFAULT: Buffer; - export var LIB_EXT: string; - export var FFI_TYPE: StructType; - - /** Default types. */ - export var types: { - void: ref.Type; int64: ref.Type; ushort: ref.Type; - int: ref.Type; uint64: ref.Type; float: ref.Type; - uint: ref.Type; long: ref.Type; double: ref.Type; - int8: ref.Type; ulong: ref.Type; Object: ref.Type; - uint8: ref.Type; longlong: ref.Type; CString: ref.Type; - int16: ref.Type; ulonglong: ref.Type; bool: ref.Type; - uint16: ref.Type; char: ref.Type; byte: ref.Type; - int32: ref.Type; uchar: ref.Type; size_t: ref.Type; - uint32: ref.Type; short: ref.Type; - }; + /** Get a `Callback` pointer of this function type. */ + toPointer(fn: (...args: any[]) => any): Buffer; + /** Get a `ForeignFunction` of this function type. */ + toFunction(buf: Buffer): ForeignFunction; } + +/** Creates and returns a type for a C function pointer. */ +export var Function: { + new (retType: ref.Type, argTypes: any[], abi?: number): Function; + new (retType: string, argTypes: any[], abi?: number): Function; + (retType: ref.Type, argTypes: any[], abi?: number): Function; + (retType: string, argTypes: any[], abi?: number): Function; +}; + +export interface ForeignFunction { + (...args: any[]): any; + async(...args: any[]): void; +} + +/** + * Represents a foreign function in another library. Manages all of the aspects + * of function execution, including marshalling the data parameters for the + * function into native types and also unmarshalling the return from function + * execution. + */ +export var ForeignFunction: { + new (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + new (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; + (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; +} + +export interface VariadicForeignFunction { + /** + * What gets returned is another function that needs to be invoked with the rest + * of the variadic types that are being invoked from the function. + */ + (...args: any[]): ForeignFunction; + + /** + * Return type as a property of the function generator to + * allow for monkey patching the return value in the very rare case where the + * return type is variadic as well + */ + returnType: any; +} + +/** + * For when you want to call to a C function with variable amount of arguments. + * i.e. `printf`. + * + * This function takes care of caching and reusing `ForeignFunction` instances that + * contain the same ffi_type argument signature. + */ +export var VariadicForeignFunction: { + new (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + new (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; +}; + +export interface DynamicLibrary { + /** Close library, returns the result of the `dlclose` system function. */ + close(): number; + /** Get a symbol from this library. */ + get(symbol: string): Buffer; + /** Get the result of the `dlerror` system function. */ + error(): string; +} + +/** + * This class loads and fetches function pointers for dynamic libraries + * (.so, .dylib, etc). After the libray's function pointer is acquired, then you + * call `get(symbol)` to retreive a pointer to an exported symbol. You need to + * call `get___` on the pointer to dereference it into its actual value, or + * turn the pointer into a callable function with `ForeignFunction`. + */ +export var DynamicLibrary: { + FLAGS: { + RTLD_LAZY: number; + RTLD_NOW: number; + RTLD_LOCAL: number; + RTLD_GLOBAL: number; + RTLD_NOLOAD: number; + RTLD_NODELETE: number; + RTLD_NEXT: Buffer; + RTLD_DEFAUL: Buffer; + } + + new (path?: string, mode?: number): DynamicLibrary; + (path?: string, mode?: number): DynamicLibrary; +}; + +/** + * Turns a JavaScript function into a C function pointer. + * The function pointer may be used in other C functions that + * accept C callback functions. + */ +export var Callback: { + new (retType: any, argTypes: any[], abi: number, fn: any): Buffer; + new (retType: any, argTypes: any[], fn: any): Buffer; + (retType: any, argTypes: any[], abi: number, fn: any): Buffer; + (retType: any, argTypes: any[], fn: any): Buffer; +} + +export var ffiType: { + /** Get a `ffi_type *` Buffer appropriate for the given type. */ + (type: ref.Type): Buffer + /** Get a `ffi_type *` Buffer appropriate for the given type. */ + (type: string): Buffer + FFI_TYPE: StructType; +} + +export var CIF: (retType: any, types: any[], abi?: any) => Buffer +export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => Buffer; +export var HAS_OBJC: boolean; +export var FFI_TYPES: {[key: string]: Buffer}; +export var FFI_OK: number; +export var FFI_BAD_TYPEDEF: number; +export var FFI_BAD_ABI: number; +export var FFI_DEFAULT_ABI: number; +export var FFI_FIRST_ABI: number; +export var FFI_LAST_ABI: number; +export var FFI_SYSV: number; +export var FFI_UNIX64: number; +export var RTLD_LAZY: number; +export var RTLD_NOW: number; +export var RTLD_LOCAL: number; +export var RTLD_GLOBAL: number; +export var RTLD_NOLOAD: number; +export var RTLD_NODELETE: number; +export var RTLD_NEXT: Buffer; +export var RTLD_DEFAULT: Buffer; +export var LIB_EXT: string; +export var FFI_TYPE: StructType; + +/** Default types. */ +export var types: { + void: ref.Type; int64: ref.Type; ushort: ref.Type; + int: ref.Type; uint64: ref.Type; float: ref.Type; + uint: ref.Type; long: ref.Type; double: ref.Type; + int8: ref.Type; ulong: ref.Type; Object: ref.Type; + uint8: ref.Type; longlong: ref.Type; CString: ref.Type; + int16: ref.Type; ulonglong: ref.Type; bool: ref.Type; + uint16: ref.Type; char: ref.Type; byte: ref.Type; + int32: ref.Type; uchar: ref.Type; size_t: ref.Type; + uint32: ref.Type; short: ref.Type; +}; + diff --git a/file-url/file-url-tests.ts b/file-url/file-url-tests.ts index 9fc9cded68..e47cd737cb 100644 --- a/file-url/file-url-tests.ts +++ b/file-url/file-url-tests.ts @@ -1,3 +1,4 @@ +import fileUrl = require("file-url"); // Copied from https://github.com/sindresorhus/file-url/blob/14c7a69ae3798f50b3a4a21823c86e10b38160fe/readme.md diff --git a/file-url/index.d.ts b/file-url/index.d.ts index d0c0dd02c9..1df68f6dbc 100644 --- a/file-url/index.d.ts +++ b/file-url/index.d.ts @@ -11,6 +11,4 @@ declare function fileUrl(path:string):string; /** * Convert a path to a file URL. */ -declare module "file-url" { - export = fileUrl; -} +export = fileUrl; diff --git a/filesize/index.d.ts b/filesize/index.d.ts index 2ac4de6e05..374db62ec8 100644 --- a/filesize/index.d.ts +++ b/filesize/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var fileSize: Filesize.IFilesize; +export = fileSize; +export as namespace filesize; + declare namespace Filesize { export interface SiJedecBits { @@ -76,9 +80,3 @@ declare namespace Filesize { (bytes: number, options: Options): string; } } - - -declare module "filesize" { - let fileSize: Filesize.IFilesize; - export = fileSize; -} diff --git a/first-mate/index.d.ts b/first-mate/index.d.ts index b72be53818..e46811aa85 100644 --- a/first-mate/index.d.ts +++ b/first-mate/index.d.ts @@ -5,6 +5,9 @@ /// +import * as AtomEventKit from "event-kit"; +export = AtomFirstMate; + declare namespace AtomFirstMate { type Disposable = AtomEventKit.Disposable; @@ -101,8 +104,4 @@ declare namespace AtomFirstMate { /** Registry containing one or more grammars. */ var GrammarRegistry: GrammarRegistryStatic; -} - -declare module 'first-mate' { - export = AtomFirstMate; -} +} \ No newline at end of file diff --git a/fixed-data-table/index.d.ts b/fixed-data-table/index.d.ts index 762b09d103..4df367d669 100644 --- a/fixed-data-table/index.d.ts +++ b/fixed-data-table/index.d.ts @@ -5,6 +5,9 @@ /// +export = FixedDataTable; +export as namespace FixedDataTable; + declare namespace FixedDataTable { export var version: string; @@ -491,7 +494,3 @@ declare namespace FixedDataTable { export class Cell extends React.Component { } } - -declare module "fixed-data-table" { - export = FixedDataTable; -} diff --git a/flat/index.d.ts b/flat/index.d.ts index 454b3f0cde..1b0d8e9ef2 100644 --- a/flat/index.d.ts +++ b/flat/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Ilya Mochalov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var flatten: FlatTypes.Flatten; + +export = flatten; + declare namespace FlatTypes { interface FlattenOptions { delimiter?: string; @@ -33,9 +37,3 @@ declare namespace FlatTypes { ): TResult; } } - -declare module "flat" { - var flatten: FlatTypes.Flatten; - - export = flatten; -} diff --git a/fromnow/index.d.ts b/fromnow/index.d.ts index d2b90891ec..86c1610f9b 100644 --- a/fromnow/index.d.ts +++ b/fromnow/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Martin Bukovics // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var FromNow: FromNow.FromNowStatic; +export = FromNow; +export as namespace fromNow; + declare namespace FromNow { interface FromNowOpts { maxChunks?: number, @@ -21,8 +25,3 @@ declare namespace FromNow { (date: string|Date, opts?: FromNowOpts): string } } - -declare module 'fromnow' { - var FromNow: FromNow.FromNowStatic; - export = FromNow; -} diff --git a/fs-finder/fs-finder-tests.ts b/fs-finder/fs-finder-tests.ts index 2fb75bf022..8a0afe4243 100644 --- a/fs-finder/fs-finder-tests.ts +++ b/fs-finder/fs-finder-tests.ts @@ -4,23 +4,23 @@ import finder = require('fs-finder'); // static -var a: FsFinder.Finder = finder.in('./*'); +var a = finder.in('./*'); -var b: FsFinder.Finder = finder.from('./*'); +var b = finder.from('./*'); -var c: FsFinder.Finder = finder.find('./*'); +var c = finder.find('./*'); finder.find('./*', (paths: string[]) => {}); -var d: FsFinder.Finder = finder.findFiles('./*'); +var d = finder.findFiles('./*'); finder.findFiles('./*', (paths: string[]) => {}); -var e: FsFinder.Finder = finder.findDirectories('./*'); +var e = finder.findDirectories('./*'); finder.findDirectories('./*', (paths: string[]) => {}); -var f: FsFinder.Finder = finder.findFile('./*'); +var f = finder.findFile('./*'); finder.findFile('./*', (paths: string[]) => {}); -var g: FsFinder.Finder = finder.findDirectory('./*'); +var g = finder.findDirectory('./*'); finder.findDirectory('./*', (paths: string[]) => {}); diff --git a/fs-finder/index.d.ts b/fs-finder/index.d.ts index 368179146c..28073d06ba 100644 --- a/fs-finder/index.d.ts +++ b/fs-finder/index.d.ts @@ -49,7 +49,5 @@ declare namespace FsFinder { } } -declare module "fs-finder" { - import Finder = FsFinder.Finder; - export = Finder; -} +import Finder = FsFinder.Finder; +export = Finder; diff --git a/go/goJS-tests.ts b/go/goJS-tests.ts index 294d61da08..8992e506f2 100644 --- a/go/goJS-tests.ts +++ b/go/goJS-tests.ts @@ -3,7 +3,7 @@ /* Copyright (C) 1998-2016 by Northwoods Software Corporation. */ - +import go = require("go"); class CustomLink extends go.Link { constructor() { diff --git a/go/index.d.ts b/go/index.d.ts index f37c6bf466..cb9918ff1f 100644 --- a/go/index.d.ts +++ b/go/index.d.ts @@ -9458,6 +9458,5 @@ declare namespace go { } } //END go -declare module "go" { - export = go; -} +export = go; +export as namespace go; diff --git a/google-apps-script/index.d.ts b/google-apps-script/index.d.ts new file mode 100644 index 0000000000..9f60a23b2a --- /dev/null +++ b/google-apps-script/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for google-apps-script + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// reference path="google-apps-script.maps.d.ts"/> +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + diff --git a/google-maps/index.d.ts b/google-maps/index.d.ts index c6649f8d17..f5c28f1581 100644 --- a/google-maps/index.d.ts +++ b/google-maps/index.d.ts @@ -21,6 +21,5 @@ declare namespace GoogleMapsLoader { export function isLoaded(): boolean; } -declare module 'google-maps' { - export = GoogleMapsLoader; -} +export = GoogleMapsLoader; +export as namespace GoogleMapsLoader; diff --git a/graham_scan/graham_scan-tests.ts b/graham_scan/graham_scan-tests.ts index 40b7f9b6d1..15c114aefe 100644 --- a/graham_scan/graham_scan-tests.ts +++ b/graham_scan/graham_scan-tests.ts @@ -1,4 +1,4 @@ - +import ConvexHullGrahamScan = require("graham_scan"); // Based on the README.MD diff --git a/graham_scan/index.d.ts b/graham_scan/index.d.ts index dbc30517b2..ac3bdfc9ad 100644 --- a/graham_scan/index.d.ts +++ b/graham_scan/index.d.ts @@ -7,6 +7,5 @@ declare class ConvexHullGrahamScan { getHull(): {x: number, y: number}[]; } -declare module 'graham_scan' { - export = ConvexHullGrahamScan; -} +export = ConvexHullGrahamScan; +export as namespace ConvexHullGrahamScan; diff --git a/gravatar/index.d.ts b/gravatar/index.d.ts index d5685e3717..5c2c113ab8 100644 --- a/gravatar/index.d.ts +++ b/gravatar/index.d.ts @@ -18,6 +18,4 @@ declare namespace GravatarModule { function url(email: string, options?: Options, forceProtocol?: boolean): string; } -declare module "gravatar" { - export = GravatarModule; -} +export = GravatarModule; diff --git a/gridfs-stream/index.d.ts b/gridfs-stream/index.d.ts index e75c2c10e7..1c803348ad 100644 --- a/gridfs-stream/index.d.ts +++ b/gridfs-stream/index.d.ts @@ -39,31 +39,31 @@ declare namespace GridFSStream { } } -declare module "gridfs-stream" { - import mongo = require('mongodb'); - // Merged declaration, g is both a callable function and a namespace - function g(db: any, mongo: any): g.Grid; +import mongo = require('mongodb'); - namespace g { +// Merged declaration, g is both a callable function and a namespace +declare function g(db: any, mongo: any): g.Grid; - export class Grid { +declare namespace g { - files: mongo.Collection; - collection(name?: string): mongo.Collection; - curCol: string; + export class Grid { - createWriteStream(options?: GridFSStream.Options): GridFSStream.WriteStream; - createReadStream(options?: GridFSStream.Options): GridFSStream.ReadStream; - createWriteStream(options?: string): GridFSStream.WriteStream; - createReadStream(options?: string): GridFSStream.ReadStream; + files: mongo.Collection; + collection(name?: string): mongo.Collection; + curCol: string; - remove(options: GridFSStream.Options, callback: (err: Error) => void): void; - exist(options: GridFSStream.Options, callback: (err: Error, found: boolean) => void): void; - findOne(options: GridFSStream.Options, callback: (err: Error, record: any)=>void):void; - } + createWriteStream(options?: GridFSStream.Options): GridFSStream.WriteStream; + createReadStream(options?: GridFSStream.Options): GridFSStream.ReadStream; + createWriteStream(options?: string): GridFSStream.WriteStream; + createReadStream(options?: string): GridFSStream.ReadStream; + + remove(options: GridFSStream.Options, callback: (err: Error) => void): void; + exist(options: GridFSStream.Options, callback: (err: Error, found: boolean) => void): void; + findOne(options: GridFSStream.Options, callback: (err: Error, record: any)=>void):void; } - - export = g; } +export = g; + + diff --git a/hapi/index.d.ts b/hapi/index.d.ts index b5582c1f4e..c95db3380d 100644 --- a/hapi/index.d.ts +++ b/hapi/index.d.ts @@ -8,223 +8,2410 @@ /// -declare module "hapi" { - import http = require("http"); - import stream = require("stream"); - import Events = require("events"); - import url = require("url"); +import http = require("http"); +import stream = require("stream"); +import Events = require("events"); +import url = require("url"); - interface IDictionary { - [key: string]: T; - } +interface IDictionary { + [key: string]: T; +} - interface IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IThenable; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IThenable; - } +interface IThenable { + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IThenable; + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IThenable; +} - interface IPromise extends IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IPromise; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IPromise; - catch(onRejected?: (error: any) => U | IThenable): IPromise; - } +interface IPromise extends IThenable { + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IPromise; + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IPromise; + catch(onRejected?: (error: any) => U | IThenable): IPromise; +} - export interface IHeaderOptions { - append?: boolean; - separator?: string; - override?: boolean; - duplicate?: boolean; - } +export interface IHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} - /** Boom Module for errors. https://github.com/hapijs/boom - * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ - export interface IBoom extends Error { - /** if true, indicates this is a Boom object instance. */ - isBoom: boolean; - /** convenience bool indicating status code >= 500. */ - isServer: boolean; - /** the error message. */ - message: string; - /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ - output: { - /** the HTTP status code (typically 4xx or 5xx). */ +/** Boom Module for errors. https://github.com/hapijs/boom + * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ +export interface IBoom extends Error { + /** if true, indicates this is a Boom object instance. */ + isBoom: boolean; + /** convenience bool indicating status code >= 500. */ + isServer: boolean; + /** the error message. */ + message: string; + /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ + output: { + /** the HTTP status code (typically 4xx or 5xx). */ + statusCode: number; + /** an object containing any HTTP headers where each key is a header name and value is the header content. */ + headers: IDictionary; + /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ + payload: { + /** the HTTP status code, derived from error.output.statusCode. */ statusCode: number; - /** an object containing any HTTP headers where each key is a header name and value is the header content. */ - headers: IDictionary; - /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ - payload: { - /** the HTTP status code, derived from error.output.statusCode. */ - statusCode: number; - /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ - error: string; - /** the error message derived from error.message. */ - message: string; - }; + /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ + error: string; + /** the error message derived from error.message. */ + message: string; }; - /** reformat()rebuilds error.output using the other object properties. */ - reformat(): void; + }; + /** reformat()rebuilds error.output using the other object properties. */ + reformat(): void; - } +} - /** cache functionality via the "CatBox" module. */ - export interface ICatBoxCacheOptions { - /** a prototype function or catbox engine object. */ - engine: any; - /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ - name?: string; - /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ - shared?: boolean; - } +/** cache functionality via the "CatBox" module. */ +export interface ICatBoxCacheOptions { + /** a prototype function or catbox engine object. */ + engine: any; + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ + name?: string; + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; +} - /** Any connections configuration server defaults can be included to override and customize the individual connection. */ - export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { - /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ - host?: string; - /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ - address?: string; - /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ - port?: string | number; - /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ - uri?: string; - /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ - listener?: any; - /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ - autoListen?: boolean; - /** caching headers configuration: */ - cache?: { - /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ - statuses: number[]; +/** Any connections configuration server defaults can be included to override and customize the individual connection. */ +export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ + host?: string; + /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ + address?: string; + /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ + port?: string | number; + /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ + uri?: string; + /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ + listener?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ + statuses: number[]; + }; + /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ + labels?: string | string[]; + /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; + +} + +export interface IConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: IRouteAdditionalConfigurationOptions; + state?: IServerState; +} + +/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ +export interface IServerOptions { + /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). + a configuration object with the following options: + enginea prototype function or catbox engine object. + namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. + sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + other options passed to the catbox strategy used. + an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ + cache?: string | ICatBoxCacheOptions | Array | any; + /** sets the default connections configuration which can be overridden by each connection where: */ + connections?: IConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ + debug?: boolean | { + /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log: string[]; + /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ + request: string[]; + }; + /** file system related settings*/ + files?: { + /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ + etagsCacheMaxSize?: number; + }; + /** process load monitoring*/ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ + sampleInterval?: number; + }; + + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ + mime?: any; + /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ + minimal?: boolean; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ + plugins?: IDictionary; + +} + +export interface IServerViewCompile { + (template: string, options: any): void; + (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; +} + +export interface IServerViewsAdditionalOptions { + /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ + path?: string; + /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + */ + partialsPath?: string; + /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ + helpersPath?: string; + /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ + relativeTo?: string; + + /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ + layout?: boolean | string; + /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ + layoutPath?: string; + /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ + layoutKeywork?: string; + /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ + encoding?: string; + /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ + isCached?: boolean; + /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ + allowAbsolutePaths?: boolean; + /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ + allowInsecureAccess?: boolean; + /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ + compileOptions?: any; + /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ + runtimeOptions?: any; + /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ + contentType?: string; + /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ + compileMode?: string; + /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ + context?: any; +} + +export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { + /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. + * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ + module: { + compile?(template: any, options: any): (context: any, options: any) => void; + compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + }; +} + +/**Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + + server.views({ +engines: { +html: require('handlebars'), +jade: require('jade') +}, +path: '/static/templates' +}); + When server.views() is called within a plugin, the views manager is only available to plugins methods. + */ +export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { + /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ + engines: IDictionary | IServerViewsEnginesOptions; + /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ + defaultExtension?: string; +} + +/** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ +export interface IReply { + (err: Error, + result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; + + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + * The data argument is only used for passing back authentication data and is ignored elsewhere. */ + continue(credentialData?: any): void; + + /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ + file(/** the file path. */ + path: string, + /** optional settings: */ + options?: { + /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /** specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed: boolean; + }): void; + /** Concludes the handler activity by returning control over to the router with a templatized view response. + the response flow control rules apply. */ + view(/** the template filename and path, relative to the templates path configured via the server views manager. */ + template: string, + /** optional object used by the template to render context-specific result. Defaults to no context {}. */ + context?: {}, + /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ + options?: any): Response; + /** Sets a header on the response */ + header(name: string, value: string, options?: IHeaderOptions): Response; + + /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed + The response flow control rules do not apply. */ + close(options?: { + /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ + end?: boolean; + }): void; + /** Proxies the request to an upstream endpoint. + the response flow control rules do not apply. */ + + proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ + options: IProxyHandlerConfig): void; + /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). + he response flow control rules apply. */ + redirect(uri: string): ResponseRedirect; + + /** Replies with the specified response */ + response(result: any): Response; + + /** Sets a cookie on the response */ + state(name: string, value: any, options?: any): void; + + /** Clears a cookie on the response */ + unstate(name: string, options?: any): void; +} + +export interface ISessionHandler { + (request: Request, reply: IReply): void; +} +export interface IRequestHandler { + (request: Request): T; +} + + +export interface IFailAction { + (source: string, error: any, next: () => void): void +} +/** generates a reverse proxy handler */ +export interface IProxyHandlerConfig { + /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ + host?: string; + /** the upstream service port. */ + port?: number; + /** The protocol to use when making a request to the proxied host: + 'http' + 'https'*/ + protocol?: string; + /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ + uri?: string; + /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ + passThrough?: boolean; + /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ + localStatePassThrough?: boolean; + /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ + rejectUnauthorized?: boolean; + /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ + xforward?: boolean; + /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ + redirects?: boolean | number; + /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ + timeout?: number; + /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: + request - is the incoming request object. + callback - is function(err, uri, headers) where: + err - internal error condition. + uri - the absolute proxy URI. + headers - optional object where each key is an HTTP request header and the value is the header content.*/ + mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; + /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ + onResponse?: (err: any, + res: http.ServerResponse, + req: Request, + reply: IReply, + settings: IProxyHandlerConfig, + ttl: number) => void; + /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ + ttl?: number; + /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ + agent?: http.Agent; + /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ + maxSockets?: boolean | number; +} +/** TODO: fill in joi definition */ +export interface IJoi { + +} +/** a validation function using the signature function(value, options, next) */ +export interface IValidationFunction { + + (/** the object containing the path parameters. */ + value: any, + /** the server validation options. */ + options: any, + /** the callback function called when validation is completed. */ + next: (err: any, value: any) => void): void; +} +/** a custom error handler function with the signature 'function(request, reply, source, error)` */ +export interface IRouteFailFunction { + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + (/** - the [request object]. */ + request: Request, + /** the continuation reply interface. */ + reply: IReply, + /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ + source: string, + /** the error object prepared for the client response (including the validation function error under error.data). */ + error: any): void; +} + +/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ +export interface IRouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. + a string with the name of an authentication strategy registered with server.auth.strategy(). + an object */ + auth?: boolean | string | + { + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + 'required'authentication is required. + 'optional'authentication is optional (must be valid if present). + 'try'same as 'optional' but allows for invalid authentication. */ + mode?: string; + /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies?: string | Array; + /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: + falseno payload authentication.This is the default value. + 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. + 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ + payload?: string; + /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ + scope?: string | Array | boolean; + /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: + anythe authentication can be on behalf of a user or application.This is the default value. + userthe authentication must be on behalf of a user. + appthe authentication must be on behalf of an application. */ + entity?: string; + /** + * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming + * request and access is granted if at least one rule matches. Each rule object must include at least one of: + */ + access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; }; - /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ - labels?: string | string[]; - /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; + /** an object passed back to the provided handler (via this) when called. */ + bind?: any; + /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ + cache?: { + /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: + fault'no privacy flag.This is the default setting. + 'public'mark the response as suitable for public caching. + 'private'mark the response as suitable only for private caching. */ + privacy: string; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ + expiresIn: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ + expiresAt: string; + }; + /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ + cors?: { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ + origin?: Array; + /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ + matchOrigin?: boolean; + /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ + isOriginExposed?: boolean; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ + headers?: string[]; + /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ + methods?: string[]; + /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ + additionalMethods?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ + credentials?: boolean; + /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ + override?: boolean; + }; + /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ + files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ + relativeTo: string; + }; - } - - export interface IConnectionConfigurationServerDefaults { - /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ - app?: any; - /** connection load limits configuration where: */ - load?: { - /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxHeapUsedBytes: number; - /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxRssBytes: number; - /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxEventLoopDelay: number; + /** an alternative location for the route handler option. */ + handler?: ISessionHandler | string | IRouteHandlerConfig; + /** an optional unique identifier used to look up the route using server.lookup(). */ + id?: number; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ + json?: { + /** the replacer function or array.Defaults to no action. */ + replacer?: Function | string[]; + /** number of spaces to indent nested object keys.Defaults to no indentation. */ + space?: number | string; + /** string suffix added after conversion to JSON string.Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ + jsonp?: string; + /** determines how the request payload is processed: */ + payload?: { + /** the type of payload representation requested. The value must be one of: + 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. + 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ + output?: string; + /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + 'application/json' + 'application/x-www-form-urlencoded' + 'application/octet-stream' + 'text/ *' + 'multipart/form-data' */ + parse?: string | boolean; + /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ + uploads?: string; + /** determines how to handle payload parsing errors. Allowed values are: + 'error'return a Bad Request (400) error response. This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action and continue processing the request. */ + failAction?: string; + }; + /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: IDictionary; + /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ + pre?: any[]; + /** validation rules for the outgoing response payload (response body).Can only validate object response: */ + response?: { + /** the default HTTP status code when the payload is empty. Value can be 200 or 204. + Note that a 200 status code is converted to a 204 only at the time or response transmission + (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ + emptyStatusCode?: number; + /** the default response object validation rules (for all non-error responses) expressed as one of: + true - any payload allowed (no validation performed). This is the default. + false - no payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + value - the object containing the response object. + options - the server validation options. + next(err) - the callback function called when validation is completed. */ + schema?: boolean | any; + /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ + status?: { [statusCode: number]: boolean | any }; + /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ + sample?: number; + /** defines what to do when a response fails validation.Options are: + errorreturn an Internal Server Error (500) error response.This is the default value. + loglog the error but send the response. */ + failAction?: string; + /** if true, applies the validation rule changes to the response.Defaults to false. */ + modify?: boolean; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ + security?: boolean | { + /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ + hsts?: boolean | number | { + /** the max- age portion of the header, as a number.Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubdomains flag to the header. */ + includeSubdomains?: boolean; + /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ + preload?: boolean; }; - /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ - plugins?: any; - /** controls how incoming request URIs are matched against the routing table: */ - router?: { - /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ - isCaseSensitive: boolean; - /** removes trailing slashes on incoming paths. Defaults to false. */ - stripTrailingSlash: boolean; + /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe?: { + /** either 'deny', 'sameorigin', or 'allow-from' */ + rule: string; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; }; - /** a route options object used to set the default configuration for every route. */ - routes?: IRouteAdditionalConfigurationOptions; - state?: IServerState; - } - - /** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ - export interface IServerOptions { - /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: any; - /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: - a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). - a configuration object with the following options: - enginea prototype function or catbox engine object. - namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. - sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - other options passed to the catbox strategy used. - an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ - cache?: string | ICatBoxCacheOptions | Array | any; - /** sets the default connections configuration which can be overridden by each connection where: */ - connections?: IConnectionConfigurationServerDefaults; - /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ - debug?: boolean | { - /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ - log: string[]; - /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ - request: string[]; - }; - /** file system related settings*/ - files?: { - /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ - etagsCacheMaxSize?: number; - }; - /** process load monitoring*/ - load?: { - /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ - sampleInterval?: number; - }; - - /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ - mime?: any; - /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ - minimal?: boolean; - /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ - plugins?: IDictionary; - - } - - export interface IServerViewCompile { - (template: string, options: any): void; - (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; - } - - export interface IServerViewsAdditionalOptions { - /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ - path?: string; - /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ + xss?: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ + noOpen?: boolean; + /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ + noSniff?: boolean; + }; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ + parse: boolean; + /** determines how to handle cookie parsing errors.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action. */ + failAction: string; + }; + /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ + validate?: { + /** validation rules for incoming request headers.Values allowed: + * trueany headers allowed (no validation performed).This is the default. + falseno headers allowed (this will cause all valid HTTP requests to fail). + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the request headers. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ - partialsPath?: string; - /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ - helpersPath?: string; - /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ - relativeTo?: string; + headers?: boolean | IJoi | IValidationFunction; - /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ - layout?: boolean | string; - /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ - layoutPath?: string; - /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ - layoutKeywork?: string; - /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ - encoding?: string; - /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ - isCached?: boolean; - /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ - allowAbsolutePaths?: boolean; - /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ - allowInsecureAccess?: boolean; - /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ - compileOptions?: any; - /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ - runtimeOptions?: any; - /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ - contentType?: string; - /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ - compileMode?: string; - /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ - context?: any; - } - export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { - /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. - * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ - module: { - compile?(template: any, options: any): (context: any, options: any) => void; - compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: + trueany path parameters allowed (no validation performed).This is the default. + falseno path variables allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the path parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + params?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: + trueany query parameters allowed (no validation performed).This is the default. + falseno query parameters allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the query parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + query?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request payload (request body).Values allowed: + trueany payload allowed (no validation performed).This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the payload object. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + payload?: boolean | IJoi | IValidationFunction; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** determines how to handle invalid requests.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'log the error but continue processing the request. + 'ignore'take no action. + OR a custom error handler function with the signature 'function(request, reply, source, error)` where: + requestthe request object. + replythe continuation reply interface. + sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). + errorthe error object prepared for the client response (including the validation function error under error.data). */ + failAction?: string | IRouteFailFunction; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ + server: boolean | number; + /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ + socket: boolean | number; + }; + + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route description used for generating documentation (string). + */ + description?: string; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route notes used for generating documentation (string or array of strings). + */ + notes?: string | string[]; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route tags used for generating documentation (array of strings). + */ + tags?: string[] +} + +/** + * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches + */ +export interface IRouteAdditionalConfigurationAuthAccess { + /** + * the application scope required to access the route. Value can be a scope string or an array of scope strings. + * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, + * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' + * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties + * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, + * such as 'user-{params.id}'. Defaults to false (no scope requirements). + */ + scope?: string | Array | boolean; + /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: + * any - the authentication can be on behalf of a user or application. This is the default value. + * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. + * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + */ + entity?: string; +} + +/** server.realm http://hapijs.com/api#serverrealm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { +console.log(server.realm.modifiers.route.prefix); +return next(); +}; + */ +export interface IServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ + modifiers: { + /** routes preferences: */ + route: { + /** - the route path prefix used by any calls to server.route() from the server. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; }; - } - /**Initializes the server views manager + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: IDictionary; + /** settings overrides */ + settings: { + files: { + relativeTo: any; + }; + bind: any; + } +} +/** server.state(name, [options]) http://hapijs.com/api#serverstatename-options + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ +export interface IServerState { + /** - the cookie name string. */name: string; + + /** - are the optional cookie settings: */options: { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; + /** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean + /** - the path scope.Defaults to null (no path).*/path: any; + /** - the domain scope.Defaults to null (no domain). */domain: any; + /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization. Options are: + 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON-stringified than encoded using Base64. + 'form' - object value is encoded using the x-www-form-urlencoded method. + 'iron' - Encrypts and sign the value using iron.*/ + encoding: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { + /** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; + /** - password used for HMAC key generation.*/password: string; + }; + /** - password used for 'iron' encoding.*/password: string; + /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; + /** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; + /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; + /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; + /** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; + }; +} + +export interface IFileHandlerConfig { + /** a path string or function as described above.*/ + path: string; + /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ + lookupCompressed: boolean; +} + +/**http://hapijs.com/api#route-handler + Built-in handlers + + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ +export interface IRouteHandlerConfig { + /** generates a static file endpoint for serving a single file. file can be set to: + a relative or absolute file path string (relative paths are resolved based on the route files configuration). + a function with the signature function(request) which returns the relative or absolute file path. + an object with the following options */ + file?: string | IRequestHandler | IFileHandlerConfig; + /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. + listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. + defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ + directory?: { + path: string | Array | IRequestHandler | IRequestHandler>; + index?: boolean | string | string[]; + listing?: boolean; + showHidden?: boolean; + redirectToSlash?: boolean; + lookupCompressed?: boolean; + defaultExtension?: string; + }; + proxy?: IProxyHandlerConfig; + view?: string | { + template: string; + context: { + payload: any; + params: any; + query: any; + pre: any; + } + }; + config?: { + handler: any; + bind: any; + app: any; + plugins: { + [name: string]: any; + }; + pre: Array<() => void>; + validate: { + headers: any; + params: any; + query: any; + payload: any; + errorFields?: any; + failAction?: string | IFailAction; + }; + payload: { + output: { + data: any; + stream: any; + file: any; + }; + parse?: any; + allow?: string | Array; + override?: string; + maxBytes?: number; + uploads?: number; + failAction?: string; + }; + response: { + schema: any; + sample: number; + failAction: string; + }; + cache: { + privacy: string; + expiresIn: number; + expiresAt: number; + }; + auth: string | boolean | { + mode: string; + strategies: Array; + payload?: boolean | string; + tos?: boolean | string; + scope?: string | Array; + entity: string; + }; + cors?: boolean; + jsonp?: string; + description?: string; + notes?: string | Array; + tags?: Array; + }; +} +/** Route configuration + The route configuration object*/ +export interface IRouteConfiguration { + /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ + path: string; + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ + method: string | string[]; + /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ + vhost?: string; + /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ + handler: ISessionHandler | string | IRouteHandlerConfig; + /** - additional route options.*/ + config?: IRouteAdditionalConfigurationOptions; +} +/** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ +export interface IRoute { + + + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | Array; + /** the [active realm] associated with the route.*/ + realm: IServerRealm; + /** the [route options] object with all defaults applied. */ + settings: IRouteAdditionalConfigurationOptions; +} + +export interface IServerAuthScheme { + /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: + request - the request object. + reply - the reply interface the authentication method must call when done authenticating the request where: + reply(err, response, result) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + result - an object containing: + credentials - the authenticated credentials. + artifacts - optional authentication artifacts. + reply.continue(result) - is called if authentication succeeded where: + result - same object as result above. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var scheme = function (server, options) { + return { + authenticate: function (request, reply) { + var req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply(null, { credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme);*/ + authenticate(request: Request, reply: IReply): void; + /** payload(request, reply) - optional function called to authenticate the request payload where: + request - the request object. + reply(err, response) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + reply.continue() - is called if payload authentication succeeded. + When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ + payload?(request: Request, reply: IReply): void; + /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: + request - the request object. + reply(err, response) - is called if an error occurred where: + err - any authentication error. + response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + reply.continue() - is called if the operation succeeded.*/ + response?(request: Request, reply: IReply): void; + /** an optional object */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ + payload: boolean; + } +} + +/**the response object where: + statusCode - the HTTP status code. + headers - an object containing the headers set. + payload - the response payload string. + rawPayload - the raw response payload buffer. + raw - an object with the injection request and response objects: + req - the simulated node request object. + res - the simulated node response object. + result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + request - the request object.*/ +export interface IServerInjectResponse { + statusCode: number; + headers: IDictionary; + payload: string; + rawPayload: Buffer; + raw: { + req: http.ClientRequest; + res: http.ServerResponse + }; + result: string; + request: Request; +} + +export interface IServerInject { + (options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void; + (options: string | IServerInjectOptions): IPromise; +} + +export interface IServerInjectOptions { + /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ + method: string; + /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ + url: string; + /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ + headers?: IDictionary; + /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ + payload?: string | {} | Buffer; + /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ + credentials?: any; + /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ + artifacts?: any; + /** sets the initial value of request.app*/ + app?: any; + /** sets the initial value of request.plugins*/ + plugins?: any; + /** allows access to routes with config.isInternal set to true. Defaults to false.*/ + allowInternals?: boolean; + /** sets the remote address for the incoming connection.*/ + remoteAddress?: boolean; + /**object with options used to simulate client request stream conditions for testing: + error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + end - if false, does not end the stream. Defaults to true.*/ + simulate?: { + error: boolean; + close: boolean; + end: boolean; + }; +} + + +/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path.*/ +export interface IConnectionTable { + info: any; + labels: any; + table: IRoute[]; +} + +export interface ICookieSettings { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl?: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure?: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly?: boolean; + /** - the path scope.Defaults to null (no path).*/ + path?: string; + /** - the domain scope.Defaults to null (no domain).*/ + domain?: any; + /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue?: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization.Options are: + 'none' - no encoding.When used, the cookie value must be a string.This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON- stringified than encoded using Base64. + 'form' - object value is encoded using the x- www - form - urlencoded method. */ + encoding?: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: + integrity - algorithm options.Defaults to require('iron').defaults.integrity. + password - password used for HMAC key generation. */ + sign?: { integrity: any; password: string; } + password?: string; + iron?: any; + ignoreErrors?: boolean; + clearInvalid?: boolean; + strictHeader?: boolean; + passThrough?: any; +} + +/** method - the method function with the signature is one of: + function(arg1, arg2, ..., argn, next) where: + arg1, arg2, etc. - the method function arguments. + next - the function called when the method is done with the signature function(err, result, ttl) where: + err - error response if the method failed. + result - the return value. + ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + function(arg1, arg2, ..., argn) where: + arg1, arg2, etc. - the method function arguments. + the callback option is set to false. + the method must returns a value (result, Error, or a promise) or throw an Error.*/ +export interface IServerMethod { + //(): void; + //(next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any): void; + //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any, arg2: any): void; + (...args: any[]): void; + +} +/** options - optional configuration: + bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. + cache - the same cache configuration used in server.cache(). + callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ +export interface IServerMethodOptions { + bind?: any; + cache?: ICatBoxCacheOptions; + callback?: boolean; + generateKey?(args: any[]): string; +} +/** Request object + + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + Request events + + The request object supports the following events: + + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the request payload finished reading. The event method signature is function (). + 'disconnect' - emitted when a request errors or aborts unexpectedly. + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + +var hash = Crypto.createHash('sha1'); +request.on('peek', function (chunk) { + +hash.update(chunk); +}); + +request.once('finish', function () { + +console.log(hash.digest('hex')); +}); + +request.once('disconnect', function () { + +console.error('request aborted'); +}); + +return reply.continue(); +});*/ +export class Request extends Events.EventEmitter { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** authentication information*/ + auth: { + /** true is the request has been successfully authenticated, otherwise false.*/ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ + artifacts: any; + /** the route authentication mode.*/ + mode: any; + /** the authentication error is failed and mode set to 'try'.*/ + error: any; + }; + /** the connection used by this request*/ + connection: ServerConnection; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ + domain: any; + /** the raw request headers (references request.raw.headers).*/ + headers: IDictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: number; + /** request information */ + info: { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com').*/ + hostname: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: number; + /** request response timestamp (0 is not responded yet). */ + responded: number; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ + params: IDictionary; + /** an array containing all the path params values in the order they appeared in the path.*/ + paramsArray: string[]; + /** the request URI's path component. */ + path: string; + /** the request payload based on the route payload.output and payload.parse settings.*/ + payload: stream.Readable | Buffer | any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ + plugins: any; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ + pre: IDictionary; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ + response: Response; + /**preResponses - same as pre but represented as the response object created by the pre method.*/ + preResponses: any; + /**an object containing the query parameters.*/ + query: any; + /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ + raw: { + req: http.ClientRequest; + res: http.ServerResponse; + }; + /** the route public interface.*/ + route: IRoute; + /** the server object. */ + server: Server; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: any; + /** complex object contining details on the url */ + url: { + /** null when i tested */ + auth: any; + /** null when i tested */ + hash: any; + /** null when i tested */ + host: any; + /** null when i tested */ + hostname: any; + href: string; + path: string; + /** path without search*/ + pathname: string; + /** null when i tested */ + port: any; + /** null when i tested */ + protocol: any; + /** querystring parameters*/ + query: IDictionary; + /** querystring parameters as a string*/ + search: string; + /** null when i tested */ + slashes: any; + }; + + /** request.setUrl(url) + + Available only in 'onRequest' extension methods. + + Changes the request URI before the router begins processing the request where: + + url - the new request path value. var Hapi = require('hapi'); var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + });*/ + setUrl(url: string | url.Url): void; + /** request.setMethod(method) + + Available only in 'onRequest' extension methods. + + Changes the request method before the router begins processing the request where: + + method - is the request HTTP method (e.g. 'GET'). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); + });*/ + setMethod(method: string): void; + + /** request.log(tags, [data, [timestamp]]) + + Always available. + + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.on('request', function (request, event, tags) { + + if (tags.error) { + console.log(event); + } + }); + + var handler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); + }; + */ + log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ + tags: string | string[], + /** an optional message string or object with the application data being logged.*/ + data?: string, + /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ + timestamp?: number): void; + + /** request.getLog([tags], [internal]) + + Always available. + + Returns an array containing the events matching any of the tags specified (logical OR) + request.getLog(); + request.getLog('error'); + request.getLog(['error', 'auth']); + request.getLog(['error'], true); + request.getLog(false);*/ + + getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ + tags?: string, + /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ + internal?: boolean): string[]; + + /** request.tail([name]) + + Available until immediately after the 'response' event is emitted. + + Adds a request tail which has to complete before the request lifecycle is complete where: + + name - an optional tail name used for logging purposes. + Returns a tail function which must be called when the tail activity is completed. + + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + + When all tails completed, the server emits a 'tail' event. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + var get = function (request, reply) { + + var dbTail = request.tail('write to database'); + + db.save('key', 'value', function () { + + dbTail(); + }); + + return reply('Success!'); + }; + + server.route({ method: 'GET', path: '/', handler: get }); + + server.on('tail', function (request) { + + console.log('Request completed including db activity'); + });*/ + tail(/** an optional tail name used for logging purposes.*/ + name?: string): Function; +} +/** Response events + + The response object supports the following events: + + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onPreResponse', function (request, reply) { + +var response = request.response; +if (response.isBoom) { +return reply(); +} + +var hash = Crypto.createHash('sha1'); +response.on('peek', function (chunk) { + +hash.update(chunk); +}); + +response.once('finish', function () { + +console.log(hash.digest('hex')); +}); + +return reply.continue(); +});*/ +export class Response extends Events.EventEmitter { + isBoom: boolean; + /** the HTTP response status code. Defaults to 200 (except for errors).*/ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ + headers: IDictionary; + /** the value provided using the reply interface.*/ + source: any; + /** a string indicating the type of source with available values: + 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + 'buffer' - a Buffer. + 'view' - a view generated with reply.view(). + 'file' - a file generated with reply.file() of via the directory handler. + 'stream' - a Stream. + 'promise' - a Promise object. */ + variety: string; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: any; + /** settings - response handling flags: + charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. + encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. + passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. + stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. + ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. + varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ + settings: { + charset: string; + encoding: string; + passThrough: boolean; + stringify: any; + ttl: number; + varyEtag: boolean; + } + + /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + length - the header value. Must match the actual payload size.*/ + bytes(length: number): Response; + + /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ + charset(charset: string): Response; + + /** sets the HTTP status code where: + statusCode - the HTTP status code.*/ + code(statusCode: number): Response; + + /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ + created(uri: string): Response; + + + /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ + encoding(encoding: string): Response; + + /** etag(tag, options) - sets the representation entity tag where: + tag - the entity tag string without the double-quote. + options - optional settings where: + weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ + etag(tag: string, options: { + weak: boolean; vary: boolean; + }): Response; + + /**header(name, value, options) - sets an HTTP header where: + name - the header name. + value - the header value. + options - optional settings where: + append - if true, the value is appended to any existing header value using separator. Defaults to false. + separator - string used as separator when appending to an exiting value. Defaults to ','. + override - if false, the header value is not set if an existing value present. Defaults to true.*/ + header(name: string, value: string, options?: IHeaderOptions): Response; + + /** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */ + hold(): Response; + + /** location(uri) - sets the HTTP 'Location' header where: + uri - an absolute or relative URI used as the 'Location' header value.*/ + location(uri: string): Response; + + /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: + uri - an absolute or relative URI used to redirect the client to another resource. */ + redirect(uri: string): Response; + + /** replacer(method) - sets the JSON.stringify() replacer argument where: + method - the replacer function or array. Defaults to none.*/ + replacer(method: Function | Array): Response; + + /** spaces(count) - sets the JSON.stringify() space argument where: + count - the number of spaces to indent nested object keys. Defaults to no indentation. */ + spaces(count: number): Response; + + /**state(name, value, [options]) - sets an HTTP cookie where: + name - the cookie name. + value - the cookie value. If no encoding is defined, must be a string. + options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + state(name: string, value: string, options?: any): Response; + + /** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */ + send(): void; + + /** sets a string suffix when the response is process via JSON.stringify().*/ + suffix(suffix: string): void; + + /** overrides the default route cache expiration rule for this response instance where: + msec - the time-to-live value in milliseconds.*/ + ttl(msec: number): void; + + /** type(mimeType) - sets the HTTP 'Content-Type' header where: + mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ + type(mimeType: string): Response; + + /** clears the HTTP cookie by setting an expired value where: + name - the cookie name. + options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + unstate(name: string, options?: { [key: string]: string }): Response; + + /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + header - the HTTP request header name.*/ + vary(header: string): void; +} +/** When using the redirect() method, the response object provides these additional methods */ +export class ResponseRedirect extends Response { + /** sets the status code to 302 or 307 (based on the rewritable() setting) where: + isTemporary - if false, sets status to permanent. Defaults to true.*/ + temporary(isTemporary: boolean): void; + + /** sets the status code to 301 or 308 (based on the rewritable() setting) where: + isPermanent - if true, sets status to temporary. Defaults to false. */ + permanent(isPermanent: boolean): void; + + /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: + isRewritable - if false, sets to non-rewritable. Defaults to true. + Permanent Temporary + Rewritable 301 302(1) + Non-rewritable 308(2) 307 + Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ + rewritable(isRewritable: boolean): void; +} +/** info about a server connection */ +export interface IServerConnectionInfo { + /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ + id: string; + /** - the connection creation timestamp.*/ + created: number; + /** - the connection start timestamp (0 when stopped).*/ + started: number; + /** the connection port based on the following rules: + the configured port value before the server has been started. + the actual port assigned when no port is configured or set to 0 after the server has been started.*/ + port: number; + + /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ + host: string; + /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ + address: string; + /** - the protocol used: + 'http' - HTTP. + 'https' - HTTPS. + 'socket' - UNIX domain socket or Windows named pipe.*/ + protocol: string; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ + uri: string; +} +/** + * undocumented. The connection object constructed after calling server.connection(); + * can be accessed via server.connections; or request.connection; + */ +export class ServerConnection extends Events.EventEmitter { + domain: any; + _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; + _eventsCount: number; + settings: IServerConnectionOptions; + server: Server; + /** ex: "tcp" */ + type: string; + _started: boolean; + /** dictionary of sockets */ + _connections: { [ip_port: string]: any }; + _onConnection: Function; + registrations: any; + _extensions: any; + _requestCounter: { value: number; min: number; max: number }; + _load: any; + states: { + settings: any; cookies: any; names: any[] + }; + auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; }; + _router: any; + MSPluginsCollection: any; + applicationCache: any; + addEventListener: any; + info: IServerConnectionInfo; +} + +/** Server http://hapijs.com/api#server + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + Server events + The server object inherits from Events.EventEmitter and emits the following events: + 'log' - events logged with server.log() and server events generated internally by the framework. + 'start' - emitted when the server is started using server.start(). + 'stop' - emitted when the server is stopped using server.stop(). + 'request' - events generated by request.log(). Does not include any internally generated events. + 'request-internal' - request events generated internally by the framework (multiple events per request). + 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. + 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. + 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. + Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. + MORE EVENTS HERE: http://hapijs.com/api#server-events*/ +export class Server extends Events.EventEmitter { + + constructor(options?: IServerOptions); + + /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + var Hapi = require('hapi'); + server = new Hapi.Server(); + server.app.key = 'value'; + var handler = function (request, reply) { + return reply(request.server.app.key); + }; */ + app: any; + /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + var server = new Hapi.Server(); + server.connection({ port: 80, labels: 'a' }); + server.connection({ port: 8080, labels: 'b' }); + // server.connections.length === 2 + var a = server.select('a'); + // a.connections.length === 1*/ + connections: Array; + /** When the server contains exactly one connection, info is an object containing information about the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // server.info.port === 80 + server.connection({ port: 8080 }); + // server.info === null + // server.connections[1].info.port === 8080 + */ + info: IServerConnectionInfo; + /** An object containing the process load metrics (when load.sampleInterval is enabled): + rss - RSS memory usage. + var Hapi = require('hapi'); + var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + console.log(server.load.rss);*/ + load: { + /** - event loop delay milliseconds.*/ + eventLoopDelay: number; + /** - V8 heap usage.*/ + heapUsed: number; + }; + /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + When the server contains more than one connection, each server.connections array member provides its own connection.listener. + var Hapi = require('hapi'); + var SocketIO = require('socket.io'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var io = SocketIO.listen(server.listener); + io.sockets.on('connection', function(socket) { + socket.emit({ msg: 'welcome' }); + });*/ + listener: http.Server; + + /** server.methods + An object providing access to the server methods where each server method name is an object property. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.method('add', function (a, b, next) { + return next(null, a + b); + }); + server.methods.add(1, 2, function (err, result) { + // result === 3 + });*/ + methods: IDictionary; + + /** server.mime + Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + var Hapi = require('hapi'); + var options = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } + }; + var server = new Hapi.Server(options); + // server.mime.path('code.js').type === 'application/javascript' + // server.mime.path('file.npm').type === 'node/module'*/ + mime: any; + /**server.plugins + An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + exports.register = function (server, options, next) { + server.expose('key', 'value'); + // server.plugins.example.key === 'value' + return next(); + }; + exports.register.attributes = { + name: 'example' + };*/ + plugins: IDictionary; + /** server.realm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: + route - routes preferences: + prefix - the route path prefix used by any calls to server.route() from the server. + vhost - the route virtual host settings used by any calls to server.route() from the server. + plugin - the active plugin name (empty string if at the server root). + plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. + settings - settings overrides: + files.relativeTo + bind + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + };*/ + realm: IServerRealm; + + /** server.root + The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ + root: Server; + /** server.settings + The server configuration object after defaults applied. + var Hapi = require('hapi'); + var server = new Hapi.Server({ + app: { + key: 'value' + } + }); + // server.settings.app === { key: 'value' }*/ + settings: IServerOptions; + + /** server.version + The hapi module version number. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + // server.version === '8.0.0'*/ + version: string; + + /** server.after(method, [dependencies]) + Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: + after - the method with signature function(plugin, next) where: + server - server object the after() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error which is returned back via the server.start() callback. + dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.after(function () { + // Perform some pre-start logic + }); + server.start(function (err) { + // After method already executed + }); + server.auth.default(options)*/ + after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; + + auth: { + /** server.auth.api + An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. + When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. + const server = new Hapi.Server(); + server.connection({ port: 80 }); + const scheme = function (server, options) { + return { + api: { + settings: { + x: 5 + } + }, + authenticate: function (request, reply) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply.continue({ credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + console.log(server.auth.api.default.settings.x); // 5 + */ + api: { + [index: string]: any; + } + /** server.auth.default(options) + Sets a default strategy which is applied to every route where: + options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. + The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. + The default auth strategy configuration can be accessed via connection.auth.settings.default. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + });*/ + default(options: string): void; + default(options: { strategy: string }): void; + default(options: { strategies: string[] }): void; + /** server.auth.scheme(name, scheme) + Registers an authentication scheme where: + name - the scheme name. + scheme - the method implementing the scheme with signature function(server, options) where: + server - a reference to the server object the scheme is added to. + options - optional scheme settings used to instantiate a strategy.*/ + scheme(name: string, + /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + server = new Hapi.Server(); + server.connection({ port: 80 }); + scheme = function (server, options) { + urn { + authenticate: function (request, reply) { + req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + urn reply(null, { credentials: { user: 'john' } }); + } + }; + }; + */ + scheme: (server: Server, options: any) => IServerAuthScheme): void; + + /** server.auth.strategy(name, scheme, [mode], [options]) + Registers an authentication strategy where: + name - the strategy name. + scheme - the scheme name (must be previously registered using server.auth.scheme()). + mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. + options - scheme options based on the scheme requirements. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + } + });*/ + strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; + + /** server.auth.test(strategy, request, next) + Tests a request against an authentication strategy where: + strategy - the strategy name registered with server.auth.strategy(). + request - the request object. + next - the callback function with signature function(err, credentials) where: + err - the error if authentication failed. + credentials - the authentication credentials object if authentication was successful. + Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.server.auth.test('default', request, function (err, credentials) { + if (err) { + return reply({ status: false }); + } + return reply({ status: true, user: credentials.name }); + }); + } + });*/ + test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; + }; + + /** server.bind(context) + Sets a global context used as the default bind object when adding a route or an extension where: + context - the object used to bind this in handler and extension methods. + When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + var handler = function (request, reply) { + return reply(this.message); + }; + exports.register = function (server, options, next) { + var bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); + };*/ + bind(context: any): void; + + + /** server.cache(options) + Provisions a cache segment within the server cache facility where: + options - catbox policy configuration where: + expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + staleTimeout - number of milliseconds to wait before checking if an item is stale. + generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. + cache - the cache name configured in 'server.cache`. Defaults to the default cache. + segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. + shared - if true, allows multiple cache provisions to share the same segment. Default to false. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, function (err) { + cache.get('norway', function (err, value, cached, log) { + // value === { capital: 'oslo' }; + }); + });*/ + cache(options: ICatBoxCacheOptions): void; + + /** server.connection([options]) + Adds an incoming server connection + Returns a server object with the new connection selected. + Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). + Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); + var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + // server.connections.length === 2 + // web.connections.length === 1 + // admin.connections.length === 1 */ + connection(options: IServerConnectionOptions): Server; + + /** server.decorate(type, property, method, [options]) + Extends various framework interfaces with custom methods where: + type - the interface being decorated. Supported types: + 'reply' - adds methods to the reply interface. + 'server' - adds methods to the Server object. + property - the object decoration key name. + method - the extension function. + options - if the type is 'request', supports the following optional settings: + 'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + Note that decorations apply to the entire server and all its connections regardless of current selection. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.decorate('reply', 'success', function () { + return this.response({ status: 'ok' }); + }); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply.success(); + } + });*/ + decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void; + + /** server.dependency(dependencies, [after]) + Used within a plugin to declares a required dependency on other plugins where: + dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. + after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + server - the server the dependency() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error condition, which is returned back via the server.start() callback. + exports.register = function (server, options, next) { + server.dependency('yar', after); + return next(); + }; + var after = function (server, next) { + // Additional plugin registration logic + return next(); + };*/ + dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; + + + /** server.expose(key, value) + Used within a plugin to expose a property via server.plugins[name] where: + key - the key assigned (server.plugins[name][key]). + value - the value assigned. + exports.register = function (server, options, next) { + server.expose('util', function () { console.log('something'); }); + return next(); + };*/ + expose(key: string, value: any): void; + + /** server.expose(obj) + Merges a deep copy of an object into to the existing content of server.plugins[name] where: + obj - the object merged into the exposed properties container. + exports.register = function (server, options, next) { + server.expose({ util: function () { console.log('something'); } }); + return next(); + };*/ + expose(obj: any): void; + + /** server.ext(event, method, [options]) + Registers an extension function in one of the available extension points where: + event - the event name. + method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: + request - the request object. NOTE: Access the Response via request.response + reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + this - the object provided via options.bind or the current active context set with server.bind(). + options - an optional object with the following: + before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + bind - a context object passed back to the provided method (via this) when called. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + }); + var handler = function (request, reply) { + return reply({ status: 'ok' }); + }; + server.route({ method: 'GET', path: '/test', handler: handler }); + server.start(); + // All requests will get routed to '/test'*/ + ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + + /** server.handler(name, method) + Registers a new handler type to be used in routes where: + name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. + method - the function used to generate the route handler using the signature function(route, options) where: + route - the route public interface object. + options - the configuration object provided in the handler config. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + // Defines new handler for routes on this server + server.handler('test', function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }); + server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } + }); + server.start(); + The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + var handler = function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }; + // Change the default payload processing for this handler + handler.defaults = { + payload: { + output: 'stream', + parse: false + } + }; + server.handler('test', handler);*/ + handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; + + /** server.initialize([callback]) + Initializes the server (starts the caches, finalizes plugin registration) but does not start listening + on the connection ports, where: + - `callback` - the callback method when server initialization is completed or failed with the signature + `function(err)` where: + - `err` - any initialization error condition. + + If no `callback` is provided, a `Promise` object is returned. + + Note that if the method fails and the callback includes an error, the server is considered to be in + an undefined state and should be shut down. In most cases it would be impossible to fully recover as + the various plugins, caches, and other event listeners will get confused by repeated attempts to + start the server or make assumptions about the healthy state of the environment. It is recommended + to assert that no error has been returned after calling `initialize()` to abort the process when the + server fails to start properly. If you must try to resume after an error, call `server.stop()` + first to reset the server state. + */ + initialize(callback?: (error: any) => void): IPromise; + + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var handler = function (request, reply) { + return reply('Success!'); + }; + server.route({ method: 'GET', path: '/', handler: handler }); + server.inject('/', function (res) { + console.log(res.result); + }); + */ + inject: IServerInject; + + /** server.log(tags, [data, [timestamp]]) + Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('log', function (event, tags) { + if (tags.error) { + console.log(event); + } + }); + server.log(['test', 'error'], 'Test event');*/ + log(tags: string | string[], data?: string | any, timestamp?: number): void; + + /**server.lookup(id) + When the server contains exactly one connection, looks up a route configuration where: + id - the route identifier as set in the route options. + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.lookup('root'); + When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ + lookup(id: string): IRoute; + + /** server.match(method, path, [host]) + When the server contains exactly one connection, looks up a route configuration where: + method - the HTTP method (e.g. 'GET', 'POST'). + path - the requested path (must begin with '/'). + host - optional hostname (to match against routes with vhost). + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.match('get', '/'); + When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ + match(method: string, path: string, host?: string): IRoute; + + + /** server.method(name, method, [options]) + Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + Methods are registered via server.method(name, method, [options]) + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Simple arguments + var add = function (a, b, next) { + return next(null, a + b); + }; + server.method('sum', add, { cache: { expiresIn: 2000 } }); + server.methods.sum(4, 5, function (err, result) { + console.log(result); + }); + // Object argument + var addArray = function (array, next) { + var sum = 0; + array.forEach(function (item) { + sum += item; + }); + return next(null, sum); + }; + server.method('sumObj', addArray, { + cache: { expiresIn: 2000 }, + generateKey: function (array) { + return array.join(','); + } + }); + server.methods.sumObj([5, 6], function (err, result) { + console.log(result); + }); + // Synchronous method with cache + var addSync = function (a, b) { + return a + b; + }; + server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); + server.methods.sumSync(4, 5, function (err, result) { + console.log(result); + }); */ + method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ + name: string, + method: IServerMethod, + options?: IServerMethodOptions): void; + + + /**server.method(methods) + Registers a server method function as described in server.method() using a configuration object where: + methods - an object or an array of objects where each one contains: + name - the method name. + method - the method function. + options - optional settings. + var add = function (a, b, next) { + next(null, a + b); + }; + server.method({ + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000 + } + } + });*/ + method(methods: { + name: string; method: IServerMethod; options?: IServerMethodOptions + } | Array<{ + name: string; method: IServerMethod; options?: IServerMethodOptions + }>): void; + + /**server.path(relativeTo) + Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + relativeTo - the path prefix added to any relative file path starting with '.'. + Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + exports.register = function (server, options, next) { + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); + };*/ + path(relativeTo: string): void; + + + /** + * server.register(plugins, [options], callback) + * Registers a plugin where: + * plugins - an object or array of objects where each one is either: + * a plugin registration function. + * an object with the following: + * register - the plugin registration function. + * options - optional options passed to the registration function when called. + * options - optional registration options (different from the options passed to the registration function): + * select - a string or array of string labels used to pre-select connections for plugin registration. + * routes - modifiers applied to each route added by the plugin: + * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * callback - the callback function with signature function(err) where: + * err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + * + * If no callback is provided, a Promise object is returned. + */ + register(plugins: any | any[], options: { + select: string | string[]; + routes: { + prefix: string; vhost?: string | string[] + }; + }, callback: (err: any) => void): void; + register(plugins: any | any[], options: { + select: string | string[]; + routes: { + prefix: string; vhost?: string | string[] + }; + }): IPromise; + + register(plugins: any | any[], callback: (err: any) => void): void; + register(plugins: any | any[]): IPromise; + + /**server.render(template, context, [options], callback) + Utilizes the server views manager to render a template where: + template - the template filename and path, relative to the views manager templates path (path or relativeTo). + context - optional object used by the template to render context-specific result. Defaults to no context ({}). + options - optional object used to override the views manager configuration. + callback - the callback function with signature function (err, rendered, config) where: + err - the rendering error if any. + rendered - the result view string. + config - the configuration used to render the template. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.views({ + engines: { html: require('handlebars') }, + path: __dirname + '/templates' + }); + var context = { + title: 'Views Example', + message: 'Hello, World' + }; + server.render('hello', context, function (err, rendered, config) { + console.log(rendered); + });*/ + render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; + + /** server.route(options) + Adds a connection route where: + options - a route configuration object or an array of configuration objects. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); + server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } + ]);*/ + route(options: IRouteConfiguration): void; + route(options: IRouteConfiguration[]): void; + + /**server.select(labels) + Selects a subset of the server's connections where: + labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, labels: ['a'] }); + server.connection({ port: 8080, labels: ['b'] }); + server.connection({ port: 8081, labels: ['c'] }); + server.connection({ port: 8082, labels: ['c','d'] }); + var a = server.select('a'); // The server with port 80 + var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 + var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ + select(labels: string | string[]): Server | Server[]; + + /** server.start([callback]) + Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: + callback - optional callback when server startup is completed or failed with the signature function(err) where: + err - any startup error condition. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.start(function (err) { + console.log('Server started at: ' + server.info.uri); + });*/ + start(callback?: (err: any) => void): IPromise; + + /** server.state(name, [options]) + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions + State defaults can be modified via the server connections.routes.state configuration option. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Set cookie definition + server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' + }); + // Set state in route handler + var handler = function (request, reply) { + var session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + session.last = Date.now(); + return reply('Success').state('session', session); + }; + Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('request-internal', function (request, event, tags) { + if (tags.error && tags.state) { + console.error(event); + } + }); */ + state(name: string, options?: ICookieSettings): void; + + /** server.stop([options], [callback]) + Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + options - optional object with: + timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.stop({ timeout: 60 * 1000 }, function () { + console.log('Server stopped'); + });*/ + stop(options?: { timeout: number }, callback?: () => void): IPromise; + + /**server.table([host]) + Returns a copy of the routing table where: + host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path. + Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.table(); + When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.connections[0].table(); + //[ + // { + // method: 'get', + // path: '/example', + // settings: { ... } + // } + //] + */ + table(host?: any): IConnectionTable; + + /**server.views(options) + Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); server.views({ engines: { html: require('handlebars'), @@ -232,2196 +2419,8 @@ declare module "hapi" { }, path: '/static/templates' }); - When server.views() is called within a plugin, the views manager is only available to plugins methods. - */ - export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { - /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ - engines: IDictionary | IServerViewsEnginesOptions; - /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ - defaultExtension?: string; - } + When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ + views(options: IServerViewsConfiguration): void; - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; - - /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. - * The data argument is only used for passing back authentication data and is ignored elsewhere. */ - continue(credentialData?: any): void; - - /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ - file(/** the file path. */ - path: string, - /** optional settings: */ - options?: { - /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /** specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ - lookupCompressed: boolean; - }): void; - /** Concludes the handler activity by returning control over to the router with a templatized view response. - the response flow control rules apply. */ - view(/** the template filename and path, relative to the templates path configured via the server views manager. */ - template: string, - /** optional object used by the template to render context-specific result. Defaults to no context {}. */ - context?: {}, - /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ - options?: any): Response; - /** Sets a header on the response */ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed - The response flow control rules do not apply. */ - close(options?: { - /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ - end?: boolean; - }): void; - /** Proxies the request to an upstream endpoint. - the response flow control rules do not apply. */ - - proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ - options: IProxyHandlerConfig): void; - /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). - he response flow control rules apply. */ - redirect(uri: string): ResponseRedirect; - - /** Replies with the specified response */ - response(result: any): Response; - - /** Sets a cookie on the response */ - state(name: string, value: any, options?: any): void; - - /** Clears a cookie on the response */ - unstate(name: string, options?: any): void; - } - - export interface ISessionHandler { - (request: Request, reply: IReply): void; - } - export interface IRequestHandler { - (request: Request): T; - } - - - export interface IFailAction { - (source: string, error: any, next: () => void): void - } - /** generates a reverse proxy handler */ - export interface IProxyHandlerConfig { - /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ - host?: string; - /** the upstream service port. */ - port?: number; - /** The protocol to use when making a request to the proxied host: - 'http' - 'https'*/ - protocol?: string; - /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ - uri?: string; - /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ - passThrough?: boolean; - /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ - localStatePassThrough?: boolean; - /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ - acceptEncoding?: boolean; - /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ - rejectUnauthorized?: boolean; - /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ - xforward?: boolean; - /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ - redirects?: boolean | number; - /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ - timeout?: number; - /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: - request - is the incoming request object. - callback - is function(err, uri, headers) where: - err - internal error condition. - uri - the absolute proxy URI. - headers - optional object where each key is an HTTP request header and the value is the header content.*/ - mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; - /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ - onResponse?: (err: any, - res: http.ServerResponse, - req: Request, - reply: IReply, - settings: IProxyHandlerConfig, - ttl: number) => void; - /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ - ttl?: number; - /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ - agent?: http.Agent; - /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ - maxSockets?: boolean | number; - } - /** TODO: fill in joi definition */ - export interface IJoi { - - } - /** a validation function using the signature function(value, options, next) */ - export interface IValidationFunction { - - (/** the object containing the path parameters. */ - value: any, - /** the server validation options. */ - options: any, - /** the callback function called when validation is completed. */ - next: (err: any, value: any) => void): void; - } - /** a custom error handler function with the signature 'function(request, reply, source, error)` */ - export interface IRouteFailFunction { - /** a custom error handler function with the signature 'function(request, reply, source, error)` */ - (/** - the [request object]. */ - request: Request, - /** the continuation reply interface. */ - reply: IReply, - /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ - source: string, - /** the error object prepared for the client response (including the validation function error under error.data). */ - error: any): void; - } - - /** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ - export interface IRouteAdditionalConfigurationOptions { - /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ - app?: any; - /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. - a string with the name of an authentication strategy registered with server.auth.strategy(). - an object */ - auth?: boolean | string | - { - /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: - 'required'authentication is required. - 'optional'authentication is optional (must be valid if present). - 'try'same as 'optional' but allows for invalid authentication. */ - mode?: string; - /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ - strategies?: string | Array; - /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: - falseno payload authentication.This is the default value. - 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. - 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ - payload?: string; - /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ - scope?: string | Array | boolean; - /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: - anythe authentication can be on behalf of a user or application.This is the default value. - userthe authentication must be on behalf of a user. - appthe authentication must be on behalf of an application. */ - entity?: string; - /** - * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming - * request and access is granted if at least one rule matches. Each rule object must include at least one of: - */ - access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; - }; - /** an object passed back to the provided handler (via this) when called. */ - bind?: any; - /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ - cache?: { - /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: - fault'no privacy flag.This is the default setting. - 'public'mark the response as suitable for public caching. - 'private'mark the response as suitable only for private caching. */ - privacy: string; - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ - expiresIn: number; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ - expiresAt: string; - }; - /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ - cors?: { - /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ - origin?: Array; - /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ - matchOrigin?: boolean; - /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ - isOriginExposed?: boolean; - /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ - maxAge?: number; - /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ - headers?: string[]; - /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ - additionalHeaders?: string[]; - /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ - methods?: string[]; - /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ - additionalMethods?: string[]; - /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ - exposedHeaders?: string[]; - /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ - additionalExposedHeaders?: string[]; - /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ - credentials?: boolean; - /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ - override?: boolean; - }; - /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ - files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ - relativeTo: string; - }; - - /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; - /** an optional unique identifier used to look up the route using server.lookup(). */ - id?: number; - /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ - json?: { - /** the replacer function or array.Defaults to no action. */ - replacer?: Function | string[]; - /** number of spaces to indent nested object keys.Defaults to no indentation. */ - space?: number | string; - /** string suffix added after conversion to JSON string.Defaults to no suffix. */ - suffix?: string; - }; - /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ - jsonp?: string; - /** determines how the request payload is processed: */ - payload?: { - /** the type of payload representation requested. The value must be one of: - 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. - 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. - 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ - output?: string; - /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: - 'application/json' - 'application/x-www-form-urlencoded' - 'application/octet-stream' - 'text/ *' - 'multipart/form-data' */ - parse?: string | boolean; - /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ - allow?: string | string[]; - /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ - override?: string; - /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ - maxBytes?: number; - /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ - timeout?: number; - /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ - uploads?: string; - /** determines how to handle payload parsing errors. Allowed values are: - 'error'return a Bad Request (400) error response. This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action and continue processing the request. */ - failAction?: string; - }; - /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ - plugins?: IDictionary; - /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ - pre?: any[]; - /** validation rules for the outgoing response payload (response body).Can only validate object response: */ - response?: { - /** the default HTTP status code when the payload is empty. Value can be 200 or 204. - Note that a 200 status code is converted to a 204 only at the time or response transmission - (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ - emptyStatusCode?: number; - /** the default response object validation rules (for all non-error responses) expressed as one of: - true - any payload allowed (no validation performed). This is the default. - false - no payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - value - the object containing the response object. - options - the server validation options. - next(err) - the callback function called when validation is completed. */ - schema?: boolean | any; - /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ - status?: { [statusCode: number]: boolean | any }; - /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ - sample?: number; - /** defines what to do when a response fails validation.Options are: - errorreturn an Internal Server Error (500) error response.This is the default value. - loglog the error but send the response. */ - failAction?: string; - /** if true, applies the validation rule changes to the response.Defaults to false. */ - modify?: boolean; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ - security?: boolean | { - /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ - hsts?: boolean | number | { - /** the max- age portion of the header, as a number.Default is 15768000. */ - maxAge?: number; - /** a boolean specifying whether to add the includeSubdomains flag to the header. */ - includeSubdomains?: boolean; - /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ - preload?: boolean; - }; - /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ - xframe?: { - /** either 'deny', 'sameorigin', or 'allow-from' */ - rule: string; - /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ - source: string; - }; - /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ - xss?: boolean; - /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ - noOpen?: boolean; - /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ - noSniff?: boolean; - }; - /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ - state?: { - /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ - parse: boolean; - /** determines how to handle cookie parsing errors.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action. */ - failAction: string; - }; - /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ - validate?: { - /** validation rules for incoming request headers.Values allowed: - * trueany headers allowed (no validation performed).This is the default. - falseno headers allowed (this will cause all valid HTTP requests to fail). - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the request headers. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. - */ - headers?: boolean | IJoi | IValidationFunction; - - - /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: - trueany path parameters allowed (no validation performed).This is the default. - falseno path variables allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the path parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - params?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: - trueany query parameters allowed (no validation performed).This is the default. - falseno query parameters allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the query parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - query?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request payload (request body).Values allowed: - trueany payload allowed (no validation performed).This is the default. - falseno payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the payload object. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - payload?: boolean | IJoi | IValidationFunction; - /** an optional object with error fields copied into every validation error response. */ - errorFields?: any; - /** determines how to handle invalid requests.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'log the error but continue processing the request. - 'ignore'take no action. - OR a custom error handler function with the signature 'function(request, reply, source, error)` where: - requestthe request object. - replythe continuation reply interface. - sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). - errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction?: string | IRouteFailFunction; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** define timeouts for processing durations: */ - timeout?: { - /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ - server: boolean | number; - /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ - socket: boolean | number; - }; - - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route description used for generating documentation (string). - */ - description?: string; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route notes used for generating documentation (string or array of strings). - */ - notes?: string | string[]; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route tags used for generating documentation (array of strings). - */ - tags?: string[] - } - - /** - * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches - */ - export interface IRouteAdditionalConfigurationAuthAccess { - /** - * the application scope required to access the route. Value can be a scope string or an array of scope strings. - * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. - * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, - * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' - * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties - * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, - * such as 'user-{params.id}'. Defaults to false (no scope requirements). - */ - scope?: string | Array | boolean; - /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: - * any - the authentication can be on behalf of a user or application. This is the default value. - * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. - * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. - */ - entity?: string; - } - - /** server.realm http://hapijs.com/api#serverrealm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), - the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). - Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { - console.log(server.realm.modifiers.route.prefix); - return next(); - }; - */ - export interface IServerRealm { - /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ - modifiers: { - /** routes preferences: */ - route: { - /** - the route path prefix used by any calls to server.route() from the server. */ - prefix: string; - /** the route virtual host settings used by any calls to server.route() from the server. */ - vhost: string; - }; - - }; - /** the active plugin name (empty string if at the server root). */ - plugin: string; - /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ - plugins: IDictionary; - /** settings overrides */ - settings: { - files: { - relativeTo: any; - }; - bind: any; - } - } - /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ - export interface IServerState { - /** - the cookie name string. */name: string; - - /** - are the optional cookie settings: */options: { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; - /** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean - /** - the path scope.Defaults to null (no path).*/path: any; - /** - the domain scope.Defaults to null (no domain). */domain: any; - /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue: (request: Request, next: (err: any, value: any) => void) => void; - /** - encoding performs on the provided value before serialization. Options are: - 'none' - no encoding. When used, the cookie value must be a string. This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON-stringified than encoded using Base64. - 'form' - object value is encoded using the x-www-form-urlencoded method. - 'iron' - Encrypts and sign the value using iron.*/ - encoding: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { - /** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; - /** - password used for HMAC key generation.*/password: string; - }; - /** - password used for 'iron' encoding.*/password: string; - /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; - /** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; - /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; - /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; - /** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; - }; - } - - export interface IFileHandlerConfig { - /** a path string or function as described above.*/ - path: string; - /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ - lookupCompressed: boolean; - } - - /**http://hapijs.com/api#route-handler - Built-in handlers - - The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ - export interface IRouteHandlerConfig { - /** generates a static file endpoint for serving a single file. file can be set to: - a relative or absolute file path string (relative paths are resolved based on the route files configuration). - a function with the signature function(request) which returns the relative or absolute file path. - an object with the following options */ - file?: string | IRequestHandler | IFileHandlerConfig; - /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: - path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: - a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. - an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). - a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. - index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. - listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. - showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. - redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. - lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. - defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ - directory?: { - path: string | Array | IRequestHandler | IRequestHandler>; - index?: boolean | string | string[]; - listing?: boolean; - showHidden?: boolean; - redirectToSlash?: boolean; - lookupCompressed?: boolean; - defaultExtension?: string; - }; - proxy?: IProxyHandlerConfig; - view?: string | { - template: string; - context: { - payload: any; - params: any; - query: any; - pre: any; - } - }; - config?: { - handler: any; - bind: any; - app: any; - plugins: { - [name: string]: any; - }; - pre: Array<() => void>; - validate: { - headers: any; - params: any; - query: any; - payload: any; - errorFields?: any; - failAction?: string | IFailAction; - }; - payload: { - output: { - data: any; - stream: any; - file: any; - }; - parse?: any; - allow?: string | Array; - override?: string; - maxBytes?: number; - uploads?: number; - failAction?: string; - }; - response: { - schema: any; - sample: number; - failAction: string; - }; - cache: { - privacy: string; - expiresIn: number; - expiresAt: number; - }; - auth: string | boolean | { - mode: string; - strategies: Array; - payload?: boolean | string; - tos?: boolean | string; - scope?: string | Array; - entity: string; - }; - cors?: boolean; - jsonp?: string; - description?: string; - notes?: string | Array; - tags?: Array; - }; - } - /** Route configuration - The route configuration object*/ - export interface IRouteConfiguration { - /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ - path: string; - /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). - * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ - method: string | string[]; - /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ - vhost?: string; - /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler: ISessionHandler | string | IRouteHandlerConfig; - /** - additional route options.*/ - config?: IRouteAdditionalConfigurationOptions; - } - /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ - export interface IRoute { - - - /** the route HTTP method. */ - method: string; - /** the route path. */ - path: string; - /** the route vhost option if configured. */ - vhost?: string | Array; - /** the [active realm] associated with the route.*/ - realm: IServerRealm; - /** the [route options] object with all defaults applied. */ - settings: IRouteAdditionalConfigurationOptions; - } - - export interface IServerAuthScheme { - /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: - request - the request object. - reply - the reply interface the authentication method must call when done authenticating the request where: - reply(err, response, result) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - result - an object containing: - credentials - the authenticated credentials. - artifacts - optional authentication artifacts. - reply.continue(result) - is called if authentication succeeded where: - result - same object as result above. - When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. - .If the err returned by the reply() method includes a message, no additional strategies will be attempted. - If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var scheme = function (server, options) { - return { - authenticate: function (request, reply) { - var req = request.raw.req; - var authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply(null, { credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme);*/ - authenticate(request: Request, reply: IReply): void; - /** payload(request, reply) - optional function called to authenticate the request payload where: - request - the request object. - reply(err, response) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - reply.continue() - is called if payload authentication succeeded. - When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ - payload?(request: Request, reply: IReply): void; - /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: - request - the request object. - reply(err, response) - is called if an error occurred where: - err - any authentication error. - response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. - reply.continue() - is called if the operation succeeded.*/ - response?(request: Request, reply: IReply): void; - /** an optional object */ - options?: { - /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ - payload: boolean; - } - } - - /**the response object where: - statusCode - the HTTP status code. - headers - an object containing the headers set. - payload - the response payload string. - rawPayload - the raw response payload buffer. - raw - an object with the injection request and response objects: - req - the simulated node request object. - res - the simulated node response object. - result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - request - the request object.*/ - export interface IServerInjectResponse { - statusCode: number; - headers: IDictionary; - payload: string; - rawPayload: Buffer; - raw: { - req: http.ClientRequest; - res: http.ServerResponse - }; - result: string; - request: Request; - } - - export interface IServerInject { - (options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void; - (options: string | IServerInjectOptions): IPromise; - } - - export interface IServerInjectOptions { - /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ - method: string; - /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ - url: string; - /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ - headers?: IDictionary; - /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ - payload?: string | {} | Buffer; - /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ - credentials?: any; - /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ - artifacts?: any; - /** sets the initial value of request.app*/ - app?: any; - /** sets the initial value of request.plugins*/ - plugins?: any; - /** allows access to routes with config.isInternal set to true. Defaults to false.*/ - allowInternals?: boolean; - /** sets the remote address for the incoming connection.*/ - remoteAddress?: boolean; - /**object with options used to simulate client request stream conditions for testing: - error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. - close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. - end - if false, does not end the stream. Defaults to true.*/ - simulate?: { - error: boolean; - close: boolean; - end: boolean; - }; - } - - - /** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path.*/ - export interface IConnectionTable { - info: any; - labels: any; - table: IRoute[]; - } - - export interface ICookieSettings { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ - ttl?: number; - /** - sets the 'Secure' flag.Defaults to false.*/ - isSecure?: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/ - isHttpOnly?: boolean; - /** - the path scope.Defaults to null (no path).*/ - path?: string; - /** - the domain scope.Defaults to null (no domain).*/ - domain?: any; - /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue?: (request: Request, next: (err: any, value: any) => void) => void; - /** - encoding performs on the provided value before serialization.Options are: - 'none' - no encoding.When used, the cookie value must be a string.This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON- stringified than encoded using Base64. - 'form' - object value is encoded using the x- www - form - urlencoded method. */ - encoding?: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: - integrity - algorithm options.Defaults to require('iron').defaults.integrity. - password - password used for HMAC key generation. */ - sign?: { integrity: any; password: string; } - password?: string; - iron?: any; - ignoreErrors?: boolean; - clearInvalid?: boolean; - strictHeader?: boolean; - passThrough?: any; - } - - /** method - the method function with the signature is one of: - function(arg1, arg2, ..., argn, next) where: - arg1, arg2, etc. - the method function arguments. - next - the function called when the method is done with the signature function(err, result, ttl) where: - err - error response if the method failed. - result - the return value. - ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. - function(arg1, arg2, ..., argn) where: - arg1, arg2, etc. - the method function arguments. - the callback option is set to false. - the method must returns a value (result, Error, or a promise) or throw an Error.*/ - export interface IServerMethod { - //(): void; - //(next: (err: any, result: any, ttl: number) => void): void; - //(arg1: any): void; - //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; - //(arg1: any, arg2: any): void; - (...args: any[]): void; - - } - /** options - optional configuration: - bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. - cache - the same cache configuration used in server.cache(). - callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. - generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ - export interface IServerMethodOptions { - bind?: any; - cache?: ICatBoxCacheOptions; - callback?: boolean; - generateKey?(args: any[]): string; - } - /** Request object - - The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. - Request events - - The request object supports the following events: - - 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the request payload finished reading. The event method signature is function (). - 'disconnect' - emitted when a request errors or aborts unexpectedly. - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - var hash = Crypto.createHash('sha1'); - request.on('peek', function (chunk) { - - hash.update(chunk); - }); - - request.once('finish', function () { - - console.log(hash.digest('hex')); - }); - - request.once('disconnect', function () { - - console.error('request aborted'); - }); - - return reply.continue(); - });*/ - export class Request extends Events.EventEmitter { - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** authentication information*/ - auth: { - /** true is the request has been successfully authenticated, otherwise false.*/ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ - credentials: any; - /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ - artifacts: any; - /** the route authentication mode.*/ - mode: any; - /** the authentication error is failed and mode set to 'try'.*/ - error: any; - }; - /** the connection used by this request*/ - connection: ServerConnection; - /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ - domain: any; - /** the raw request headers (references request.raw.headers).*/ - headers: IDictionary; - /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ - id: number; - /** request information */ - info: { - /** the request preferred encoding. */ - acceptEncoding: string; - /** if CORS is enabled for the route, contains the following: */ - cors: { - isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ - }; - /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ - host: string; - /** the hostname part of the 'Host' header (e.g. 'example.com').*/ - hostname: string; - /** request reception timestamp. */ - received: number; - /** content of the HTTP 'Referrer' (or 'Referer') header. */ - referrer: string; - /** remote client IP address. */ - remoteAddress: string; - /** remote client port. */ - remotePort: number; - /** request response timestamp (0 is not responded yet). */ - responded: number; - }; - /** the request method in lower case (e.g. 'get', 'post'). */ - method: string; - /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ - mime: string; - /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ - orig: { - params: any; - query: any; - payload: any; - }; - /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ - params: IDictionary; - /** an array containing all the path params values in the order they appeared in the path.*/ - paramsArray: string[]; - /** the request URI's path component. */ - path: string; - /** the request payload based on the route payload.output and payload.parse settings.*/ - payload: stream.Readable | Buffer | any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ - plugins: any; - /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ - pre: IDictionary; - /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ - response: Response; - /**preResponses - same as pre but represented as the response object created by the pre method.*/ - preResponses: any; - /**an object containing the query parameters.*/ - query: any; - /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ - raw: { - req: http.ClientRequest; - res: http.ServerResponse; - }; - /** the route public interface.*/ - route: IRoute; - /** the server object. */ - server: Server; - /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - state: any; - /** complex object contining details on the url */ - url: { - /** null when i tested */ - auth: any; - /** null when i tested */ - hash: any; - /** null when i tested */ - host: any; - /** null when i tested */ - hostname: any; - href: string; - path: string; - /** path without search*/ - pathname: string; - /** null when i tested */ - port: any; - /** null when i tested */ - protocol: any; - /** querystring parameters*/ - query: IDictionary; - /** querystring parameters as a string*/ - search: string; - /** null when i tested */ - slashes: any; - }; - - /** request.setUrl(url) - - Available only in 'onRequest' extension methods. - - Changes the request URI before the router begins processing the request where: - - url - the new request path value. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - });*/ - setUrl(url: string | url.Url): void; - /** request.setMethod(method) - - Available only in 'onRequest' extension methods. - - Changes the request method before the router begins processing the request where: - - method - is the request HTTP method (e.g. 'GET'). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to 'GET' - request.setMethod('GET'); - return reply.continue(); - });*/ - setMethod(method: string): void; - - /** request.log(tags, [data, [timestamp]]) - - Always available. - - Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.on('request', function (request, event, tags) { - - if (tags.error) { - console.log(event); - } - }); - - var handler = function (request, reply) { - - request.log(['test', 'error'], 'Test event'); - return reply(); - }; - */ - log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ - tags: string | string[], - /** an optional message string or object with the application data being logged.*/ - data?: string, - /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ - timestamp?: number): void; - - /** request.getLog([tags], [internal]) - - Always available. - - Returns an array containing the events matching any of the tags specified (logical OR) - request.getLog(); - request.getLog('error'); - request.getLog(['error', 'auth']); - request.getLog(['error'], true); - request.getLog(false);*/ - - getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ - tags?: string, - /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ - internal?: boolean): string[]; - - /** request.tail([name]) - - Available until immediately after the 'response' event is emitted. - - Adds a request tail which has to complete before the request lifecycle is complete where: - - name - an optional tail name used for logging purposes. - Returns a tail function which must be called when the tail activity is completed. - - Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - - When all tails completed, the server emits a 'tail' event. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - var get = function (request, reply) { - - var dbTail = request.tail('write to database'); - - db.save('key', 'value', function () { - - dbTail(); - }); - - return reply('Success!'); - }; - - server.route({ method: 'GET', path: '/', handler: get }); - - server.on('tail', function (request) { - - console.log('Request completed including db activity'); - });*/ - tail(/** an optional tail name used for logging purposes.*/ - name?: string): Function; - } - /** Response events - - The response object supports the following events: - - 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onPreResponse', function (request, reply) { - - var response = request.response; - if (response.isBoom) { - return reply(); - } - - var hash = Crypto.createHash('sha1'); - response.on('peek', function (chunk) { - - hash.update(chunk); - }); - - response.once('finish', function () { - - console.log(hash.digest('hex')); - }); - - return reply.continue(); - });*/ - export class Response extends Events.EventEmitter { - isBoom: boolean; - /** the HTTP response status code. Defaults to 200 (except for errors).*/ - statusCode: number; - /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ - headers: IDictionary; - /** the value provided using the reply interface.*/ - source: any; - /** a string indicating the type of source with available values: - 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). - 'buffer' - a Buffer. - 'view' - a view generated with reply.view(). - 'file' - a file generated with reply.file() of via the directory handler. - 'stream' - a Stream. - 'promise' - a Promise object. */ - variety: string; - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ - plugins: any; - /** settings - response handling flags: - charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. - encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. - passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. - stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. - ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. - varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ - settings: { - charset: string; - encoding: string; - passThrough: boolean; - stringify: any; - ttl: number; - varyEtag: boolean; - } - - /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: - length - the header value. Must match the actual payload size.*/ - bytes(length: number): Response; - - /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ - charset(charset: string): Response; - - /** sets the HTTP status code where: - statusCode - the HTTP status code.*/ - code(statusCode: number): Response; - - /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ - created(uri: string): Response; - - - /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ - encoding(encoding: string): Response; - - /** etag(tag, options) - sets the representation entity tag where: - tag - the entity tag string without the double-quote. - options - optional settings where: - weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. - vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ - etag(tag: string, options: { - weak: boolean; vary: boolean; - }): Response; - - /**header(name, value, options) - sets an HTTP header where: - name - the header name. - value - the header value. - options - optional settings where: - append - if true, the value is appended to any existing header value using separator. Defaults to false. - separator - string used as separator when appending to an exiting value. Defaults to ','. - override - if false, the header value is not set if an existing value present. Defaults to true.*/ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */ - hold(): Response; - - /** location(uri) - sets the HTTP 'Location' header where: - uri - an absolute or relative URI used as the 'Location' header value.*/ - location(uri: string): Response; - - /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: - uri - an absolute or relative URI used to redirect the client to another resource. */ - redirect(uri: string): Response; - - /** replacer(method) - sets the JSON.stringify() replacer argument where: - method - the replacer function or array. Defaults to none.*/ - replacer(method: Function | Array): Response; - - /** spaces(count) - sets the JSON.stringify() space argument where: - count - the number of spaces to indent nested object keys. Defaults to no indentation. */ - spaces(count: number): Response; - - /**state(name, value, [options]) - sets an HTTP cookie where: - name - the cookie name. - value - the cookie value. If no encoding is defined, must be a string. - options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - state(name: string, value: string, options?: any): Response; - - /** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */ - send(): void; - - /** sets a string suffix when the response is process via JSON.stringify().*/ - suffix(suffix: string): void; - - /** overrides the default route cache expiration rule for this response instance where: - msec - the time-to-live value in milliseconds.*/ - ttl(msec: number): void; - - /** type(mimeType) - sets the HTTP 'Content-Type' header where: - mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ - type(mimeType: string): Response; - - /** clears the HTTP cookie by setting an expired value where: - name - the cookie name. - options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - unstate(name: string, options?: { [key: string]: string }): Response; - - /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: - header - the HTTP request header name.*/ - vary(header: string): void; - } - /** When using the redirect() method, the response object provides these additional methods */ - export class ResponseRedirect extends Response { - /** sets the status code to 302 or 307 (based on the rewritable() setting) where: - isTemporary - if false, sets status to permanent. Defaults to true.*/ - temporary(isTemporary: boolean): void; - - /** sets the status code to 301 or 308 (based on the rewritable() setting) where: - isPermanent - if true, sets status to temporary. Defaults to false. */ - permanent(isPermanent: boolean): void; - - /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: - isRewritable - if false, sets to non-rewritable. Defaults to true. - Permanent Temporary - Rewritable 301 302(1) - Non-rewritable 308(2) 307 - Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ - rewritable(isRewritable: boolean): void; - } - /** info about a server connection */ - export interface IServerConnectionInfo { - /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ - id: string; - /** - the connection creation timestamp.*/ - created: number; - /** - the connection start timestamp (0 when stopped).*/ - started: number; - /** the connection port based on the following rules: - the configured port value before the server has been started. - the actual port assigned when no port is configured or set to 0 after the server has been started.*/ - port: number; - - /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ - host: string; - /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ - address: string; - /** - the protocol used: - 'http' - HTTP. - 'https' - HTTPS. - 'socket' - UNIX domain socket or Windows named pipe.*/ - protocol: string; - /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ - uri: string; - } - /** - * undocumented. The connection object constructed after calling server.connection(); - * can be accessed via server.connections; or request.connection; - */ - export class ServerConnection extends Events.EventEmitter { - domain: any; - _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; - _eventsCount: number; - settings: IServerConnectionOptions; - server: Server; - /** ex: "tcp" */ - type: string; - _started: boolean; - /** dictionary of sockets */ - _connections: { [ip_port: string]: any }; - _onConnection: Function; - registrations: any; - _extensions: any; - _requestCounter: { value: number; min: number; max: number }; - _load: any; - states: { - settings: any; cookies: any; names: any[] - }; - auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; }; - _router: any; - MSPluginsCollection: any; - applicationCache: any; - addEventListener: any; - info: IServerConnectionInfo; - } - - /** Server http://hapijs.com/api#server - rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). - Server events - The server object inherits from Events.EventEmitter and emits the following events: - 'log' - events logged with server.log() and server events generated internally by the framework. - 'start' - emitted when the server is started using server.start(). - 'stop' - emitted when the server is stopped using server.stop(). - 'request' - events generated by request.log(). Does not include any internally generated events. - 'request-internal' - request events generated internally by the framework (multiple events per request). - 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. - 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. - 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. - Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. - MORE EVENTS HERE: http://hapijs.com/api#server-events*/ - export class Server extends Events.EventEmitter { - - constructor(options?: IServerOptions); - - /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. - var Hapi = require('hapi'); - server = new Hapi.Server(); - server.app.key = 'value'; - var handler = function (request, reply) { - return reply(request.server.app.key); - }; */ - app: any; - /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. - var server = new Hapi.Server(); - server.connection({ port: 80, labels: 'a' }); - server.connection({ port: 8080, labels: 'b' }); - // server.connections.length === 2 - var a = server.select('a'); - // a.connections.length === 1*/ - connections: Array; - /** When the server contains exactly one connection, info is an object containing information about the sole connection. - * When the server contains more than one connection, each server.connections array member provides its own connection.info. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // server.info.port === 80 - server.connection({ port: 8080 }); - // server.info === null - // server.connections[1].info.port === 8080 - */ - info: IServerConnectionInfo; - /** An object containing the process load metrics (when load.sampleInterval is enabled): - rss - RSS memory usage. - var Hapi = require('hapi'); - var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); - console.log(server.load.rss);*/ - load: { - /** - event loop delay milliseconds.*/ - eventLoopDelay: number; - /** - V8 heap usage.*/ - heapUsed: number; - }; - /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. - When the server contains more than one connection, each server.connections array member provides its own connection.listener. - var Hapi = require('hapi'); - var SocketIO = require('socket.io'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var io = SocketIO.listen(server.listener); - io.sockets.on('connection', function(socket) { - socket.emit({ msg: 'welcome' }); - });*/ - listener: http.Server; - - /** server.methods - An object providing access to the server methods where each server method name is an object property. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.method('add', function (a, b, next) { - return next(null, a + b); - }); - server.methods.add(1, 2, function (err, result) { - // result === 3 - });*/ - methods: IDictionary; - - /** server.mime - Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. - var Hapi = require('hapi'); - var options = { - mime: { - override: { - 'node/module': { - source: 'steve', - compressible: false, - extensions: ['node', 'module', 'npm'], - type: 'node/module' - } - } - } - }; - var server = new Hapi.Server(options); - // server.mime.path('code.js').type === 'application/javascript' - // server.mime.path('file.npm').type === 'node/module'*/ - mime: any; - /**server.plugins - An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. - exports.register = function (server, options, next) { - server.expose('key', 'value'); - // server.plugins.example.key === 'value' - return next(); - }; - exports.register.attributes = { - name: 'example' - };*/ - plugins: IDictionary; - /** server.realm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: - route - routes preferences: - prefix - the route path prefix used by any calls to server.route() from the server. - vhost - the route virtual host settings used by any calls to server.route() from the server. - plugin - the active plugin name (empty string if at the server root). - plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. - settings - settings overrides: - files.relativeTo - bind - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { - console.log(server.realm.modifiers.route.prefix); - return next(); - };*/ - realm: IServerRealm; - - /** server.root - The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ - root: Server; - /** server.settings - The server configuration object after defaults applied. - var Hapi = require('hapi'); - var server = new Hapi.Server({ - app: { - key: 'value' - } - }); - // server.settings.app === { key: 'value' }*/ - settings: IServerOptions; - - /** server.version - The hapi module version number. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - // server.version === '8.0.0'*/ - version: string; - - /** server.after(method, [dependencies]) - Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: - after - the method with signature function(plugin, next) where: - server - server object the after() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error which is returned back via the server.start() callback. - dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.after(function () { - // Perform some pre-start logic - }); - server.start(function (err) { - // After method already executed - }); - server.auth.default(options)*/ - after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; - - auth: { - /** server.auth.api - An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. - When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. - const server = new Hapi.Server(); - server.connection({ port: 80 }); - const scheme = function (server, options) { - return { - api: { - settings: { - x: 5 - } - }, - authenticate: function (request, reply) { - const req = request.raw.req; - const authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply.continue({ credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - console.log(server.auth.api.default.settings.x); // 5 - */ - api: { - [index: string]: any; - } - /** server.auth.default(options) - Sets a default strategy which is applied to every route where: - options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. - The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. - The default auth strategy configuration can be accessed via connection.auth.settings.default. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.auth.default('default'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply(request.auth.credentials.user); - } - });*/ - default(options: string): void; - default(options: { strategy: string }): void; - default(options: { strategies: string[] }): void; - /** server.auth.scheme(name, scheme) - Registers an authentication scheme where: - name - the scheme name. - scheme - the method implementing the scheme with signature function(server, options) where: - server - a reference to the server object the scheme is added to. - options - optional scheme settings used to instantiate a strategy.*/ - scheme(name: string, - /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. - server = new Hapi.Server(); - server.connection({ port: 80 }); - scheme = function (server, options) { - urn { - authenticate: function (request, reply) { - req = request.raw.req; - var authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - urn reply(null, { credentials: { user: 'john' } }); - } - }; - }; - */ - scheme: (server: Server, options: any) => IServerAuthScheme): void; - - /** server.auth.strategy(name, scheme, [mode], [options]) - Registers an authentication strategy where: - name - the strategy name. - scheme - the scheme name (must be previously registered using server.auth.scheme()). - mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. - options - scheme options based on the scheme requirements. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.route({ - method: 'GET', - path: '/', - config: { - auth: 'default', - handler: function (request, reply) { - return reply(request.auth.credentials.user); - } - } - });*/ - strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; - - /** server.auth.test(strategy, request, next) - Tests a request against an authentication strategy where: - strategy - the strategy name registered with server.auth.strategy(). - request - the request object. - next - the callback function with signature function(err, credentials) where: - err - the error if authentication failed. - credentials - the authentication credentials object if authentication was successful. - Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - request.server.auth.test('default', request, function (err, credentials) { - if (err) { - return reply({ status: false }); - } - return reply({ status: true, user: credentials.name }); - }); - } - });*/ - test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; - }; - - /** server.bind(context) - Sets a global context used as the default bind object when adding a route or an extension where: - context - the object used to bind this in handler and extension methods. - When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. - var handler = function (request, reply) { - return reply(this.message); - }; - exports.register = function (server, options, next) { - var bind = { - message: 'hello' - }; - server.bind(bind); - server.route({ method: 'GET', path: '/', handler: handler }); - return next(); - };*/ - bind(context: any): void; - - - /** server.cache(options) - Provisions a cache segment within the server cache facility where: - options - catbox policy configuration where: - expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. - generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. - staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. - staleTimeout - number of milliseconds to wait before checking if an item is stale. - generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. - cache - the cache name configured in 'server.cache`. Defaults to the default cache. - segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. - shared - if true, allows multiple cache provisions to share the same segment. Default to false. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); - cache.set('norway', { capital: 'oslo' }, null, function (err) { - cache.get('norway', function (err, value, cached, log) { - // value === { capital: 'oslo' }; - }); - });*/ - cache(options: ICatBoxCacheOptions): void; - - /** server.connection([options]) - Adds an incoming server connection - Returns a server object with the new connection selected. - Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). - Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); - var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); - // server.connections.length === 2 - // web.connections.length === 1 - // admin.connections.length === 1 */ - connection(options: IServerConnectionOptions): Server; - - /** server.decorate(type, property, method, [options]) - Extends various framework interfaces with custom methods where: - type - the interface being decorated. Supported types: - 'reply' - adds methods to the reply interface. - 'server' - adds methods to the Server object. - property - the object decoration key name. - method - the extension function. - options - if the type is 'request', supports the following optional settings: - 'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. - Note that decorations apply to the entire server and all its connections regardless of current selection. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.decorate('reply', 'success', function () { - return this.response({ status: 'ok' }); - }); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply.success(); - } - });*/ - decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void; - - /** server.dependency(dependencies, [after]) - Used within a plugin to declares a required dependency on other plugins where: - dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. - after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: - server - the server the dependency() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error condition, which is returned back via the server.start() callback. - exports.register = function (server, options, next) { - server.dependency('yar', after); - return next(); - }; - var after = function (server, next) { - // Additional plugin registration logic - return next(); - };*/ - dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; - - - /** server.expose(key, value) - Used within a plugin to expose a property via server.plugins[name] where: - key - the key assigned (server.plugins[name][key]). - value - the value assigned. - exports.register = function (server, options, next) { - server.expose('util', function () { console.log('something'); }); - return next(); - };*/ - expose(key: string, value: any): void; - - /** server.expose(obj) - Merges a deep copy of an object into to the existing content of server.plugins[name] where: - obj - the object merged into the exposed properties container. - exports.register = function (server, options, next) { - server.expose({ util: function () { console.log('something'); } }); - return next(); - };*/ - expose(obj: any): void; - - /** server.ext(event, method, [options]) - Registers an extension function in one of the available extension points where: - event - the event name. - method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: - request - the request object. NOTE: Access the Response via request.response - reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. - this - the object provided via options.bind or the current active context set with server.bind(). - options - an optional object with the following: - before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - bind - a context object passed back to the provided method (via this) when called. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.ext('onRequest', function (request, reply) { - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - }); - var handler = function (request, reply) { - return reply({ status: 'ok' }); - }; - server.route({ method: 'GET', path: '/test', handler: handler }); - server.start(); - // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - - /** server.handler(name, method) - Registers a new handler type to be used in routes where: - name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. - method - the function used to generate the route handler using the signature function(route, options) where: - route - the route public interface object. - options - the configuration object provided in the handler config. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - // Defines new handler for routes on this server - server.handler('test', function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }); - server.route({ - method: 'GET', - path: '/', - handler: { test: { msg: 'test' } } - }); - server.start(); - The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - var handler = function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }; - // Change the default payload processing for this handler - handler.defaults = { - payload: { - output: 'stream', - parse: false - } - }; - server.handler('test', handler);*/ - handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; - - /** server.initialize([callback]) - Initializes the server (starts the caches, finalizes plugin registration) but does not start listening - on the connection ports, where: - - `callback` - the callback method when server initialization is completed or failed with the signature - `function(err)` where: - - `err` - any initialization error condition. - - If no `callback` is provided, a `Promise` object is returned. - - Note that if the method fails and the callback includes an error, the server is considered to be in - an undefined state and should be shut down. In most cases it would be impossible to fully recover as - the various plugins, caches, and other event listeners will get confused by repeated attempts to - start the server or make assumptions about the healthy state of the environment. It is recommended - to assert that no error has been returned after calling `initialize()` to abort the process when the - server fails to start properly. If you must try to resume after an error, call `server.stop()` - first to reset the server state. - */ - initialize(callback?: (error: any) => void): IPromise; - - /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. - Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. - Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties - * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var handler = function (request, reply) { - return reply('Success!'); - }; - server.route({ method: 'GET', path: '/', handler: handler }); - server.inject('/', function (res) { - console.log(res.result); - }); - */ - inject: IServerInject; - - /** server.log(tags, [data, [timestamp]]) - Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: - tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('log', function (event, tags) { - if (tags.error) { - console.log(event); - } - }); - server.log(['test', 'error'], 'Test event');*/ - log(tags: string | string[], data?: string | any, timestamp?: number): void; - - /**server.lookup(id) - When the server contains exactly one connection, looks up a route configuration where: - id - the route identifier as set in the route options. - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.lookup('root'); - When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ - lookup(id: string): IRoute; - - /** server.match(method, path, [host]) - When the server contains exactly one connection, looks up a route configuration where: - method - the HTTP method (e.g. 'GET', 'POST'). - path - the requested path (must begin with '/'). - host - optional hostname (to match against routes with vhost). - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.match('get', '/'); - When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ - match(method: string, path: string, host?: string): IRoute; - - - /** server.method(name, method, [options]) - Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. - Methods are registered via server.method(name, method, [options]) - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Simple arguments - var add = function (a, b, next) { - return next(null, a + b); - }; - server.method('sum', add, { cache: { expiresIn: 2000 } }); - server.methods.sum(4, 5, function (err, result) { - console.log(result); - }); - // Object argument - var addArray = function (array, next) { - var sum = 0; - array.forEach(function (item) { - sum += item; - }); - return next(null, sum); - }; - server.method('sumObj', addArray, { - cache: { expiresIn: 2000 }, - generateKey: function (array) { - return array.join(','); - } - }); - server.methods.sumObj([5, 6], function (err, result) { - console.log(result); - }); - // Synchronous method with cache - var addSync = function (a, b) { - return a + b; - }; - server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); - server.methods.sumSync(4, 5, function (err, result) { - console.log(result); - }); */ - method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ - name: string, - method: IServerMethod, - options?: IServerMethodOptions): void; - - - /**server.method(methods) - Registers a server method function as described in server.method() using a configuration object where: - methods - an object or an array of objects where each one contains: - name - the method name. - method - the method function. - options - optional settings. - var add = function (a, b, next) { - next(null, a + b); - }; - server.method({ - name: 'sum', - method: add, - options: { - cache: { - expiresIn: 2000 - } - } - });*/ - method(methods: { - name: string; method: IServerMethod; options?: IServerMethodOptions - } | Array<{ - name: string; method: IServerMethod; options?: IServerMethodOptions - }>): void; - - /**server.path(relativeTo) - Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: - relativeTo - the path prefix added to any relative file path starting with '.'. - Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. - exports.register = function (server, options, next) { - server.path(__dirname + '../static'); - server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); - next(); - };*/ - path(relativeTo: string): void; - - - /** - * server.register(plugins, [options], callback) - * Registers a plugin where: - * plugins - an object or array of objects where each one is either: - * a plugin registration function. - * an object with the following: - * register - the plugin registration function. - * options - optional options passed to the registration function when called. - * options - optional registration options (different from the options passed to the registration function): - * select - a string or array of string labels used to pre-select connections for plugin registration. - * routes - modifiers applied to each route added by the plugin: - * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * callback - the callback function with signature function(err) where: - * err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. - * - * If no callback is provided, a Promise object is returned. - */ - register(plugins: any | any[], options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }, callback: (err: any) => void): void; - register(plugins: any | any[], options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }): IPromise; - - register(plugins: any | any[], callback: (err: any) => void): void; - register(plugins: any | any[]): IPromise; - - /**server.render(template, context, [options], callback) - Utilizes the server views manager to render a template where: - template - the template filename and path, relative to the views manager templates path (path or relativeTo). - context - optional object used by the template to render context-specific result. Defaults to no context ({}). - options - optional object used to override the views manager configuration. - callback - the callback function with signature function (err, rendered, config) where: - err - the rendering error if any. - rendered - the result view string. - config - the configuration used to render the template. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.views({ - engines: { html: require('handlebars') }, - path: __dirname + '/templates' - }); - var context = { - title: 'Views Example', - message: 'Hello, World' - }; - server.render('hello', context, function (err, rendered, config) { - console.log(rendered); - });*/ - render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; - - /** server.route(options) - Adds a connection route where: - options - a route configuration object or an array of configuration objects. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); - server.route([ - { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, - { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } - ]);*/ - route(options: IRouteConfiguration): void; - route(options: IRouteConfiguration[]): void; - - /**server.select(labels) - Selects a subset of the server's connections where: - labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. - Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, labels: ['a'] }); - server.connection({ port: 8080, labels: ['b'] }); - server.connection({ port: 8081, labels: ['c'] }); - server.connection({ port: 8082, labels: ['c','d'] }); - var a = server.select('a'); // The server with port 80 - var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 - var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ - select(labels: string | string[]): Server | Server[]; - - /** server.start([callback]) - Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: - callback - optional callback when server startup is completed or failed with the signature function(err) where: - err - any startup error condition. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.start(function (err) { - console.log('Server started at: ' + server.info.uri); - });*/ - start(callback?: (err: any) => void): IPromise; - - /** server.state(name, [options]) - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions - State defaults can be modified via the server connections.routes.state configuration option. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Set cookie definition - server.state('session', { - ttl: 24 * 60 * 60 * 1000, // One day - isSecure: true, - path: '/', - encoding: 'base64json' - }); - // Set state in route handler - var handler = function (request, reply) { - var session = request.state.session; - if (!session) { - session = { user: 'joe' }; - } - session.last = Date.now(); - return reply('Success').state('session', session); - }; - Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('request-internal', function (request, event, tags) { - if (tags.error && tags.state) { - console.error(event); - } - }); */ - state(name: string, options?: ICookieSettings): void; - - /** server.stop([options], [callback]) - Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: - options - optional object with: - timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). - callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.stop({ timeout: 60 * 1000 }, function () { - console.log('Server stopped'); - });*/ - stop(options?: { timeout: number }, callback?: () => void): IPromise; - - /**server.table([host]) - Returns a copy of the routing table where: - host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path. - Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.table(); - When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.connections[0].table(); - //[ - // { - // method: 'get', - // path: '/example', - // settings: { ... } - // } - //] - */ - table(host?: any): IConnectionTable; - - /**server.views(options) - Initializes the server views manager - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.views({ - engines: { - html: require('handlebars'), - jade: require('jade') - }, - path: '/static/templates' - }); - When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ - views(options: IServerViewsConfiguration): void; - - } } + diff --git a/harmony-proxy/index.d.ts b/harmony-proxy/index.d.ts index 851d671869..734c752084 100644 --- a/harmony-proxy/index.d.ts +++ b/harmony-proxy/index.d.ts @@ -29,7 +29,5 @@ declare namespace harmonyProxy { } } -declare module "harmony-proxy" { - let _Proxy: harmonyProxy.ProxyConstructor; - export = _Proxy; -} +declare var _Proxy: harmonyProxy.ProxyConstructor; +export = _Proxy; diff --git a/hashids/index.d.ts b/hashids/index.d.ts index 791d22fefe..d7c5ec56b7 100644 --- a/hashids/index.d.ts +++ b/hashids/index.d.ts @@ -30,7 +30,5 @@ declare namespace Hashids { } } -declare module 'hashids' { - var hashids: Hashids.IHashids; - export = hashids; -} +declare var hashids: Hashids.IHashids; +export = hashids; diff --git a/hashmap/hashmap-tests.ts b/hashmap/hashmap-tests.ts index 0725e1e893..04a2459b54 100644 --- a/hashmap/hashmap-tests.ts +++ b/hashmap/hashmap-tests.ts @@ -1,3 +1,4 @@ +import HashMap = require("hashmap"); var emptyMap:HashMap = new HashMap(); var filledMap:HashMap = new HashMap("bar", 123, "bar2", 234); var copiedMap:HashMap = new HashMap(filledMap); diff --git a/hashmap/index.d.ts b/hashmap/index.d.ts index 9f059d2df8..79e5fd380d 100644 --- a/hashmap/index.d.ts +++ b/hashmap/index.d.ts @@ -125,6 +125,5 @@ declare class HashMap { forEach(callback:(value:TValue, key:TKey) => void):HashMap; } -declare module "hashmap" { - export = HashMap; -} +export = HashMap; +export as namespace HashMap; diff --git a/heap/heap-tests.ts b/heap/heap-tests.ts index 351e2737e5..b3982e13a2 100644 --- a/heap/heap-tests.ts +++ b/heap/heap-tests.ts @@ -1,4 +1,4 @@ - +import Heap = require("heap"); var numberComparator = (a: number, b: number) => { return a.toString().length - b.toString().length; }; var stringComparator = (a: string, b: string) => { return a.length - b.length; }; diff --git a/heap/index.d.ts b/heap/index.d.ts index 3bf17033ad..1ad6936334 100644 --- a/heap/index.d.ts +++ b/heap/index.d.ts @@ -79,6 +79,5 @@ declare class Heap { } -declare module 'heap' { - export = Heap; -} +export = Heap; +export as namespace Heap; diff --git a/helmet/index.d.ts b/helmet/index.d.ts index b38599d1b0..baa99a48bb 100644 --- a/helmet/index.d.ts +++ b/helmet/index.d.ts @@ -4,144 +4,143 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "helmet" { - import express = require("express"); - - interface IHelmetCspDirectiveFunction { - (req: express.Request, res: express.Response): string; - } - type HelmetCspDirectiveValue = string | IHelmetCspDirectiveFunction; +import express = require("express"); - interface IHelmetCspDirectives { - baseUri? : HelmetCspDirectiveValue[], - childSrc? : HelmetCspDirectiveValue[], - connectSrc? : HelmetCspDirectiveValue[], - defaultSrc? : HelmetCspDirectiveValue[], - fontSrc? : HelmetCspDirectiveValue[], - formAction? : HelmetCspDirectiveValue[], - frameAncestors? : HelmetCspDirectiveValue[], - frameSrc? : HelmetCspDirectiveValue[], - imgSrc? : HelmetCspDirectiveValue[], - mediaSrc? : HelmetCspDirectiveValue[], - objectSrc? : HelmetCspDirectiveValue[], - pluginTypes? : HelmetCspDirectiveValue[], - reportUri?: string, - sandbox? : HelmetCspDirectiveValue[], - scriptSrc? : HelmetCspDirectiveValue[], - styleSrc? : HelmetCspDirectiveValue[] - } - - interface IHelmetCspConfiguration { - reportOnly? : boolean; - setAllHeaders? : boolean; - disableAndroid? : boolean; - browserSniff?: boolean; - directives? : IHelmetCspDirectives - } +interface IHelmetCspDirectiveFunction { + (req: express.Request, res: express.Response): string; +} +type HelmetCspDirectiveValue = string | IHelmetCspDirectiveFunction; - interface IHelmetPublicKeyPinsSetIfFunction { - (req: express.Request, res: express.Response): boolean; - } +interface IHelmetCspDirectives { + baseUri? : HelmetCspDirectiveValue[], + childSrc? : HelmetCspDirectiveValue[], + connectSrc? : HelmetCspDirectiveValue[], + defaultSrc? : HelmetCspDirectiveValue[], + fontSrc? : HelmetCspDirectiveValue[], + formAction? : HelmetCspDirectiveValue[], + frameAncestors? : HelmetCspDirectiveValue[], + frameSrc? : HelmetCspDirectiveValue[], + imgSrc? : HelmetCspDirectiveValue[], + mediaSrc? : HelmetCspDirectiveValue[], + objectSrc? : HelmetCspDirectiveValue[], + pluginTypes? : HelmetCspDirectiveValue[], + reportUri?: string, + sandbox? : HelmetCspDirectiveValue[], + scriptSrc? : HelmetCspDirectiveValue[], + styleSrc? : HelmetCspDirectiveValue[] +} - interface IHelmetPublicKeyPinsConfiguration { - maxAge : number; - sha256s : string[]; - includeSubdomains? : boolean; - reportUri? : string; - reportOnly? : boolean; - setIf?: IHelmetPublicKeyPinsSetIfFunction - } +interface IHelmetCspConfiguration { + reportOnly? : boolean; + setAllHeaders? : boolean; + disableAndroid? : boolean; + browserSniff?: boolean; + directives? : IHelmetCspDirectives +} - interface IHelmetXssFilterConfiguration { - setOnOldIE? : boolean; - } +interface IHelmetPublicKeyPinsSetIfFunction { + (req: express.Request, res: express.Response): boolean; +} - interface IHelmetDnsPrefetchControlConfiguration { - allow? : boolean; - } +interface IHelmetPublicKeyPinsConfiguration { + maxAge : number; + sha256s : string[]; + includeSubdomains? : boolean; + reportUri? : string; + reportOnly? : boolean; + setIf?: IHelmetPublicKeyPinsSetIfFunction +} + +interface IHelmetXssFilterConfiguration { + setOnOldIE? : boolean; +} + +interface IHelmetDnsPrefetchControlConfiguration { + allow? : boolean; +} + +/** + * @summary Interface for helmet class. + * @interface + */ +interface Helmet { + /** + * @summary Constructor. + * @return {RequestHandler} The Request handler. + */ + ():express.RequestHandler; /** - * @summary Interface for helmet class. - * @interface + * @summary Stop browsers from doing DNS prefetching. */ - interface Helmet { - /** - * @summary Constructor. - * @return {RequestHandler} The Request handler. - */ - ():express.RequestHandler; + dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration):express.RequestHandler; - /** - * @summary Stop browsers from doing DNS prefetching. - */ - dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration):express.RequestHandler; + /** + * @summary Prevent clickjacking. + * @param {string} header The header. + * @return {RequestHandler} The Request handler. + */ + frameguard(header ?: string):express.RequestHandler; - /** - * @summary Prevent clickjacking. - * @param {string} header The header. - * @return {RequestHandler} The Request handler. - */ - frameguard(header ?: string):express.RequestHandler; + /** + * @summary Hide "X-Powered-By" header. + * @param {Object} options The options. + * @return {RequestHandler} The Request handler. + */ + hidePoweredBy(options ?: Object):express.RequestHandler; - /** - * @summary Hide "X-Powered-By" header. - * @param {Object} options The options. - * @return {RequestHandler} The Request handler. - */ - hidePoweredBy(options ?: Object):express.RequestHandler; + /** + * @summary Adds the "Strict-Transport-Security" header. + * @param {Object} options The options. + * @return {RequestHandler} The Request handler. + */ + hsts(options ?: Object):express.RequestHandler; - /** - * @summary Adds the "Strict-Transport-Security" header. - * @param {Object} options The options. - * @return {RequestHandler} The Request handler. - */ - hsts(options ?: Object):express.RequestHandler; + /** + * @summary Add the "X-Download-Options" header. + * @return {RequestHandler} The Request handler. + */ + ieNoOpen():express.RequestHandler; - /** - * @summary Add the "X-Download-Options" header. - * @return {RequestHandler} The Request handler. - */ - ieNoOpen():express.RequestHandler; + /** + * @summary Add the "Cache-Control" and "Pragma" headers to stop caching. + * @return {RequestHandler} The Request handler. + */ + noCache(options ?: Object):express.RequestHandler; - /** - * @summary Add the "Cache-Control" and "Pragma" headers to stop caching. - * @return {RequestHandler} The Request handler. - */ - noCache(options ?: Object):express.RequestHandler; + /** + * @summary Adds the "X-Content-Type-Options" header. + * @return {RequestHandler} The Request handler. + */ + noSniff():express.RequestHandler; - /** - * @summary Adds the "X-Content-Type-Options" header. - * @return {RequestHandler} The Request handler. - */ - noSniff():express.RequestHandler; + /** + * @summary Adds the "Public-Key-Pins" header. + * @return {RequestHandler} The Request handler. + */ + publicKeyPins(options ?: IHelmetPublicKeyPinsConfiguration):express.RequestHandler; - /** - * @summary Adds the "Public-Key-Pins" header. - * @return {RequestHandler} The Request handler. - */ - publicKeyPins(options ?: IHelmetPublicKeyPinsConfiguration):express.RequestHandler; + /** + * @summary Mitigate cross-site scripting attacks with the "X-XSS-Protection" header. + * @return {RequestHandler} The Request handler. + * @param {Object} options The options. + */ + xssFilter(options ?: IHelmetXssFilterConfiguration):express.RequestHandler; - /** - * @summary Mitigate cross-site scripting attacks with the "X-XSS-Protection" header. - * @return {RequestHandler} The Request handler. - * @param {Object} options The options. - */ - xssFilter(options ?: IHelmetXssFilterConfiguration):express.RequestHandler; + /** + * @summary Set policy around third-party content via headers + * @return {RequestHandler} The Request handler + * @param {Object} options The options + */ + csp(options ?: IHelmetCspConfiguration): express.RequestHandler; - /** - * @summary Set policy around third-party content via headers - * @return {RequestHandler} The Request handler - * @param {Object} options The options - */ - csp(options ?: IHelmetCspConfiguration): express.RequestHandler; + /** + * @see csp + */ + contentSecurityPolicy(options ?: IHelmetCspConfiguration): express.RequestHandler; - /** - * @see csp - */ - contentSecurityPolicy(options ?: IHelmetCspConfiguration): express.RequestHandler; - - } - - var helmet: Helmet; - export = helmet; } + +declare var helmet: Helmet; +export = helmet; + diff --git a/highlight.js/highlightjs.d.ts b/highlight.js/index.d.ts similarity index 98% rename from highlight.js/highlightjs.d.ts rename to highlight.js/index.d.ts index 3de85acb2b..dab36329fe 100644 --- a/highlight.js/highlightjs.d.ts +++ b/highlight.js/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Niklas Mollenhauer , Jeremy Hull // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'highlight.js' { - export = hljs; -} +export = hljs; +export as namespace hljs; declare namespace hljs { diff --git a/i18next/i18next-tests.ts b/i18next/i18next-tests.ts index 3b072587b0..7817c46717 100644 --- a/i18next/i18next-tests.ts +++ b/i18next/i18next-tests.ts @@ -3,7 +3,7 @@ /// /// -import * as i18n from 'i18next'; +import i18n = require("i18next"); i18n.init({ debug: true, @@ -48,15 +48,15 @@ i18n.init({ }, joinArrays: '\n', overloadTranslationOptionHandler: (args:any[]) => { - return {} + return {} }, - interpolation: {}, + interpolation: {}, detection: null, backend: null, cache: null }); -i18n.t('helloWorld', { +i18n.t('helloWorld', { defaultValue: 'default', count: 10 }); diff --git a/i18next/index.d.ts b/i18next/index.d.ts index 9f976fd751..674911fc27 100644 --- a/i18next/index.d.ts +++ b/i18next/index.d.ts @@ -6,7 +6,7 @@ // Sources: https://github.com/i18next/i18next/ -declare namespace I18next { +declare namespace I18n { interface ResourceStore { [language: string]: ResourceStoreLanguage; } @@ -118,8 +118,6 @@ declare namespace I18next { } } -declare module 'i18next' { - var i18n:I18next.I18n; +declare var i18n:I18n.I18n; - export = i18n; -} +export = i18n; diff --git a/iconv/iconv-tests.ts b/iconv/iconv-tests.ts index ecad6547a8..396c207279 100644 --- a/iconv/iconv-tests.ts +++ b/iconv/iconv-tests.ts @@ -1,4 +1,4 @@ -import {Iconv} from "iconv"; +import Iconv = require("iconv"); import {Writable} from "stream"; const iconv: Iconv.Iconv = new Iconv("utf-8", "cp932"); diff --git a/iconv/index.d.ts b/iconv/index.d.ts index a344b82bff..7edebc5f65 100644 --- a/iconv/index.d.ts +++ b/iconv/index.d.ts @@ -33,7 +33,5 @@ declare namespace Iconv { } } -declare module "iconv" { - - var Iconv: Iconv.Static; -} +declare var Iconv: Iconv.Static; +export = Iconv; diff --git a/imap/imap-tests.ts b/imap/imap-tests.ts index ca35ee288b..cae85ae697 100644 --- a/imap/imap-tests.ts +++ b/imap/imap-tests.ts @@ -2,11 +2,11 @@ * This code contains all of the example code that was on https://www.npmjs.com/package/imap as of Sat Dec 13, 2014. */ -import Imap = require('imap'); +import IMAP = require('imap'); import util = require('util'); import inspect = util.inspect; -var imap = new Imap({ +var imap = new IMAP({ user: 'mygmailname@gmail.com', password: 'mygmailpassword', host: 'imap.gmail.com', @@ -36,7 +36,7 @@ imap.once('ready', function() { buffer += chunk.toString('utf8'); }); stream.once('end', function() { - console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer))); + console.log(prefix + 'Parsed header: %s', inspect(IMAP.parseHeader(buffer))); }); }); msg.once('attributes', function(attrs : Object) { @@ -88,7 +88,7 @@ openInbox(function(err : Error, box : IMAP.Box) { }); stream.once('end', function() { if (info.which !== 'TEXT') - console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer))); + console.log(prefix + 'Parsed header: %s', inspect(IMAP.parseHeader(buffer))); else console.log(prefix + 'Body [%s] Finished', inspect(info.which)); }); @@ -148,8 +148,8 @@ openInbox(function(err : Error, box : IMAP.Box) { var rawHeader : string = ''; -var headers = Imap.parseHeader(rawHeader); -headers = Imap.parseHeader(rawHeader, true); +var headers = IMAP.parseHeader(rawHeader); +headers = IMAP.parseHeader(rawHeader, true); var f : IMAP.ImapFetch; f = imap.fetch('1:3', { bodies: '' }); diff --git a/imap/index.d.ts b/imap/index.d.ts index 38cf0a8f77..b0d1ca1f92 100644 --- a/imap/index.d.ts +++ b/imap/index.d.ts @@ -5,7 +5,7 @@ /// -declare namespace IMAP { +declare namespace Connection { // The property names of these interfaces match the documentation (where type names were given). @@ -236,9 +236,12 @@ declare namespace IMAP { serverSupports(capability: string): boolean; } - export class Connection implements NodeJS.EventEmitter, MessageFunctions { + +} + +declare class Connection implements NodeJS.EventEmitter, Connection.MessageFunctions { /** @constructor */ - constructor(config: Config); + constructor(config: Connection.Config); // from NodeJS.EventEmitter addListener(event: string, listener: Function): this; @@ -256,7 +259,7 @@ declare namespace IMAP { /** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. */ search(criteria: any[], callback: (error: Error, uids: number[]) => void): void; /** Fetches message(s) in the currently open mailbox. */ - fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch; + fetch(source: any /* MessageSource */, options: Connection.FetchOptions): Connection.ImapFetch; /** Copies message(s) in the currently open mailbox to another mailbox. */ copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void; /** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */ @@ -295,7 +298,7 @@ declare namespace IMAP { /** seq exposes the search() ... serverSupports() set of commands, but returns sequence number(s) instead of UIDs. */ - seq: MessageFunctions; + seq: Connection.MessageFunctions; /** Attempts to connect and authenticate with the IMAP server. */ connect(): void; /** Closes the connection to the server after all requests in the queue have been sent. */ @@ -303,9 +306,9 @@ declare namespace IMAP { /** Immediately destroys the connection to the server. */ destroy(): void; /** Opens a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. modifiers is used by IMAP extensions. */ - openBox(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void; - openBox(mailboxName: string, openReadOnly: boolean, callback: (error: Error, mailbox: Box) => void): void; - openBox(mailboxName: string, openReadOnly: boolean, modifiers: Object, callback: (error: Error, mailbox: Box) => void): void; + openBox(mailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void; + openBox(mailboxName: string, openReadOnly: boolean, callback: (error: Error, mailbox: Connection.Box) => void): void; + openBox(mailboxName: string, openReadOnly: boolean, modifiers: Object, callback: (error: Error, mailbox: Connection.Box) => void): void; /** Closes the currently open mailbox. If autoExpunge is true, any messages marked as Deleted in the currently open mailbox will be removed if the mailbox was NOT opened in read-only mode. If autoExpunge is false, you disconnect, or you open another mailbox, messages marked as Deleted will NOT be removed from the currently open mailbox. */ closeBox(callback: (error: Error) => void): void; closeBox(autoExpunge: boolean, callback: (error: Error) => void): void; @@ -314,29 +317,25 @@ declare namespace IMAP { /** Removes a specific mailbox that exists on the server. mailboxName should including any necessary prefix/path. */ delBox(mailboxName: string, callback: (error: Error) => void): void; /** Renames a specific mailbox that exists on the server. Both oldMailboxName and newMailboxName should include any necessary prefix/path. Note: Renaming the 'INBOX' mailbox will instead cause all messages in 'INBOX' to be moved to the new mailbox. */ - renameBox(oldMailboxName: string, newMailboxName: string, callback: (error: Error, mailbox: Box) => void): void; + renameBox(oldMailboxName: string, newMailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void; /** Subscribes to a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */ subscribeBox(mailboxName: string, callback: (error: Error) => void): void; /** Unsubscribes from a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */ unsubscribeBox(mailboxName: string, callback: (error: Error) => void): void; /** Fetches information about a mailbox other than the one currently open. Note: There is no guarantee that this will be a fast operation on the server. Also, do not call this on the currently open mailbox. */ - status(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void; + status(mailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void; /** Obtains the full list of mailboxes. If nsPrefix is not specified, the main personal namespace is used. */ - getBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void; - getBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void; + getBoxes(callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void; + getBoxes(nsPrefix: string, callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void; /** Obtains the full list of subscribed mailboxes. If nsPrefix is not specified, the main personal namespace is used. */ - getSubscribedBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void; - getSubscribedBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void; + getSubscribedBoxes(callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void; + getSubscribedBoxes(nsPrefix: string, callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void; /** Permanently removes all messages flagged as Deleted in the currently open mailbox. If the server supports the 'UIDPLUS' capability, uids can be supplied to only remove messages that both have their uid in uids and have the \Deleted flag set. Note: At least on Gmail, performing this operation with any currently open mailbox that is not the Spam or Trash mailbox will merely archive any messages marked as Deleted (by moving them to the 'All Mail' mailbox). */ expunge(callback: (error: Error) => void): void; expunge(uids: any /* MessageSource */, callback: (error: Error) => void): void; /** Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are: */ append(msgData: any, callback: (error: Error) => void): void; - append(msgData: any, options: AppendOptions, callback: (error: Error) => void): void; - } + append(msgData: any, options: Connection.AppendOptions, callback: (error: Error) => void): void; } -declare module "imap" { - var out: typeof IMAP.Connection; - export = out; -} +export = Connection; diff --git a/inflection/index.d.ts b/inflection/index.d.ts index 6a3ab01cbb..46cb32fcc0 100644 --- a/inflection/index.d.ts +++ b/inflection/index.d.ts @@ -22,7 +22,6 @@ interface Inflection { transform(str: string, arr: string[]): string; } -declare module "inflection" { - var inflection: Inflection; - export = inflection; -} +declare var inflection: Inflection; +export = inflection; +export as namespace inflection; diff --git a/insight/index.d.ts b/insight/index.d.ts index f747671bbc..2dfc147da6 100644 --- a/insight/index.d.ts +++ b/insight/index.d.ts @@ -21,29 +21,29 @@ declare namespace insight { } } -declare module "insight" { - import IOptions = insight.IOptions; - import IConfigstore = insight.IConfigstore; - class Insight { - trackingCode:string; - trackingProvider:string; - packageName:string; - packageVersion:string; - os:string; - nodeVersion:string; - appVersion:string; - config:IConfigstore; +import IOptions = insight.IOptions; +import IConfigstore = insight.IConfigstore; - optOut:boolean; - clientId:string; +declare class Insight { + trackingCode:string; + trackingProvider:string; + packageName:string; + packageVersion:string; + os:string; + nodeVersion:string; + appVersion:string; + config:IConfigstore; - constructor(options:IOptions); + optOut:boolean; + clientId:string; - track(...args:string[]):void; + constructor(options:IOptions); - askPermission(msg?:string, cb?:Function):void; - } + track(...args:string[]):void; - export = Insight; + askPermission(msg?:string, cb?:Function):void; } + +export = Insight; + diff --git a/invariant/index.d.ts b/invariant/index.d.ts index ab69402426..2a52a0b490 100644 --- a/invariant/index.d.ts +++ b/invariant/index.d.ts @@ -5,9 +5,8 @@ declare let invariant:invariant.InvariantStatic; -declare module "invariant" { - export = invariant; -} +export = invariant; +export as namespace invariant; declare namespace invariant { interface InvariantStatic { diff --git a/invariant/invariant-tests.ts b/invariant/invariant-tests.ts index 7481fa4681..e0d90fa173 100644 --- a/invariant/invariant-tests.ts +++ b/invariant/invariant-tests.ts @@ -1,4 +1,4 @@ - +import invariant = require("invariant"); // will throw in dev mode (process.env.NODE_ENV !== 'production') invariant(true); diff --git a/inversify/index.d.ts b/inversify/index.d.ts index e6599efba1..871bb99a33 100644 --- a/inversify/index.d.ts +++ b/inversify/index.d.ts @@ -138,6 +138,4 @@ declare namespace inversify { export var paramNames: any; } -declare module "inversify" { - export = inversify; -} +export = inversify; diff --git a/ioredis/index.d.ts b/ioredis/index.d.ts index 81063ed989..2460ba6f76 100644 --- a/ioredis/index.d.ts +++ b/ioredis/index.d.ts @@ -10,24 +10,21 @@ /// -declare module "ioredis" { - - - interface RedisStatic { - new (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (options: IORedis.RedisOptions): IORedis.Redis; - new (url: string): IORedis.Redis; - (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - (options: IORedis.RedisOptions): IORedis.Redis; - (url: string): IORedis.Redis; - Cluster: IORedis.Cluster; - } - - var redis: RedisStatic; - export = redis; +interface RedisStatic { + new (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new (options: IORedis.RedisOptions): IORedis.Redis; + new (url: string): IORedis.Redis; + (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + (options: IORedis.RedisOptions): IORedis.Redis; + (url: string): IORedis.Redis; + Cluster: IORedis.Cluster; } + +declare var redis: RedisStatic; +export = redis; + declare module IORedis { interface Commander { new (): Commander; diff --git a/jasmine-node/index.d.ts b/jasmine-node/index.d.ts index ce0214ac3b..e932a3529f 100644 --- a/jasmine-node/index.d.ts +++ b/jasmine-node/index.d.ts @@ -7,31 +7,29 @@ declare function it(expectation:string, assertion:(done:(err?:any) => void) => void, timeout?:number):void; -declare module "jasmine-node" { - interface ExecuteSpecsOptions { - specFolders: string[], - onComplete?: (runner:jasmine.Runner) => void, - isVerbose?: boolean, - showColors?: boolean, - teamcity?: string | boolean, - useRequireJs?: boolean, - regExpSpec: RegExp, - junitreport?: { - report: boolean, - savePath: string, - useDotNotation: boolean, - consolidate: boolean - }, - includeStackTrace?: boolean, - growl?: boolean - } - - interface JasmineNode { - executeSpecsInFolder(options:ExecuteSpecsOptions): void; - loadHelpersInFolder(path:string, pattern:RegExp): void; - } - - var jasmine:JasmineNode; - - export = jasmine; +interface ExecuteSpecsOptions { + specFolders: string[], + onComplete?: (runner:jasmine.Runner) => void, + isVerbose?: boolean, + showColors?: boolean, + teamcity?: string | boolean, + useRequireJs?: boolean, + regExpSpec: RegExp, + junitreport?: { + report: boolean, + savePath: string, + useDotNotation: boolean, + consolidate: boolean + }, + includeStackTrace?: boolean, + growl?: boolean } + +interface JasmineNode { + executeSpecsInFolder(options:ExecuteSpecsOptions): void; + loadHelpersInFolder(path:string, pattern:RegExp): void; +} + +declare var jasmine:JasmineNode; + +export = jasmine; \ No newline at end of file diff --git a/java/index.d.ts b/java/index.d.ts index aab1bb1126..264a9cdc48 100644 --- a/java/index.d.ts +++ b/java/index.d.ts @@ -8,10 +8,8 @@ // This is the core API exposed by https://github.com/joeferner/java. // To get the full power of Typescript with Java, see https://github.com/RedSeal-co/ts-java. -declare module 'java' { - var NodeJavaCore: NodeJavaCore.NodeAPI; - export = NodeJavaCore; -} +declare var NodeJavaCore: NodeJavaCore.NodeAPI; +export = NodeJavaCore; declare namespace NodeJavaCore { export interface Callback { diff --git a/jfp/index.d.ts b/jfp/index.d.ts index 3617dd2453..8770f3430c 100644 --- a/jfp/index.d.ts +++ b/jfp/index.d.ts @@ -3,7 +3,9 @@ // Definitions by: Chris Stead // Definitions: https://github.com/cmstead/DefinitelyTyped -declare var j: j.JfpStatic +declare var j: j.JfpStatic; +export = j; +export as namespace j; declare namespace j { @@ -12,8 +14,8 @@ declare namespace j { * jfp supports string function aliasing -- alias is a jfp function name and seeking behavior * will happen against the jfp object only. */ - (alias: string, ...arguments: any[]): JfpCurriedOutput; - (externalFunction: (...arguments: any[]) => any, ...arguments: any[]): JfpCurriedOutput; + (alias: string, ...args: any[]): JfpCurriedOutput; + (externalFunction: (...args: any[]) => any, ...args: any[]): JfpCurriedOutput; } interface JfpCurriedOutput { } @@ -80,7 +82,7 @@ declare namespace j { /** * Drops values from array until predicate is satisfied */ - dropUntil(predicate: (...arguments: any[]) => boolean, list: any[]): any[]; + dropUntil(predicate: (...args: any[]) => boolean, list: any[]): any[]; /** * Performs iterable function on each value of provided array @@ -295,22 +297,22 @@ declare namespace j { * @param userFn * @param value */ - shortCircuit(defaultValue: any, userFn: (...arguments: any[]) => any, value: any): any; + shortCircuit(defaultValue: any, userFn: (...args: any[]) => any, value: any): any; /** * Executes function when condition is true * @param predicateValue Value to set behavior execution * @param userFunction Behavior to execute */ - when(predicateValue: boolean, userFunction: (...arguments: any[]) => any): any; + when(predicateValue: boolean, userFunction: (...args: any[]) => any): any; /** * Executes function when condition is true * @param predicateValue Value to set behavior execution * @param userFunction Behavior to execute - * @param ...arguments arguments for userFunction + * @param ...args arguments for userFunction */ - when(predicateValue: boolean, userFunction: (...arguments: any[]) => any, ...arguments: any[]): any; + when(predicateValue: boolean, userFunction: (...args: any[]) => any, ...args: any[]): any; } @@ -338,42 +340,42 @@ declare namespace j { * Signature: (any) -> () -> any * @param value Value to return from produced function */ - always(value: any): (...arguments: any[]) => any; + always(value: any): (...args: any[]) => any; /** * Applies an array of values to a function * @param userFn Function to perform application against * @param values Array of arguments for function */ - apply(userFn: (...arguments: any[]) => any, values: any[]): void; + apply(userFn: (...args: any[]) => any, values: any[]): void; /** * Composes a set of functions into a new single function - * @param ...arguments Arguments for compose + * @param ...args Arguments for compose */ - compose(...arguments: ((...arguments: any[]) => any)[]): (...arguments: any[]) => any + compose(...args: ((...args: any[]) => any)[]): (...args: any[]) => any /** * Counts the number of arguments in a function declaration * @param userFn Function to count arguments of */ - countArguments(userFn: (...arguments: any[]) => any): number; + countArguments(userFn: (...args: any[]) => any): number; /** * Curries function until all arguments are satisfied * @param userFn Function to curry * @param ...argments Initial arguments for currying application */ - curry(userFn: (...arguments: any[]) => any): (...arguments: any[]) => any; - curry(userFn: (...arguments: any[]) => any): any; - curry(userFn: (...arguments: any[]) => any, ...arguments: any[]): (...arguments: any[]) => any; - curry(userFn: (...arguments: any[]) => any, ...arguments: any[]): any; + curry(userFn: (...args: any[]) => any): (...args: any[]) => any; + curry(userFn: (...args: any[]) => any): any; + curry(userFn: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; + curry(userFn: (...args: any[]) => any, ...args: any[]): any; /** * Executes passed function * @param userFn */ - execute(userFn: (...arguments: any[]) => any): any; + execute(userFn: (...args: any[]) => any): any; /** * Gets type of passed value @@ -390,39 +392,39 @@ declare namespace j { /** * Applies values to a function and returns partially applied function * @param userFn Function to apply values to - * @param ...arguments Values to apply + * @param ...args Values to apply */ - partial(userFn: (...arguments: any[]) => any): (...arguments: any[]) => any; - partial(userFn: (...arguments: any[]) => any, ...arguments: any[]): (...arguments: any[]) => any; + partial(userFn: (...args: any[]) => any): (...args: any[]) => any; + partial(userFn: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; /** * Pipelines or chains functions producing a single final output * @param value Initial condition for function pipelining - * @param ...arguments Functions to chain/pipeline + * @param ...args Functions to chain/pipeline */ - pipeline(value: any, ...arguments: ((...arguments: any[]) => any)[]): any; + pipeline(value: any, ...args: ((...args: any[]) => any)[]): any; /** * Recursion function to allow for tail-optimized recursion * @param userFn Function to recur on - * @param ...arguments Initial condition arguments + * @param ...args Initial condition arguments */ - recur(userFn: (...arguments: any[]) => any): any; - recur(userFn: (...arguments: any[]) => any, ...arguments: any[]): any; + recur(userFn: (...args: any[]) => any): any; + recur(userFn: (...args: any[]) => any, ...args: any[]): any; /** * Reverses arguments of provided function * @param userFn */ - reverseArgs(userFn: (...arguments: any[]) => any): (...arguments: any[]) => any; + reverseArgs(userFn: (...args: any[]) => any): (...args: any[]) => any; /** * Performs a right partial application on a function * @param userFn Function to apply arguments - * @param ...arguments Inital arguments + * @param ...args Inital arguments */ - rpartial(userFn: (...arguments: any[]) => any): any; - rpartial(userFn: (...arguments: any[]) => any, ...arguments: any[]): any; + rpartial(userFn: (...args: any[]) => any): any; + rpartial(userFn: (...args: any[]) => any, ...args: any[]): any; /** * Performs a split partial application @@ -430,7 +432,7 @@ declare namespace j { * @param leftArgs * @param rightArgs */ - splitPartial(userFn: (...arguments: any[]) => any, leftArgs: any[], rightArgs: any[]): (...arguments: any[]) => any; + splitPartial(userFn: (...args: any[]) => any, leftArgs: any[], rightArgs: any[]): (...args: any[]) => any; } // Predicate functions @@ -566,12 +568,12 @@ declare namespace j { /** * Composes functions together in common nested order */ - compose(...arguments: ((...arguments: any[]) => any)[]): (...arguments: any[]) => any; + compose(...args: ((...args: any[]) => any)[]): (...args: any[]) => any; /** * Curries passed function and applies optional arguments */ - curry(fn: (...arguments: any[]) => any, ...arguments: any[]): (...arguments: any[]) => any; + curry(fn: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; /** * Returns either typed value based on type parameter @@ -586,27 +588,27 @@ declare namespace j { /** * Returns a partially applied function with remaining arguments reversed */ - partialReverse(fn: (...arguments: any[]) => any, ...arguments: any[]): (...arguments: any[]) => any; + partialReverse(fn: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; /** * Passes chains functions together with an initial arguments */ - pipeline(value: any, ...arguments: ((...arguments: any[]) => any)[]): any; + pipeline(value: any, ...args: ((...args: any[]) => any)[]): any; /** * Composes functions executing from left to right */ - rcompose(...arguments: ((...arguments: any[]) => any)[]): (...arguments: any[]) => any; + rcompose(...args: ((...args: any[]) => any)[]): (...args: any[]) => any; /** * Executes a trampolined tail-optimized recursive function */ - recur(fn: (...arguments: any[]) => any): any; + recur(fn: (...args: any[]) => any): any; /** * Repeats action n times */ - repeat(count: number, action: (...arguments: any[]) => any): any; + repeat(count: number, action: (...args: any[]) => any): any; /** * Outputs a string composed of n copies of base string @@ -821,12 +823,12 @@ declare namespace j { /** * Performs a conjunction (and) operation on two or more booleans */ - and(a: boolean, b: boolean, ...arguments: boolean[]): boolean; + and(a: boolean, b: boolean, ...args: boolean[]): boolean; /** * Performs a disjunction (or) operation on two or more booleans */ - or(a: boolean, b: boolean, ...arguments: boolean[]): boolean; + or(a: boolean, b: boolean, ...args: boolean[]): boolean; /** * Performs an exclusive or operation on two booleans @@ -836,13 +838,9 @@ declare namespace j { /** * Creates composite predicate which performs each check on a value and then conjoins the result */ - composePredicate(...arguments: ((...arguments: any[]) => boolean)[]): (...arguments: any[]) => boolean; + composePredicate(...args: ((...args: any[]) => boolean)[]): (...args: any[]) => boolean; } -} - -declare module "jfp" { - export = j; -} +} \ No newline at end of file diff --git a/jfp/jfp-tests.ts b/jfp/jfp-tests.ts index 07ad67df42..75e4e65be3 100644 --- a/jfp/jfp-tests.ts +++ b/jfp/jfp-tests.ts @@ -1,4 +1,4 @@ - +import j = require("jfp"); function testFn () {}; diff --git a/js-combinatorics/index.d.ts b/js-combinatorics/index.d.ts index d09ce432bb..6a5fa8e249 100644 --- a/js-combinatorics/index.d.ts +++ b/js-combinatorics/index.d.ts @@ -130,6 +130,5 @@ declare namespace __Combinatorics { } -declare module "js-combinatorics" { - export = __Combinatorics; -} +export = __Combinatorics; +export as namespace Combinatorics; diff --git a/js-cookie/index.d.ts b/js-cookie/index.d.ts index a00b2d5272..a54f4f4864 100644 --- a/js-cookie/index.d.ts +++ b/js-cookie/index.d.ts @@ -91,6 +91,5 @@ declare namespace Cookies { declare var Cookies: Cookies.CookiesStatic; -declare module 'js-cookie' { - export = Cookies; -} +export = Cookies; +export as namespace Cookies; diff --git a/js-cookie/js-cookie-tests.ts b/js-cookie/js-cookie-tests.ts index 2b5dfc8a5e..3b2509fe8a 100644 --- a/js-cookie/js-cookie-tests.ts +++ b/js-cookie/js-cookie-tests.ts @@ -1,3 +1,4 @@ +import Cookies = require("js-cookie"); // Create a cookie, valid across the entire site Cookies.set('name', 'value'); diff --git a/js-data/js-data-tests.ts b/js-data/js-data-tests.ts index 1cd2141eab..596e0077df 100644 --- a/js-data/js-data-tests.ts +++ b/js-data/js-data-tests.ts @@ -1,4 +1,4 @@ - +import JSData = require("js-data"); interface IUser { id?: number; diff --git a/js-yaml/index.d.ts b/js-yaml/index.d.ts index dca80dc228..1ac7b6ec26 100644 --- a/js-yaml/index.d.ts +++ b/js-yaml/index.d.ts @@ -80,6 +80,5 @@ declare namespace jsyaml { } } -declare module 'js-yaml' { - export = jsyaml; -} +export = jsyaml; +export as namespace jsyaml; diff --git a/jsen/index.d.ts b/jsen/index.d.ts index 19407c849f..7be072ab1a 100644 --- a/jsen/index.d.ts +++ b/jsen/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Vladimir Đokić // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Jsen { +declare namespace Jsen { export interface JsenFormats { [key: string]: string | RegExp | Function; @@ -46,7 +46,6 @@ declare module Jsen { } } -declare module "jsen" { - var _jsen: Jsen.JsenMain; - export = _jsen; -} +declare var Jsen: Jsen.JsenMain; +export = Jsen; +export as namespace jsen; diff --git a/jsen/jsen-tests.ts b/jsen/jsen-tests.ts index aed6db6246..16cded3688 100644 --- a/jsen/jsen-tests.ts +++ b/jsen/jsen-tests.ts @@ -1,5 +1,5 @@ import jsen = require("jsen"); -import JsenSettings = Jsen.JsenSettings; +import JsenSettings = jsen.JsenSettings; // any { diff --git a/json-patch/index.d.ts b/json-patch/index.d.ts index cbe2add41c..bb70cff6c6 100644 --- a/json-patch/index.d.ts +++ b/json-patch/index.d.ts @@ -36,6 +36,5 @@ declare namespace jsonpatch { function compile(patches: OpPatch[]): (document: any) => any; } -declare module "json-patch" { - export = jsonpatch; -} +export = jsonpatch; +export as namespace jsonpatch; diff --git a/jssha/index.d.ts b/jssha/index.d.ts index 18b41beebd..45d6686aed 100644 --- a/jssha/index.d.ts +++ b/jssha/index.d.ts @@ -80,6 +80,5 @@ declare namespace jsSHA { } declare var jsSHA: jsSHA.jsSHA; -declare module 'jssha' { - export = jsSHA; -} +export = jsSHA; +export as namespace jsSHA; diff --git a/jssha/jssha-tests.ts b/jssha/jssha-tests.ts index 1a77e401eb..a6869d6a22 100644 --- a/jssha/jssha-tests.ts +++ b/jssha/jssha-tests.ts @@ -4,11 +4,11 @@ import imported = require("jssha"); // constructor -let shaObj1:jsSHA.jsSHA = new imported("SHA-512", "TEXT"); -let shaObj2:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { }); -let shaObj3:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { encoding: "UTF8" }); -let shaObj4:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { numRounds: 1 }); -let shaObj5:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { encoding: "UTF8", numRounds: 1 }); +let shaObj1 = new imported("SHA-512", "TEXT"); +let shaObj2 = new imported("SHA-512", "TEXT", { }); +let shaObj3 = new imported("SHA-512", "TEXT", { encoding: "UTF8" }); +let shaObj4 = new imported("SHA-512", "TEXT", { numRounds: 1 }); +let shaObj5 = new imported("SHA-512", "TEXT", { encoding: "UTF8", numRounds: 1 }); // setHMACKey shaObj1.setHMACKey("key", "TEXT"); @@ -50,7 +50,7 @@ let hmac5:string = shaObj1.getHMAC("HEX", { outputUpper: true, b64Pad: '=' }); // Browser global test { - var shaObj = new jsSHA("SHA-512", "TEXT"); + var shaObj = new imported("SHA-512", "TEXT"); shaObj.update("This is a test"); var hash = shaObj.getHash("HEX"); } \ No newline at end of file diff --git a/jwt-decode/index.d.ts b/jwt-decode/index.d.ts index 61ce1ec7cf..5cf3772b68 100644 --- a/jwt-decode/index.d.ts +++ b/jwt-decode/index.d.ts @@ -10,7 +10,6 @@ declare namespace JwtDecode { } } -declare module 'jwt-decode' { - var jwtDecode: JwtDecode.JwtDecodeStatic; - export = jwtDecode; -} +declare var jwtDecode: JwtDecode.JwtDecodeStatic; +export = jwtDecode; +export as namespace jwt_decode; \ No newline at end of file diff --git a/keyboardjs/index.d.ts b/keyboardjs/index.d.ts index 820101dd67..a1249645d4 100644 --- a/keyboardjs/index.d.ts +++ b/keyboardjs/index.d.ts @@ -126,7 +126,6 @@ declare namespace keyboardjs { */ export function stop(): void; } - -declare module 'keyboardjs' { - export = keyboardjs; -} + +export = keyboardjs; +export as namespace keyboardJS; diff --git a/koa-mount/index.d.ts b/koa-mount/index.d.ts index b1025d54df..9c79156406 100644 --- a/koa-mount/index.d.ts +++ b/koa-mount/index.d.ts @@ -4,19 +4,17 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "koa-mount" { +import * as Koa from "koa"; - import * as Koa from "koa"; +interface Function { (ctx: Koa.Context, next?: () => any): any } - interface Function { (ctx: Koa.Context, next?: () => any): any } +declare function mount(app: Function): Function; - function mount(app: Function): Function; +declare function mount(app: Koa): Function; - function mount(app: Koa): Function; +declare function mount(prefix: string, app: Function): Function; - function mount(prefix: string, app: Function): Function; +declare function mount(prefix: string, app: Koa): Function; - function mount(prefix: string, app: Koa): Function; +export = mount; - export = mount; -} diff --git a/latinize/index.d.ts b/latinize/index.d.ts index 129a7a5aec..f1cfffeb85 100644 --- a/latinize/index.d.ts +++ b/latinize/index.d.ts @@ -11,7 +11,6 @@ declare namespace LatinizeModule { } -declare module "latinize" { - let latinize: LatinizeModule.Latinize; - export = latinize; -} +declare var latinize: LatinizeModule.Latinize; +export = latinize; +export as namespace latinize; diff --git a/lestate/index.d.ts b/lestate/index.d.ts index f03a4249a2..c606b93c36 100644 --- a/lestate/index.d.ts +++ b/lestate/index.d.ts @@ -22,6 +22,4 @@ declare let LeState : { }; }; -declare module "lestate" { - export default LeState; -} +export = LeState; diff --git a/lestate/lestate-tests.ts b/lestate/lestate-tests.ts index 05b5a5cf7c..3c2b074d2d 100644 --- a/lestate/lestate-tests.ts +++ b/lestate/lestate-tests.ts @@ -1,3 +1,4 @@ +import LeState = require("lestate"); let State = LeState.createState() State.set({ diff --git a/lls/index.d.ts b/lls/index.d.ts index ee7091209b..6b6b80df8c 100644 --- a/lls/index.d.ts +++ b/lls/index.d.ts @@ -121,7 +121,6 @@ declare namespace LargeLocalStorageInterfaces { } } -declare module "lls" { - var LargeLocalStorage: LargeLocalStorageInterfaces.LargeLocalStorageService; - export = LargeLocalStorage; -} +declare var LargeLocalStorage: LargeLocalStorageInterfaces.LargeLocalStorageService; +export = LargeLocalStorage; +export as namespace LargeLocalStorage; diff --git a/long/index.d.ts b/long/index.d.ts index 514eb5677a..b73d7f00f6 100644 --- a/long/index.d.ts +++ b/long/index.d.ts @@ -347,7 +347,7 @@ declare class Long xor( other: Long | number | string ): Long; } -declare module 'long' { - namespace Long {} - export = Long; -} +declare namespace Long {} +export = Long; +export as namespace Long; + \ No newline at end of file diff --git a/lovefield/index.d.ts b/lovefield/index.d.ts index 230b11a6b0..5e9b7061e7 100644 --- a/lovefield/index.d.ts +++ b/lovefield/index.d.ts @@ -228,6 +228,5 @@ declare namespace lf { } // module lf -declare module 'lovefield' { - export = lf; -} +export = lf; +export as namespace lf; diff --git a/lovefield/lovefield-tests.ts b/lovefield/lovefield-tests.ts index 3e239d6f93..11b67cab03 100644 --- a/lovefield/lovefield-tests.ts +++ b/lovefield/lovefield-tests.ts @@ -1,3 +1,4 @@ +import lf = require("lovefield"); function main(): void { var schemaBuilder: lf.schema.Builder = lf.schema.create('todo', 1); diff --git a/mapsjs/index.d.ts b/mapsjs/index.d.ts index 92fdcebf7c..b66315203d 100644 --- a/mapsjs/index.d.ts +++ b/mapsjs/index.d.ts @@ -7,2711 +7,2711 @@ * Mapsjs 9.6.0 Copyright (c) 2013 ISC. All Rights Reserved. */ -declare module 'mapsjs' { - /** - * Clusters a set of points. - * @param {object} options An options object which specifies the clustering algorithm. - * @returns {object} An array of clustered points. - */ - export function clusterPoints(options: { - data: {}[]; - pointKey: string; - valueFunction?: (row: any) => number; - radiusFunction: (row: any) => number; - aggregateFunction?: (srcRow: any, cmpRow: any, aggRow: any) => void; - mapUnitsPerPixel: number; - marginPixels?: number; - }): {}[]; + +/** + * Clusters a set of points. + * @param {object} options An options object which specifies the clustering algorithm. + * @returns {object} An array of clustered points. + */ +export function clusterPoints(options: { + data: {}[]; + pointKey: string; + valueFunction?: (row: any) => number; + radiusFunction: (row: any) => number; + aggregateFunction?: (srcRow: any, cmpRow: any, aggRow: any) => void; + mapUnitsPerPixel: number; + marginPixels?: number; +}): {}[]; + +/** + * An immutable envelope + * @class envelope + */ +export class envelope { + constructor(minX: number, minY: number, maxX: number, maxY: number); /** - * An immutable envelope - * @class envelope + * Gets the minimum x coordinate of the envelope. + * @returns {number} The minimum x coordinate. + */ + getMinX(): number; + + /** + * Gets the minimum y coordinate of the envelope + * @returns {number} The minimum y coordinate. */ - export class envelope { - constructor(minX: number, minY: number, maxX: number, maxY: number); - - /** - * Gets the minimum x coordinate of the envelope. - * @returns {number} The minimum x coordinate. - */ - getMinX(): number; - - /** - * Gets the minimum y coordinate of the envelope - * @returns {number} The minimum y coordinate. - */ - getMinY(): number; - - /** - * Gets the maximum x coordinate of the envelope - * @returns {number} The maximum x coordinate. - */ - getMaxX(): number; - - /** - * Gets the maximum y coordinate of the envelope - * @returns {number} The maximum y coordinate. - */ - getMaxY(): number; - - /** - * Creates a new envelope from this as deep copy. - * @returns {envelope} The new cloned envelope. - */ - clone(): envelope; - - /** - * Creates a new envelope from this one plus x and y margins. - * @param {number} marginX The x margin. - * @param {number} marginY The y margin. - * @returns {envelope} A new envelope. - */ - createFromMargins(marginX: number, marginY: number): envelope; - - /** - * Create a new envelope from this one plus a bleed ratio. - * @param {number} bleed The bleed ratio. - * @returns {envelope} A new envelope. - */ - createFromBleed(bleed: number): envelope; - - /** - * Gets the center point of the envelope. - * @returns {point} Center as a point. - */ - getCenter(): point; - - /** - * Gets the width of the envelope. - * @returns {number} Width of the envelope. - */ - getWidth(): number; - - /** - * Gets height of the envelope. - * @returns {number} Height of the envelope. - */ - getHeight(): number; - - /** - * Gets area of the envelope. - * @return {number} Area of the envelope. - */ - getArea(): number; - - /** - * Returns the minimum and maximum coordinates of this envelope as an envObject. - * @returns {envObject} Representaton of this envelope as an envObject. - */ - toObject(): envObject; - - /** - * Gets upper left coordinate of this envelope. - * @returns {point} A new point. - */ - getUL(): point; - - /** - * Gets upper right of this envelope. - * @returns {point} A new point. - */ - getUR(): point; - - /** - * Gets lower left of this envelope. - * @returns {point} A new point. - */ - getLL(): point; - - /** - * Gets lower right of this envelope. - * @returns {point} A new point. - */ - getLR(): point; - - /** - * Gets the aspect of the envelope. - * @returns {number} Width-to-height ratio. - */ - getAspect(): number; - - /** - * Equality comparer between this and another envelope. - * @param {envelope} env Envelope to compare. - * @return {boolean} Result of equality comparison. - */ - equals(env: envelope): boolean; - - /** - * Method for casting this envelope as a string. - * @returns {string} String of the form 'minX,minY,maxX,maxY'. - */ - toString(): string; - - /** - * Create a closed geometry from this envelope. - * @returns {geometry} A new closed path geometry. - */ - toGeometry(): geometry; - - /** - * Tests whether the given point is contained within this envelope. - * @param {point} pt Point to test. - * @returns {boolean} Result of containment test. - */ - contains(pt: point): boolean; - } - - /** - * Exposes static functions that act on or return envelopes. - * @module envelope - */ - export module envelope { + getMinY(): number; + /** + * Gets the maximum x coordinate of the envelope + * @returns {number} The maximum x coordinate. + */ + getMaxX(): number; + + /** + * Gets the maximum y coordinate of the envelope + * @returns {number} The maximum y coordinate. + */ + getMaxY(): number; + + /** + * Creates a new envelope from this as deep copy. + * @returns {envelope} The new cloned envelope. + */ + clone(): envelope; + + /** + * Creates a new envelope from this one plus x and y margins. + * @param {number} marginX The x margin. + * @param {number} marginY The y margin. + * @returns {envelope} A new envelope. + */ + createFromMargins(marginX: number, marginY: number): envelope; + + /** + * Create a new envelope from this one plus a bleed ratio. + * @param {number} bleed The bleed ratio. + * @returns {envelope} A new envelope. + */ + createFromBleed(bleed: number): envelope; + + /** + * Gets the center point of the envelope. + * @returns {point} Center as a point. + */ + getCenter(): point; + + /** + * Gets the width of the envelope. + * @returns {number} Width of the envelope. + */ + getWidth(): number; + + /** + * Gets height of the envelope. + * @returns {number} Height of the envelope. + */ + getHeight(): number; + + /** + * Gets area of the envelope. + * @return {number} Area of the envelope. + */ + getArea(): number; + + /** + * Returns the minimum and maximum coordinates of this envelope as an envObject. + * @returns {envObject} Representaton of this envelope as an envObject. + */ + toObject(): envObject; + + /** + * Gets upper left coordinate of this envelope. + * @returns {point} A new point. + */ + getUL(): point; + + /** + * Gets upper right of this envelope. + * @returns {point} A new point. + */ + getUR(): point; + + /** + * Gets lower left of this envelope. + * @returns {point} A new point. + */ + getLL(): point; + + /** + * Gets lower right of this envelope. + * @returns {point} A new point. + */ + getLR(): point; + + /** + * Gets the aspect of the envelope. + * @returns {number} Width-to-height ratio. + */ + getAspect(): number; + + /** + * Equality comparer between this and another envelope. + * @param {envelope} env Envelope to compare. + * @return {boolean} Result of equality comparison. + */ + equals(env: envelope): boolean; + + /** + * Method for casting this envelope as a string. + * @returns {string} String of the form 'minX,minY,maxX,maxY'. + */ + toString(): string; + + /** + * Create a closed geometry from this envelope. + * @returns {geometry} A new closed path geometry. + */ + toGeometry(): geometry; + + /** + * Tests whether the given point is contained within this envelope. + * @param {point} pt Point to test. + * @returns {boolean} Result of containment test. + */ + contains(pt: point): boolean; +} + +/** + * Exposes static functions that act on or return envelopes. + * @module envelope + */ +export module envelope { + + /** + * Creates a new envelope from MapDotNet XML. + * @param {string} xml A MapDotNet XML string of the envelope. + * @returns {envelope} A new envelope + */ + export function createFromMdnXml(xml: string): envelope; + + /** + * Creates new envelope from two corner points. + * @param {point} pt1 Corner point + * @param {point} pt2 Opposite corner point + * @returns {envelope} A new envelope + */ + export function createFromPoints(pt1: point, pt2: point): envelope; + + /** + * Creates a new envelope from the x and y coordinates of the center + * point and x and y margins from the center point. + * @param {number} centerPtX The center x coordinate. + * @param {number} centerPtY The center y coordinate. + * @param {number} marginX The margin from center x coordinate. + * @param {number} marginY The margin from center y coordinate. + * @returns {envelope} A new envelope + */ + export function createFromCenterAndMargins(centerPtX: number, centerPtY: number, marginX: number, marginY: number): envelope; + + /** + * Tests whether two given envelopes intersect. + * @param {envelope} env1 First envelope to test. + * @param {envelope} env2 Second envelope to test. + * @returns {boolean} Result of the intersection test. + */ + export function intersects(env1: envelope, env2: envelope): boolean; + + /** + * Creates a new envelope from the union of two given envelopes. + * @param {envelope} env1 The first enevelope to unite. + * @param {envelope} env2 The second envelope to unite. + * @returns {envelope} A new envelope. + */ + export function union(env1: envelope, env2: envelope): envelope; +} + +/** + * A general geometry which can represent a point, line, polygon, + * mulitpoint, multilinestring + * @class geometry + */ +export class geometry { + constructor(isPath?: boolean, isClosed?: boolean); + + /** + * Creates a new polygon or polyline form the geometry according to + * whether the geometry is closed. + * @returns {any} A new polyline or polygon geometry. + */ + factoryPoly(): any; + + /** + * Creates a deep copy of this geometry. + * @returns {geometry} The new cloned geometry. + */ + clone(): geometry; + + /** + * Iterates every vertex in the geometry and passes to the supplied + * callback. Return true from in the callback will break the iteration. + * @param {function} action Callback with the signature action(setIdx, idx, x, y, set). + */ + foreachVertex(action: (setIdx: number, idx: number, x: number, y: number, s: number[]) => void): void; + + /** + * Returns the geometry's bounding box as an envelope. + * @returns {envelope} The bounding box of the geometry as an envelope. + */ + getBounds(): envelope; + + /** + * Checks whether or not this geometry is closed. + * @returns {boolean} Result of the path check. + */ + getIsPath(): boolean; + + /** + * Checks whether or not this geometry is closed. + * @returns {boolean} Result of the closed check. + */ + getIsClosed(): boolean; + + /** + * Gets the number of sets in this geometry. + * @returns {number} Number of sets. + */ + getSetCount(): number; + + /** + * Gets a set from this geometry's set collection by index, or, if no + * index is provided, gets the last set. Note: for polygons, first set + * is primary ring and subsequent ones are holes. + * @param {number} [idx] Index of the set to return. + * @returns {number[]} A set as an array of points in the form [xn,yn]. + */ + getSet(idx: number): number[]; + + /** + * Adds a new set to this geometry's collection of sets. + * @param {number[]} s Set to add as an array of points in the form [xn,yn]. + */ + pushSet(s: number[]): void; + + /** + * Gets the last set in the geometry's set collection and removes it + * from the collection. + * @returns {number} Set removed as an array of points in the form [xn,yn]. + */ + popSet(): number[]; + + /** + * Creates SVG path data from this geometry if it is a path. + * @returns {string} String of the SVG path or null the geometry is not a path. + */ + toSvgPathData(): string; + + /** + * Adds point to the last set in geometry's set collection. If the + * geometry is empty, a new set is added to the geometry first. + * @param {point} pt The point to add. + * @returns {object} Object of the form {setIdx, idx} where setIdx is + * the 0-based index of the set the point was added to and idx is the + * 0-based index of the point in its set. + */ + addPointToLastSet(pt: point): { setIdx: number; idx: number; }; + + /** + * Tests the validity of this geometry. An open path geometry is valid + * if it has at least one set with at least two points. A closed + * geometry is valid if it has at least one set with at least three + * points. A point (non-path) geometry is always valid. + * @returns {geometry} valid geometry is true, otherwise false. + */ + isValid(): boolean; + + /** + * Creates a wkt string from this geometry. + * @returns {string} A string of well known text. + */ + toString(): string; + toWkt(): string; + + /** + * Finds the point in this geometry nearest to the given point. + * @param {point} pt Reference point. + * @returns {object} An object of the form {setIdx, ptIdx, pt, distance} + * where setIdx is the index of the set the point is in, ptIdx is the + * index of the point in the set, pt is the point object, and distance + * is the distance of the point to the reference point in map units. + */ + findNearestVertex(pt: point): { setIdx: number; ptIdx: number; pt: point; distance: number; }; + + /** + * Finds point along boundary of geometry nearest to the given point + * @param {point} pt Reference point. + * @param {boolean} [close] Flag to indicate whether this geometry + * should be treated as a closed geometry. + * @returns {object} An object of the form {setIdx, ptIdx, pt, distance} + * where setIdx is the index of the set the point is in, ptIdx is the + * index of the point in the set, pt is the point object, and distance + * is the distance of the point to the reference point in map units. + */ + findNearestSegment(pt: point, close?: boolean): { setIdx: number; ptIdx: number; pt: point; distance: number; }; + + /** + * Finds coordinates in map units of the midpoint of this geometry. If + * this geometry is an open path, the midpoint is the midpoint of the + * path. If this geometry is a closed path, the midpoint is the centroid + * of the polygon. If a set index is not provided, finds the labeling + * point for the last set in this geometry's set collection. + * @param {number} [idx] Index of set for which to find the labeling point. + * @returns {point} Midpoint of this geometry. + */ + getLabelingPoint(idx?: number): point; + + /** + * Tests whether this geometry contains a given point/ + * @param {point} pt The reference point. + * @returns {boolean} Result of the containment test. + */ + contains(pt: point): boolean; +} + +/** + * Exposes static functions that act on or return geometries, including + * constructors for specific geometries such as polygon and polyline. + * @module geometry + */ +export module geometry { + + /** + * A polyline object which is an open path geometry with one or more paths. + * @class polyline + */ + class polyline extends geometry { + constructor(geom: geometry); + /** - * Creates a new envelope from MapDotNet XML. - * @param {string} xml A MapDotNet XML string of the envelope. - * @returns {envelope} A new envelope + * Gets the underlying geometry of the polyline. + * @returns {geometry} The polyline's underlying geometry object. */ - export function createFromMdnXml(xml: string): envelope; + getGeometry(): geometry; /** - * Creates new envelope from two corner points. - * @param {point} pt1 Corner point - * @param {point} pt2 Opposite corner point - * @returns {envelope} A new envelope + * Creates a new polyline object from a deep copy of the underlying geometry. + * @returns {polyline} Thew new cloned polyline. */ - export function createFromPoints(pt1: point, pt2: point): envelope; + clone(): polyline; /** - * Creates a new envelope from the x and y coordinates of the center - * point and x and y margins from the center point. - * @param {number} centerPtX The center x coordinate. - * @param {number} centerPtY The center y coordinate. - * @param {number} marginX The margin from center x coordinate. - * @param {number} marginY The margin from center y coordinate. - * @returns {envelope} A new envelope + * Gets number of lines in this polyline. + * @returns {number} Number of lines. */ - export function createFromCenterAndMargins(centerPtX: number, centerPtY: number, marginX: number, marginY: number): envelope; + getLineCount(): number; /** - * Tests whether two given envelopes intersect. - * @param {envelope} env1 First envelope to test. - * @param {envelope} env2 Second envelope to test. + * Gets a line from this polyline's liune collection by index, or, + * if no index is provided, gets the last line. + * @param {number} [idx] Index of the line to return. + * @returns {number[]} A line as an array of points in the form [xn,yn]. + */ + getLine(idx: number): number[]; + + /** + * Adds a new line to this polyline's line collection. + * @param {number[]} s Line to add as an array of points in the form [xn,yn]. + */ + pushLine(s: number[]): void; + + /** + * Gets the last line in the polyline's set collection and removes it + * from the collection. + * @returns {number} Line removed as an array of points in the form [xn,yn]. + */ + popLine(): number[]; + + /** + * Calculates distance of a line in a polyline by index according + * to projected map cooordinates. If no index is provided, uses + * the last line in the polyline's set collection. + * @param {number} [idx] Index of the line for which to compute the distance. + * @returns {number} Length in projected units of the distance of the line. + */ + getProjectedDistance(idx: number): number; + + /** + * Calculates distance of a line in a polyline by index according + * to actual distance. If no index is provided, uses the last line + * in the polyline's set collection. + * @param {number} [idx] Index of the line for which to compute the distance. + * @returns {number} Distance in meters of the line. + */ + getActualDistance(idx?: number): number; + + /** + * Determines whether this polyline intersects a given geometry. + * @param {geometry} geom Geometry to test against. * @returns {boolean} Result of the intersection test. */ - export function intersects(env1: envelope, env2: envelope): boolean; - - /** - * Creates a new envelope from the union of two given envelopes. - * @param {envelope} env1 The first enevelope to unite. - * @param {envelope} env2 The second envelope to unite. - * @returns {envelope} A new envelope. - */ - export function union(env1: envelope, env2: envelope): envelope; - } - - /** - * A general geometry which can represent a point, line, polygon, - * mulitpoint, multilinestring - * @class geometry - */ - export class geometry { - constructor(isPath?: boolean, isClosed?: boolean); - - /** - * Creates a new polygon or polyline form the geometry according to - * whether the geometry is closed. - * @returns {any} A new polyline or polygon geometry. - */ - factoryPoly(): any; - - /** - * Creates a deep copy of this geometry. - * @returns {geometry} The new cloned geometry. - */ - clone(): geometry; - - /** - * Iterates every vertex in the geometry and passes to the supplied - * callback. Return true from in the callback will break the iteration. - * @param {function} action Callback with the signature action(setIdx, idx, x, y, set). - */ - foreachVertex(action: (setIdx: number, idx: number, x: number, y: number, s: number[]) => void): void; - - /** - * Returns the geometry's bounding box as an envelope. - * @returns {envelope} The bounding box of the geometry as an envelope. - */ - getBounds(): envelope; - - /** - * Checks whether or not this geometry is closed. - * @returns {boolean} Result of the path check. - */ - getIsPath(): boolean; - - /** - * Checks whether or not this geometry is closed. - * @returns {boolean} Result of the closed check. - */ - getIsClosed(): boolean; - - /** - * Gets the number of sets in this geometry. - * @returns {number} Number of sets. - */ - getSetCount(): number; - - /** - * Gets a set from this geometry's set collection by index, or, if no - * index is provided, gets the last set. Note: for polygons, first set - * is primary ring and subsequent ones are holes. - * @param {number} [idx] Index of the set to return. - * @returns {number[]} A set as an array of points in the form [xn,yn]. - */ - getSet(idx: number): number[]; - - /** - * Adds a new set to this geometry's collection of sets. - * @param {number[]} s Set to add as an array of points in the form [xn,yn]. - */ - pushSet(s: number[]): void; - - /** - * Gets the last set in the geometry's set collection and removes it - * from the collection. - * @returns {number} Set removed as an array of points in the form [xn,yn]. - */ - popSet(): number[]; - - /** - * Creates SVG path data from this geometry if it is a path. - * @returns {string} String of the SVG path or null the geometry is not a path. - */ - toSvgPathData(): string; - - /** - * Adds point to the last set in geometry's set collection. If the - * geometry is empty, a new set is added to the geometry first. - * @param {point} pt The point to add. - * @returns {object} Object of the form {setIdx, idx} where setIdx is - * the 0-based index of the set the point was added to and idx is the - * 0-based index of the point in its set. - */ - addPointToLastSet(pt: point): { setIdx: number; idx: number; }; - - /** - * Tests the validity of this geometry. An open path geometry is valid - * if it has at least one set with at least two points. A closed - * geometry is valid if it has at least one set with at least three - * points. A point (non-path) geometry is always valid. - * @returns {geometry} valid geometry is true, otherwise false. - */ - isValid(): boolean; - - /** - * Creates a wkt string from this geometry. - * @returns {string} A string of well known text. - */ - toString(): string; - toWkt(): string; - - /** - * Finds the point in this geometry nearest to the given point. - * @param {point} pt Reference point. - * @returns {object} An object of the form {setIdx, ptIdx, pt, distance} - * where setIdx is the index of the set the point is in, ptIdx is the - * index of the point in the set, pt is the point object, and distance - * is the distance of the point to the reference point in map units. - */ - findNearestVertex(pt: point): { setIdx: number; ptIdx: number; pt: point; distance: number; }; - - /** - * Finds point along boundary of geometry nearest to the given point - * @param {point} pt Reference point. - * @param {boolean} [close] Flag to indicate whether this geometry - * should be treated as a closed geometry. - * @returns {object} An object of the form {setIdx, ptIdx, pt, distance} - * where setIdx is the index of the set the point is in, ptIdx is the - * index of the point in the set, pt is the point object, and distance - * is the distance of the point to the reference point in map units. - */ - findNearestSegment(pt: point, close?: boolean): { setIdx: number; ptIdx: number; pt: point; distance: number; }; - - /** - * Finds coordinates in map units of the midpoint of this geometry. If - * this geometry is an open path, the midpoint is the midpoint of the - * path. If this geometry is a closed path, the midpoint is the centroid - * of the polygon. If a set index is not provided, finds the labeling - * point for the last set in this geometry's set collection. - * @param {number} [idx] Index of set for which to find the labeling point. - * @returns {point} Midpoint of this geometry. - */ - getLabelingPoint(idx?: number): point; - - /** - * Tests whether this geometry contains a given point/ - * @param {point} pt The reference point. - * @returns {boolean} Result of the containment test. - */ - contains(pt: point): boolean; - } - - /** - * Exposes static functions that act on or return geometries, including - * constructors for specific geometries such as polygon and polyline. - * @module geometry - */ - export module geometry { - - /** - * A polyline object which is an open path geometry with one or more paths. - * @class polyline - */ - class polyline extends geometry { - constructor(geom: geometry); - - /** - * Gets the underlying geometry of the polyline. - * @returns {geometry} The polyline's underlying geometry object. - */ - getGeometry(): geometry; - - /** - * Creates a new polyline object from a deep copy of the underlying geometry. - * @returns {polyline} Thew new cloned polyline. - */ - clone(): polyline; - - /** - * Gets number of lines in this polyline. - * @returns {number} Number of lines. - */ - getLineCount(): number; - - /** - * Gets a line from this polyline's liune collection by index, or, - * if no index is provided, gets the last line. - * @param {number} [idx] Index of the line to return. - * @returns {number[]} A line as an array of points in the form [xn,yn]. - */ - getLine(idx: number): number[]; - - /** - * Adds a new line to this polyline's line collection. - * @param {number[]} s Line to add as an array of points in the form [xn,yn]. - */ - pushLine(s: number[]): void; - - /** - * Gets the last line in the polyline's set collection and removes it - * from the collection. - * @returns {number} Line removed as an array of points in the form [xn,yn]. - */ - popLine(): number[]; - - /** - * Calculates distance of a line in a polyline by index according - * to projected map cooordinates. If no index is provided, uses - * the last line in the polyline's set collection. - * @param {number} [idx] Index of the line for which to compute the distance. - * @returns {number} Length in projected units of the distance of the line. - */ - getProjectedDistance(idx: number): number; - - /** - * Calculates distance of a line in a polyline by index according - * to actual distance. If no index is provided, uses the last line - * in the polyline's set collection. - * @param {number} [idx] Index of the line for which to compute the distance. - * @returns {number} Distance in meters of the line. - */ - getActualDistance(idx?: number): number; - - /** - * Determines whether this polyline intersects a given geometry. - * @param {geometry} geom Geometry to test against. - * @returns {boolean} Result of the intersection test. - */ - intersects(geom: geometry): boolean; - } - - /** - * A polyline object which is a closed path geometry with one or more paths. - * @class polygon - */ - class polygon extends geometry { - constructor(geom: geometry); - - /** - * Gets the underlying geometry of the polygon. - * @returns {geometry} The polygon's underlying geometry object. - */ - getGeometry(): geometry; - - /** - * Creates a new polygon object from a deep copy of the underlying geometry. - * @returns {polygon} Thew new cloned polygon. - */ - clone(): polygon; - - /** - * Gets number of rings in this polygon. - * @returns {number} Number of rings. - */ - getRingCount(): number; - - /** - * Gets a ring from this polygon's set collection by index, or, - * if no index is provided, gets the last ring. - * @param {number} [idx] Index of the ring to return. - * @returns {number[]} A ring as an array of points in the form [xn,yn]. - */ - getRing(idx: number): number[]; - - /** - * Adds a new ring to this polygon's ring collection. - * @param {number[]} s Ring to add as an array of points in the form [xn,yn]. - */ - pushRing(s: number[]): void; - - /** - * Gets the last ring in the polygon's ring collection and removes it - * from the collection. - * @returns {number} Ring removed as an array of points in the form [xn,yn]. - */ - popRing(): number[]; - - /** - * Calculates area of a ring in a polygon by index according - * to projected map cooordinates. If no index is provided, uses - * the last ring in the polygon's ring collection. - * @param {number} [idx] Index of the ring for which to compute the area. - * @returns {number} Area in square projected units of the ring. - */ - getProjectedArea(idx: number): number; - - /** - * Calculates perimeter of a ring in a polygon by index according - * to projected map cooordinates. If no index is provided, uses - * the last ring in the polygon's ring collection. - * @param {number} [idx] Index of the ring for which to compute the perimeter. - * @returns {number} Length in projected units of the distance of the ring. - */ - getProjectedPerimeter(idx: number): number; - - /** - * Calculates area of a ring in a polygon by index according - * to the actual area. If no index is provided, uses the last ring - * in the polygon's ring collection. - * @param {number} [idx] Index of the ring for which to compute the area. - * @returns {number} Area in square meters of the ring. - */ - getActualArea(idx?: number): number; - - /** - * Calculates perimeter of a ring in a polygon by index according - * to actual distance. If no index is provided, uses the last ring - * in the polygon's ring collection. - * @param {number} [idx] Index of the ring for which to compute the perimeter. - * @returns {number} Length in meters of the perimeter of the ring. - */ - getActualPerimeter(idx?: number): number; - - /** - * Determines whether this polygon intersects a given geometry. - * @param {geometry} geom Geometry to test against. - * @returns {boolean} Result of the intersection test. - */ - intersects(geom: geometry): boolean; - - /** - * Determines whether this polyline overlaps a given geometry. - * @param {geometry} geom Geometry to test against. - * @returns {boolean} Result of the intersection test. - */ - overlaps(poly: polygon): boolean; - - /** - * Convert this polygon into an array of OGC compliant polygons where - * the first set is a ring and all subsequent contained sets are holes. - * @returns {polygon[]} An array of OGC polygons. - */ - toMultiPolygon(): polygon[]; - } - } - - /** - * A style specification for geometry objects. - * @class geometryStyle - */ - export class geometryStyle { - constructor(options?: styleObj); - - /** - * Gets path outline thickness in pixels. - * @returns {number} Thickness of path outline. - */ - getOutlineThicknessPix(): number; - - /** - * Sets path outline thickness in pixels. - * @param {number} t Desired thickness. - */ - setOutlineThicknessPix(t: number): void; - - /** - * Gets path outline color as a CSS style string. - * @returns {string} Outline color as a CSS style string. - */ - getOutlineColor(): string; - - /** - * Sets path outline color from a CSS style string. - * @param {string} c Outline color as a CSS style string. - */ - setOutlineColor(c: string): void; - - /** - * Gets path outline opacity in decimal format. - * @returns {number} Outline opacity. - */ - getOutlineOpacity(): number; - - /** - * Set path outline opacity to a decimal between 0 and 1. - * @param {number} o Outline opacity. - */ - setOutlineOpacity(o: number): void; - - /** - * Gets fill color as a CSS style string. - * @returns {string} Fill color as a CSS style string. - */ - getFillColor(): string; - - /** - * Sets fill color as a CSS style string. - * @param {string} c Fill color as a CSS style string. - */ - setFillColor(c: string): void; - - /** - * Gets fill opacity in decimal format. - * @returns {number} Fill opacity. - */ - getFillOpacity(): number; - - /** - * Sets fill opacity to a decimal between 0 and 1. - * @param {number} o Fill opacity. - */ - setFillOpacity(o: number): void; - - /** - * Gets the dash array as a string. - * @returns {string} Dash array as astring. - */ - getDashArray(): string; - - /** - * Sets dash array string from a CSS style string. Defaults to solid - * stroke if no dash array string is provided. - * @param {string} [da] Dash array as a CSS style string. - */ - setDashArray(da: string): void; - } - - /** - * Gets the mapsjs license. - * @returns {string} The license. - */ - export var license: string; - - /** - * A simple point class with x and y coordinates. - * @class point - */ - export class point { - - constructor(x: number, y: number); - - /** - * Returns the x coordinate. - * @returns {number} The x coordinate. - */ - getX(): number; - - /** - * Returns the y coordinate. - * @returns {number} The y coordinate. - */ - getY(): number; - - /** - * Returns the x and y coordinates of this point as a pointObject. - * @returns {pointObject} Representaton of this point as an pointObject. - */ - toProps(): pointObject; - - /** - * Equality comparer between this point and a given reference point. - * @param {point} pt Reference point. - * @returns {boolean} Result of the equality test. - */ - equals(pt: point): boolean; - - /** - * Creates a point from this point offset by a given x and y distance. - * @param {number} dx The x offset. - * @param {number} dy The y offset. - * @returns {point} The offset point. - */ - createOffsetBy(dx: number, dy: number): point; - - /** - * Creates new n-sided polygon around this point. - * @param {number} sides Number of polygon sides. - * @param {number} radius Distance to polygon points. - * @returns {polygon} The generated polygon. - */ - convertToPoly(side: number, radius: number): geometry.polygon; - - /** - * Gets the wkt representation of this point. - * @returns {string} The well known text for this point. - */ - toString(): string; - - /** - * Creates a deep copy of this point. - * @returns {point} The new cloned point. - */ - clone(): point; - - /** - * Returns this point's bounding box. - * @returns {envelope} The bounding box of the point as an envelope. - */ - getBounds(): envelope; - - /** - * Computes distance between this point and a given point in projected - * map units. - * @param {point} pt Point to which to compute distance. - * @returns {number} Distance from this point to the given point in - * projected map units. - */ - distanceTo(pt: point): number; + intersects(geom: geometry): boolean; } /** - * Exposes static functions that act on points. - * @module point - */ - export module point { - - /** - * Computes the distance between two points in coordinate units. - * @param {number} x1 The x coordinate for the first point. - * @param {number} y1 The y coordinate for the first point. - * @param {number} x2 The x coordinate for the second point. - * @param {number} y2 The y coordinate for the second point. - * @returns {number} Distance in coordinate units. - */ - export function distance(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Computes the midpoint of two points. - * @param {number} x1 The x coordinate for the first point. - * @param {number} y1 The y coordinate for the first point. - * @param {number} x2 The x coordinate for the second point. - * @param {number} y2 The y coordinate for the second point. - * @return {point} Midpoint point. - */ - export function midpoint(x1: number, y1: number, x2: number, y2: number): point; - } - - /** - * Exposes static functions related to the Spherical Mercator projection. - * @module sphericalMercator - */ - export module sphericalMercator { - - /** - * Gets the EPSG number for Spherical Mercator. - * @return {number} ESPG number. - */ - export function getEpsg(): number; - - /** - * Gets the minimum zoom level for this projection. - * @returns {number} Minimum zoom level. - */ - export function getMinZoomLevel(): number; + * A polyline object which is a closed path geometry with one or more paths. + * @class polygon + */ + class polygon extends geometry { + constructor(geom: geometry); /** - * Sets the minimum zoom level for this projection. Normally this is - * set to 1.0 and should not be altered. - * @param {number} minZ Desired minimum zoom level. - */ - export function setMinZoomLevel(minZ: number): void; - - /** - * Gets the maxmimum zoom level for this projection. - * @returns {number} Maximum zoom level. - */ - export function getMaxZoomLevel(): number; - - /** - * Sets the maximum zoom level for this projection. Normally this is - * set to 20.0 and should not be altered. - * @param {number} maxZ1 Desired maximum zoom level. - */ - export function setMaxZoomLevel(maxZ: number): void; - - /** - * Gets the tile height and width in pixels. - * @returns {number} The height and width of the tiles in pixels. - */ - export function getTileSizePix(): number; - - /** - * Gets the display DPI, which defaults to 96. Note: The dpi is - * recomputed on page load complete. - * @returns {number} Dots per inch on display. - */ - export function getDpi(): number; - - /** - * Set the display DPI, which defaults to 96. Note: The DPI is - * recomputed on page load complete. - * @param {number} dpi Dots per inch on display. - */ - export function setDpi(dpi: number): void; - - /** - * Return the equitorial radius in meters for this projection. - * @returns {number} Equitorial radius in meters. - */ - export function getRadius(): number; - - /** - * Returns equitorial circumference in meters for this projection - * @returns {number} Equitorial circumference in meters. - */ - export function getCircumference(): number; - - /** - * Returns half the equitorial circumference in meters for this projection - * @returns {number} Half of the equitorial circumference in meters. - */ - export function getHalfCircumference(): number; - - /** - * Get the envelope in map units for a given quadtree node, i.e. tile, - * based on the given x, y, and z quadtree coordinates. - * @param {number} x The x coordinate. - * @param {number} y The y coordinate. - * @param {number} z The z coordinate. - * @returns {envelope} Envelope of the tile in map units. - */ - export function getQuadTreeNodeToMapEnvelope(x: number, y: number, z: number): envelope; - - /** - * Gets the envelope in map units of tiles in the quadtree from an - * evelope in map units and a zoom level. - * @param {envelope} env Envelope for which to find intersecting tiles. - * @param {number} z Zoom level with which to test for intersection. - * @returns {envelope} The envelope in map units of the tiles. - */ - export function getQuadTreeNodeRangeFromEnvelope(env: envelope, z: number): envelope; - - /** - * Gets projected map units per pixel for a given zoom level. - * @param {number} zoomLevel Reference zoom level. - * @returns {number} Projection units per pixel. - */ - export function getProjectionUnitsPerPixel(zoomLevel: number): number; - - /** - * Gets the required scale transform to apply to shapes so distance - * and area computations yield actual Earth-geodesic units instead of - * projected map units. - * @param {number} mapPtY Reference latitude for the computation. - * @returns {number} Scale transform multiplier. - */ - export function getActualShapeScaleTransform(mapPtY: number): number; - - /** - * Gets actual, on-the-ground meters per pixel for a given zoom level - * and map point in map units. - * @param {point} mapPt Reference location for the computation. - * @param {number} z Reference zoom level. - * @returns {number} Meters per pixel multiplier. - */ - export function getActualUnitsPerPixel(mapPt: point, zoomLevel: number): number; - - /** - * Gets the optimal zoom level for a given envelope in map units - * based on the envelope of visible device area in pixels. - * @param {envelope} envelopeMap Envelope in map units to display. - * @param {envelope} envelopeDevice Envelope in pixels of visible area. - * @returns {number} Optimal zoom level for viewing envelopeMap. - */ - export function getBestFitZoomLevelByExtents(envelopeMap: envelope, envelopeDevice: envelope): number; - - /** - * Gets a quad-key from x, y, and z coordinates. - * @param {number} x The x coordinate. - * @param {number} y The y coordinate. - * @param {number} z The z coordinate. - * @returns {string} Quad-key string. - */ - export function getQuadKeyFromXYZ(x: number, y: number, z: number): string; - - /** - * Gets x, y, and z coordinates as an object from a given quad-key. - * @param {string} key Reference quad-key. - * @return {object} JavaScript object of the form {x,y,z}. - */ - export function getXYZFromQuadKey(key: string): { x: number; y: number; z: number; }; - - /** - * Project a point from latitude/longitude to Spherical Mercator. - * @param {point} lonLat Point object in latitude/longitude. - * @returns {point} The same point in Spherical Mercator. - */ - export function projectFromLatLon(lonLat: point): point; - - /** - * Project a point from Spherical Mercator to latitude/longitude. - * @param {point} mapPt Point object in Spherical Mercator. - * @returns {point} The same point in latitude/longitude. - */ - export function deprojectToLatLon(mapPt: point): point; - } - - /** - * A geometry object decorated with a geometry style object - * @class styledGeometry - */ - export class styledGeometry { - constructor(geom: geometry, gStyle?: geometryStyle); - - /** - * Set this styledGeometry's geometry. - * @param {geometry} g A new Geometry. - */ - setGeometry(g: geometry): void; - - /** - * Set this styledGeometry's geometryStyle. - * @param {geometryStyle} gs A new styledGeometry. - */ - setGeometryStyle(gs: geometryStyle): void; - - /** - * Gets the styledGeometry's underlying geometry object. - * @returns {geometry} The underlying geometry. + * Gets the underlying geometry of the polygon. + * @returns {geometry} The polygon's underlying geometry object. */ getGeometry(): geometry; - - /** - * Gets the styledGeometry's underlying geometryStyle object. - * @returns {geometryStyle} The underlying geometry style. - */ - getGeometryStyle(): geometryStyle; /** - * Gets path outline thickness in pixels. - * @returns {number} Thickness in pixels. + * Creates a new polygon object from a deep copy of the underlying geometry. + * @returns {polygon} Thew new cloned polygon. */ - getOutlineThicknessPix(): number; + clone(): polygon; /** - * Sets path outline thickness in pixels. - * @param {number} t Thickness in pixels. + * Gets number of rings in this polygon. + * @returns {number} Number of rings. */ - setOutlineThicknessPix(t: number): void; - - /** - * Gets path outline color as a CSS style string. - * @returns {string} Outline color as a CSS style string. - */ - getOutlineColor(): string; - - /** - * Gets path outline opacity in decimal format. - * @param {number} Outline opacity. - */ - setOutlineColor(c: string): void; - - /** - * Gets path outline opacity in decimal format. - * @returns {number} Outline opacity. - */ - getOutlineOpacity(): number; - - /** - * Set path outline opacity to a decimal between 0 and 1. - * @param {number} o Outline opacity. - */ - setOutlineOpacity(o: number): void; - - /** - * Gets fill color as a CSS style string. - * @returns {string} Fill color as a CSS style string. - */ - getFillColor(): string; - - /** - * Sets fill color as a CSS style string. - * @param {string} c Fill color as a CSS style string. - */ - setFillColor(c: string): void; - - /** - * Gets fill opacity in decimal format. - * @returns {number} Fill opacity. - */ - getFillOpacity(): number; - - /** - * Sets fill opacity to a decimal between 0 and 1. - * @param {number} o Fill opacity. - */ - setFillOpacity(o: number): void; - - /** - * Gets the dash array as a string. - * @returns {string} Dash array as astring. - */ - getDashArray(): string; - - /** - * Sets dash array string from a CSS style string. Defaults to solid - * stroke if no dash array string is provided. - * @param {string} [da] Dash array as a CSS style string. - */ - setDashArray(da: string): void; - - /** - * Gets optional animation function called when SVG node is created. - * @returns {function} Function with the signature animation(pathElement, loopback). - */ - getAnimation(): (pathElement: HTMLElement, loopback: () => void) => void; - - /** - * You can use the loopback parameter on complete to call itself and - * create repeating animation. - * @param {function} Function with the signature animation(pathElement, loopback). - */ - setAnimation(action: (pathElement: HTMLElement, loopback: () => void) => void): void; - - /** - * Renders this geometry as an SVG path. Note: We attach original - * geometry bounds to svg doc as an expando. - * @param {string} key Identifer to keep track of the SVG DOM element. - * @param {number} mupp Map units per pixel with which to create the SVG element. - * @returns {HTMLElement} A new SVG document root. - */ - createSvgPathElement(key: string, mapUnitsPerPix: number): HTMLElement; - - /** - * Renders this to a canvas context. - * @param {CanvasRenderingContext2D} ctx Canvas context to which to render. - */ - renderPathToCanvasContext(ctx: CanvasRenderingContext2D): void; - } + getRingCount(): number; - /** - * The mapjs version. - */ - export var version: string; - - /** - * Exposes static functions for working with well known text. - * @module wkt - */ - export module wkt { - /** - * Parses WKT as a point. - * @param {string} w A WKT string. - * @returns {point} The parsed point. + * Gets a ring from this polygon's set collection by index, or, + * if no index is provided, gets the last ring. + * @param {number} [idx] Index of the ring to return. + * @returns {number[]} A ring as an array of points in the form [xn,yn]. */ - export function parsePoint(wkt: string): point; + getRing(idx: number): number[]; /** - * Parses WKT as a multipoint. - * @param [string} w A WKT string. - * @retuns {geometry} The parsed multipoint geometry. + * Adds a new ring to this polygon's ring collection. + * @param {number[]} s Ring to add as an array of points in the form [xn,yn]. */ - export function parseMultiPoint(wkt: string): geometry; + pushRing(s: number[]): void; /** - * Parses WKT as an open path geometry with a single set. - * @param {string} w A WKT string. - * @returns {geometry} The parsed open path geometry. + * Gets the last ring in the polygon's ring collection and removes it + * from the collection. + * @returns {number} Ring removed as an array of points in the form [xn,yn]. */ - export function parseLineString(wkt: string): geometry; + popRing(): number[]; /** - * Parses WKT as an open path geometry with multiple sets. - * @param {string} w A WKT string. - * @returns {geometry} The parsed open path geometry. + * Calculates area of a ring in a polygon by index according + * to projected map cooordinates. If no index is provided, uses + * the last ring in the polygon's ring collection. + * @param {number} [idx] Index of the ring for which to compute the area. + * @returns {number} Area in square projected units of the ring. */ - export function parseMultiLineString(wkt: string): geometry; + getProjectedArea(idx: number): number; /** - * Parses WKT as a closed path geometry with a single set. - * @param {string} w A WKT string. - * @returns {geometry} The parsed closed path geometry. + * Calculates perimeter of a ring in a polygon by index according + * to projected map cooordinates. If no index is provided, uses + * the last ring in the polygon's ring collection. + * @param {number} [idx] Index of the ring for which to compute the perimeter. + * @returns {number} Length in projected units of the distance of the ring. */ - export function parsePolygon(wkt: string): geometry; + getProjectedPerimeter(idx: number): number; /** - * Parses WKT as a closed path geometry with multiple sets. - * @param {string} w A WKT string. - * @returns {geometry} The parsed closed path geometry. + * Calculates area of a ring in a polygon by index according + * to the actual area. If no index is provided, uses the last ring + * in the polygon's ring collection. + * @param {number} [idx] Index of the ring for which to compute the area. + * @returns {number} Area in square meters of the ring. */ - export function parseMultiPolygon(wkt: string): geometry; + getActualArea(idx?: number): number; /** - * Parses WKT as a geometry and determines its type from the string. - * @param {string} w The WKT string. - * @returns {any} The parsed shape, a point, geometry, or an array of - * polygons depending on the WKT. + * Calculates perimeter of a ring in a polygon by index according + * to actual distance. If no index is provided, uses the last ring + * in the polygon's ring collection. + * @param {number} [idx] Index of the ring for which to compute the perimeter. + * @returns {number} Length in meters of the perimeter of the ring. */ - export function parse(wkt: string): any; - - /** - * Converts an array of polygons to an OGC compliant multipolygon WKT string. - * @param {polygon[]} polys Set of polygons to parse into WKT. - * @returns {geometry} The OGC compliant WKT for the polygons. - */ - export function toMultiPolygonString(polys: geometry.polygon[]): string; - } - - /** - * Exposes various tile-related constructors, including layers, descriptors, - * and requestors. - * @module tile - */ - export module tile { - - /** - * A tile layer is a view on the map containing an array of rectangular content. - * @class layer - */ - export class layer { - constructor(id: string, useBackdrop?: boolean, maxConcurrentRequests?: number); - - /** - * @param {number} m - number for margin in pixels - */ - // setContentExtentsMarginInPixels(m: number): void; - - /** - * Gets ID associated with this tile layer. - * @returns {string} ID of the layer. - */ - getId(): string; - - /** - * Determines whether this tile layer uses a backdrop. - * @returns {boolean} Whether or not the layer uses a backdrop. - */ - getUseBackdrop(): boolean; - - /** - * Returns the tile layer's descriptor, which describes how - * requested content is rendered or styled. - * @returns {object} The tile layer's descriptor. - */ - getDescriptor(): any; - - /** - * Sets the tile layer's descriptor, which describes how requested - * content is rendered or styled. - * @param {function} d A descriptor for this tile layer. - */ - setDescriptor(d: any): void; - - /** - * Notifies the tile layer to check for changes to its descriptor. - */ - notifyDescriptorChange(): void; - - /** - * Returns this tile layer's requestor which defines what kind of - * content to get and where to get it. - * @returns {requestor} This tile layer's requestor. - */ - getRequestor(): tile.requestor; - - /** - * Sets this tile layer's requestor, which defines what kind of - * content to get and where to get it. - * @param {tile.requestor} req A requestor object. - * @param {tile.requestor} [desc] Descriptor object so that both - * can be set in one call and incur only one content change event. - */ - setRequestor(req: tile.requestor, desc?: any): void; - - /** - * Returns this tile layer's renderer if it exists, which defines - * how geometry data for a quadView is rendered. - * @returns {renderer} The renderer object. - */ - getRenderer(): tile.renderer; - - /** - * Sets optional renderer which defines how geometry data for - * quadView is rendered. - * @param {renderer} r The renderer delegate function with - * signature renderer(quadview). - */ - setRenderer(r: any): void; - - /** - * Notifies the tile layer to check for changes to its renderer. - */ - notifyRendererChange(): void; - - /** - * Gets the visibility state of this tile layer. - * @returns {boolean} Whether or not this layer is visible. - */ - getIsVisible(): boolean; - - /** - * Sets visibility state of this tile layer. - * @param {boolean} v Whether this layer should be visible or not. - */ - setIsVisible(v: boolean): void; - - /** - * Gets the opacity of this tile layer. - * @returns {number} Opacity as a decimal. - */ - getOpacity(): number; - - /** - * Sets opacity of this tile layer. - * @param {number} o Opacity as a decimal. - */ - setOpacity(o: number): void; - - /** - * Gets minimum zoom level where this tile layer is visible. - * @returns {number} The minimum zoom level. - */ - getMinZoomLevel(): number; - - /** - * Sets minimum zoom level where this tile layer is visible. - * @param {number} minZ The desired minimum zoom level. - */ - setMinZoomLevel(minZ: number): void; - - /** - * Gets maximum zoom level where this tile layer is visible. - * @returns {number} The maximum zoom level. - */ - getMaxZoomLevel(): number; - - /** - * Sets maximum zoom level where this tile layer is visible. - * @param {number} maxZ The desired maximum zoom level. - */ - setMaxZoomLevel(maxZ: number): void; - - /** - * Sets pixel bleed on quadTiles, which defaults to 1. Setting this - * to zero for overlay layers with translucent polygon fills is - * recommended. Bleed overlap can create faint lines at tile - * boundries when fill is not opaque. - * @param {number} bleed The number of pixels to bleed. - */ - setTileBleedPix(bleed: number): void; - - /** - * Sets whether or not to retain and display previous level tile - * content as you change tile levels to provide a nice zoom level - * change effect. Once the next level is loaded the old level - * content is always discarded. This should be set to false if there - * is translucent content to display. Defaults to true (prior to - * version 9.0.0001 this value had the same state as useBackdrop.) - * @param {boolean} ret Whether or not to retain interlevel content. - */ - setRetainInterlevelContent(retain: boolean): void; - - /** - * Enables or disables the fade in on tile content, which defaults to enabled. - * @param {boolean} fadeIn Whether or not fade in on tile content - * should be enabled. - */ - setEnableTileFadeIn(fadeIn: boolean): void; - - /** - * Sets the default action to take on error. - * @param {function} action Function to execute on error. - */ - setNotifyErrorAction(action: () => void): void; - - /** - * Sets an optional function to be called when the tile loading - * queue for this layer has emptied. - * @param {function} action Callback function. - */ - setNotifyLoadingQueueHasEmptiedAction(action: () => void): void; - - /** - * Sets the optional function to be called by this layer's tile - * loader during processing. The supplied progress function takes - * tiles loaded and tiles total parameters. - * @param {function} action Callback of the signature action(tileLoaded, tilesTotal). - */ - setNotifyLoadingQueueProgressAction(action: (tilesLoaded: number, tilesTotal: number) => void): void; - - /** - * Sets optional request processor for this tile layer. This is - * an advanced feature allowing developers to tap into tile - * request pipeline for purposes of customizing requests or manage - * custom caching. This is also the mechanism used for offline - * apps with frameworks such as phonegap. - * @param {function} Processor function with signature - * processor(requestor, descriptor, quad, timeoutMs, complete, error) - */ - setRequestProcessor(processorFunc: ( - requestor: tile.requestor, - descriptor: any, - quad: tile.quad, - timeoutMs: number, - completeAction: (img: HTMLElement) => void, - errorAction: (msg: string) => void) => void): void; - - /** - * Instructs the tile loader to populate a specified tile pyramid. - * This is used to fetch content (e.g. bitmap tiles) and preload - * it into the browser cache. - * @param {envelope} extents Envelope for which to fetch content. - * @param {number} startZoomLevel Minimum zoom level for which to - * fetch content. - * @param {number} endZoomLevel Maximum zoom level for which to - * fetch content. - */ - preload(extents: envelope, startZoomLevel: number, endZoomLevel: number): void; - - /** - * Composes an array of quadtiles with composition information and - * requestor endpoints. This can be used to create static images - * or print-ready versions of this tile layer at arbitrary extents - * (both source and target) For example: If you needed a 5x3 inch - * 300 dpi output you can specify extents in device units to be - * 1500x900. This function determines the correct zoom level so - * that the source extents fits in the target extents to the - * nearest integer zoom level. - * @param {envelope} extentsMapUnits Source extents in map units. - * @param {envelope} extentsDeviceUnits Target extents in pixels. - * @returns {object} Composed object in the form - * {quadCollection, endpointCollection, idxMinX, idxMinY, ulX, ulY } - * where quadCollection is an array of quad objects, endpointCollection - * is an array of REST endpoints from which to obtain the tiled content, - * idxMinX and idxMinY are the minimum x and y tile indicies of the - * collection respectively, and ulX and ulY are the offset in pixels - * of the upper left tile from the upper left target extents. - */ - compose(extentsMapUnits: envelope, extentsDeviceUnits: envelope): { - quadCollection: tile.quad[]; - endpointCollection: string[]; - idxMinX: number; - idxMinY: number; - ulX: number; - ulY: number; - }; - - /** - * Unbind all associations with this tile layer to facilitate garbage collection - */ - dispose(): void; - } - - /** - * A layerOptions object is a method for constructing a tile layer for - * immediate use, for example by passing it to the jQuery widget or - * in the knockout binding. - * @class layerOptions - */ - export class layerOptions { - constructor(id: string, options: { - useBackdrop?: boolean; - maxConcurrentRequests?: number; - requestor?: tile.requestor; - descriptor?: any; - renderer?: tile.renderer; - requestProcessor?: any; - visible?: boolean; - opacity?: number; - minZoomLevel?: number; - maxZoomLevel?: number; - tileBleedPix?: number; - retainInterlevelContent?: boolean; - enableTileFadeIn?: boolean; - notifyErrorAction?: (msg?: string) => void; - notifyLoadingQueueHasEmptiedAction?: () => void; - }); - - /** - * Returns the underlying tile layer. - * @returns {layer} The underlying tile layer. - */ - getTileLayer(): tile.layer; - - /** - * Gets ID associated with the underlying tile layer. - * @returns {string} ID of the layer. - */ - getId(): string; - - /** - * Gets this layerOptions object as a JavaScript object. - */ - getOptions(): any; - } - - /** - * The quad class represents a quad tile within three dimensional - * coordinate space. - * @class quad - */ - export class quad { - - /** - * Gets the x coodinate of this quad tile. - * @returns {number} The x coordinate of this quad tile. - */ - getX(): number; - - /** - * Gets the y coordinate of this quad tile. - * @returns {number} The y coordinate of this quad tile. - */ - getY(): number; - - /** - * Gets the z coordinate of this quad tile, or depth. - * @returns {number} The z coordinate of this quad tile. - */ - getLevel(): number; - - /** - * Gets the envelope in map units which encompasses this quad tile. - * @returns {envelope} The encompassing envelope of this quad tile. - */ - getEnvelope(): envelope; - - /** - * Gets the string representation of this quad tile as a quad key. - * @returns {string} Quad key for this quad tile as a string. - */ - toString(): string; - - /** - * Gets the quad key for this quad tile as a string. - * @returns {string} Quad key for this quad tile as a string. - */ - getKey(): string; - - /** - * Compares this quad tile with another quad tile and determines - * whether or not they are equal. - * @param {quad} Quad tile with which to check for equality with this quad tile. - * @returns {boolean} Result of the equality test. - */ - equals(q: quad): boolean; - - /** - * Generates the quad tile which is a given number of levels above - * this tile in the pyramid and in which this quad tile is contained. - * @param {number} ancestorsBack Number of levels above this tile the - * generated tile should be. - * @returns {quad} The generated parent tile. - */ - factoryParent(ancestorsBack: number): quad; - } - - /** - * Exposes static functions for generating and handling quad tiles. - * @module quad - */ - export module quad { - - /** - * Generates a new quad tile based on a given quad key. - * @param {string} key The quad key from which to generate the quad tile. - * @returns The generated quad tile. - */ - export function factoryQuadFromKey(key: string): quad; - } - - /** - * A tile renderer handles converting JSON vector content loaded from the - * MapDotNet REST feature service into a canvas rendering on a tile. - * @class renderer - */ - export class renderer { - constructor(options? : { - renderPoint?: (pt: point, context: CanvasRenderingContext2D) => void; - renderGeometry?: (shape: geometry, context: CanvasRenderingContext2D) => void; - renderBitmap?: (img: HTMLElement, context: CanvasRenderingContext2D, contextSize: number, bleed: number) => void; - }); - - /** - * Sets the render point function which takes a point and canvas - * context and renders the point to the canvas. The points passed - * in are transformed to pixel units and offset to context origin. - * @param {function} func Function of the form func(shape, context) - * where shape is the point object to be rendered and context is the - * canvas context on which to render. - */ - setRenderPoint(func: (pt: point, context: CanvasRenderingContext2D) => void): void ; - - /** - * Sets render geometry function which takes a geometry and canvas - * context and renders the geometry to the canvas context. The - * geometries passed in are transformed to pixel units and offset - * to the context origin. - * @param {function} func Function with signature func(shape, context) - * where shape is the geometry to render and context is the canvas - * context on which to render. - */ - setRenderGeometry(func: (shape: geometry, context: CanvasRenderingContext2D) => void): void; - - /** - * Sets the render bitmap function which takes a bitmap image and - * a canvas context and renders the image to the canvas context. - * @param {function} func Function with the signature - * func(img, context, contextSize, bleed) where img is the bitmap - * image to render, context is the canvas context on which to - * render the image, contextSize is the size of the canvas context - * in pixels and bleed is the margin around each tile to bleed. - */ - setRenderBitmap(func: (img: HTMLElement, context: CanvasRenderingContext2D, contextSize: number, bleed: number) => void): void; - } + getActualPerimeter(idx?: number): number; /** - * An auto-ranging density map renderer. - * @class rendererDensityMap - */ - export class rendererDensityMap { - - constructor(); - - /** - * Sets the bleed ratio, which is the sets the percentage of the - * margin around each tile to use in the tile's computation. Note: - * some bleed (i.e., greater than 1) is required since a heat map - * relies on adjacent data. - * @param {number} bleed The desired bleed ratio. - */ - setBleed(bleed: number): void; - - /** - * Sets the number of rows and columns of cells to be used for - * computation within the grid. - * @param {number} gridSize Number of rows and columns used in - * the grid. - */ - setGridSize(gridSize: number): void; - - /** - * Sets filter radius corresponding to standard deviations. The - * filter radius is the cutoff point at which adjacent cells no - * longer contribute to a cell's calculation. - * @param {number} filterStdDevRadius Number of standard deviations - * from the mean of a normal distribution to which to give positive - * weight. - */ - setFilterStdDevRadius(filterStdDevRadius: number): void; - - /** - * Sets color ranges from cold to hot for the renderer. - * @param {number[][]} matrix Array of arrrays of numbers, each - * of the form [r,g,b,a], where each array represents a color and - * colors range from cold to hot. Note: Typically, a dozen colors - * is sufficient. - */ - setColorMatrix(matrix: number[][]): void; - - /** - * Sets the minimum required cell value for a cell to receive - * a color. Default minimum value is 0. - * @param {number} mcv The minimum cell value for painting. - */ - setMinCellValue(min: number): void; - - /** - * Sets an optional action to perform on each row. This enables - * processing the values on one or more columns for each row for - * use in the density map computations. - * @param {action} ra Function to call on each row with signature - * action(row). The value returned from the function will is added - * to the cell's value. - */ - setRowAction(action: (row: any) => number): void; - - /** - * Tells renderer to re-render density map and recompute ranges. - * This should be called if the data changes or if, due to extent - * changes, the density changes. - */ - notifyRecompute(extents?: envelope): void; - } + * Determines whether this polygon intersects a given geometry. + * @param {geometry} geom Geometry to test against. + * @returns {boolean} Result of the intersection test. + */ + intersects(geom: geometry): boolean; /** - * This is a base requestor class. - * @class requestor + * Determines whether this polyline overlaps a given geometry. + * @param {geometry} geom Geometry to test against. + * @returns {boolean} Result of the intersection test. */ - export class requestor { - - constructor(); - - /** - * Gets formatted endpoint using the supplied quadtile and a descriptor. - * @param {quad} quad Quadtile for which to fetch the endpoint. - * @returns {string} The requested URI string. - */ - getFormattedEndpoint(quad: quad, descriptor: any): string; - - /** - * Gets data locally if the requestor supports it. - * @param {quad} quad Quadtile for which to fetch the endpoint. - * @returns {string} The requested JSON data. - */ - getLocalData(quad: quad, descriptor: any): string; - - /** - * Creates unique sha1 hash from this requestor and the supplied - * descriptor. This is useful in creating a unique key or folder - * for tile caching. This combined with a tile's quad-key can - * efficiently and uniquely identify a particular tile. - * @params {descriptor} The descriptor for which to create the hash. - * @returns {string} The generated sha1 hash. - */ - hash(descriptor: any): string; - - /** - * Determines whether or not this requestor returns bitmap images. - * @returns {boolean} Whether or not this requestor returns bitmap - * images. - */ - getIsRestImage(): boolean; - - /** - * Sets whether this requestor should return bitmap images. - * @param {boolean} flag Whether or not this requestor should return - * bitmap images. - */ - setIsRestImage(flag: boolean): void; - - /** - * Determines whether or not this requestor uses an endpoint - * rather than local data. - * @returns {boolean} Whether or not this requestor gets data from - * an endpoint. - */ - getUsesEndpoint(): boolean; - - /** - * Sets whether or not this requestor uses an endpoint rather than - * local data. - * @param {boolean} Whether or not this requestor should get data - * from an endpoint. - */ - setUsesEndpoint(flag: boolean): void; - - /** - * Gets format of data returned by REST service. - * @returns {string} Data format returned by the REST service. - */ - getDataFormat(): string; - - /** - * Sets format of data that should be returned by REST service. - * @param {string} df Name of the data format the REST service - * should use. - */ - setDataFormat(df: string): void; - - /** - * Returns whether or not caching is enabled for vector-based - * requestors. - * @returns {boolean} Whether or not caching is enabled. - */ - getCacheEnabled(): boolean; - - /** - * Sets whether or not caching is enabled for vector-beased requestors. - * @param {boolean} flagce - true (default) if caching is enabled - */ - setCacheEnabled(flag: boolean): void; - - /** - * Gets requestor timeout in miliseconds. - * @returns {number} Requestor timeout in miliseconds. - */ - getTimeoutMs(): number; - - /** - * Sets requestor timeout in miliseconds. - * @param {number} ms Desired requestor timeout in miliseconds. - */ - setTimeoutMs(ms: number): void; - - /** ??? - * Gets the additional - * @returns {object[]} - */ - getKeyVals(): {}[]; - - /** Set any key/value pairs that are attached to the ajax call (such as username and password) - */ - setKeyVals(options: {}[]): void; - - /** - * Gets maximum available zoom level content that can be retrieved - * from the endpoint this requestor consumes. - * @returns {number} The maximum available zoom level for this requestor. - */ - getMaxAvailableZoomLevel(): number; - - /** - * Sets maximum available zoom level content that can be retrieved - * from the endpoint this requestor consumes. Note: This defaults - * to the projection's maximum available zoom level, which is 20 - * in spherical mercator. - * @param {number} max The maximum available zoom level for this requestor. - */ - setMaxAvailableZoomLevel(max: number): void; - } - - /** - * A tile requestor for Microsoft Bing maps. - * @class requestorBing - */ - export class requestorBing extends requestor { - - constructor(options?: { - dataFormat?: string; - timeoutMs?: number; - maxAvailableZoomLevel?: number; - }); - - /** - * Gets the formatted endpoint uri for Bing maps, e.g. - * ecn.t{0}.tiles.virtualearth.net/tiles/{1}{2}{3}?g={4}&mkt={5}&shading=hill. - * @returns {string} endpoint to Bing tile server as a formatted string - */ - getEndpoint(): string; - - /** - * Gets the protocol for the endpoint, either 'http' or 'https'. - * @returns {string} The endpoint protocol. - */ - getScheme(): string; - - /** - * Sets endpoint protocol to either 'http' or 'https'. - * @param {string} s Protocol to use in endpoints. - */ - setScheme(s: string): void; - - /** - * Gets Bing tile generation - * @returns {string} the tile generation as an integer - */ - getGeneration(): string; - - /** - * Sets Bing tile generation - * @param {string} g - generation as an integer - */ - setGeneration(g: string): void; - - /** - * Gets the language code for which the tiles are rendered. The - * default code is 'en-US'. - * @returns {string} The language code for which tiles are rendered. - */ - getMarket(): string; - - /** - * Sets language code for which to render tiles. For example, - * 'en-US'. - * @param {string} m Language code for which to render tiles. - */ - setMarket(m: string): void; - - /** - * Gets the Bing key associated with this requestor. - * @returns {string} The Bing key for this requestor. - */ - getBingKey(): string; - - /** - * Sets Bing key which then calls Microsoft metadata service and - * automatically configures content endpoint. - * @param {string} key Bing key. - */ - setBingKey(key: string): void; - } - - /** - * The bitmap or vector tile requestor using MapDotNet REST services. - * @class requestorMDN - */ - export class requestorMDNRest extends requestor { - constructor(endpoint: string, options?: { - dataFormat?: string; - timeoutMs?: number; - maxAvailableZoomLevel?: number; - }); - - /** - * Gets uri endpoint for the MapDotNet REST service. - * @returns {string} Uri endpoint for the MapDotNet REST service. - */ - getEndpoint(): string; - } - - /** - * Creates an instance of a descriptor for describing content from a - * MapDotNet UX REST map service. - * @class descriptorMDNRestMap - */ - export class descriptorMDNRestMap { - constructor(mapId: string, options?: { - version?: string; - imageType?: string; - bleedRatio?: number; - mapCacheOption?: string; - mapCacheName?: string; - useQuadKeyForMapCacheName?: boolean; - backgroundColorStr?: string; - layerVisibility?: {}; - layerOutline?: {}; - layerFill?: {}; - layerWhere?: {}; - tag?: string; - }); - - /** - * Sets the flag to suspend descriptor change notifications. If - * set true, all changes to this descriptor will not cause the map - * to redraw. Setting to false will enable redraws and immediately - * force a redraw. - * @param {boolean} flag Whether or not descriptor change notifications - * should be enabled. - */ - setSuspendDescriptorChangeNotifications(flag: boolean): void; - - /** - * Gets the map ID. - * @returns {string} The map ID. - */ - getMapId(): string; - - /** - * Gets the REST service version. - * @returns {string} The REST service version. - */ - getVersion(): string; - - /** - * Sets the REST service version. - * @param {string} v The version number. - */ - setVersion(v: string): void; - - /** - * Gets image type associated with this descriptor, either 'png', - * 'png8', or 'jpg'. - * @returns {string} The image type associated with this descriptor. - */ - getImageType(): string; - - /** - * Gets image type associated with this descriptor to one of 'png', - * 'png8', or 'jpg'. - * @param {string} t The image type associated which should be - * associated with this descriptor. - */ - setImageType(t: string): void; - - /** - * Gets bleed ratio for the layer associated with this descriptor. - * @returns {number} The bleed ratio. - */ - getBleedRatio(): number; - - /** - * Sets the bleed ratio. Bleeds greater than 1.0 will fetch content - * beyond the edge of the tile extents (this is useful for point - * features). - * @param {number} br The desired bleed ratio, between 1.0 and 2.0. - */ - setBleedRatio(br: number): void; - - /** - * Gets the map's cache setting, which is one of 'None', - * 'ReadOnly', 'ReadWrite', 'ForceWrite', and 'Default.' - * @returns {string} The map's cache setting. - */ - getMapCacheOption(): string; - - /** - * Gets the map's cache setting to one of 'None', - * 'ReadOnly', 'ReadWrite', 'ForceWrite', and 'Default.' - * @param {string} mco The desired cache setting for the map. - */ - setMapCacheOption(mco: string): void; - - /** - * Gets the optional map cache name. - * @returns {string} The map cache name. - */ - getMapCacheName(): string; - - /** - * Sets the optional map cache name. - * @param {string} mcn The desired map cache name. - */ - setMapCacheName(mcn: string): void; - - /** - * Determines whether the map is flagged to use the quadkey as its - * map cache name. - * @returns {boolean} Whether or not the map has been flagged to - * use the quadkey as its map cache name. - */ - getUseQuadKeyForMapCacheName(): boolean; - - /** - * Sets the flag that uses the quadkey as its map cache name. - * @param {boolean} flag Whether or not the map should be flagged - * to use the quadkey as its map cache name. - */ - setUseQuadKeyForMapCacheName(flag: boolean): void; - - /** - * Gets map image background color. - * @returns {string} CSS style string for the map image background color. - */ - getBackgroundColorStr(): string; - - /** - * Sets the map image background color. - * @param {number} a Alpha level. - * @param {number} r Red level. - * @param {number} g Green level. - * @param {number} b Blue level. - */ - setBackgroundColor(a: number, r: number, g:number, b:number): void; - - /** - * Checks whether or not the map background is transparent. - * @returns {boolean} Whether or not the map background is transparent. - */ - getIsBackgroundTransparent(): boolean; - - /** - * Sets a layer's visibility. - * @param {string} layerId The MapDotNet map layer ID. - * @param {boolean} isVisible Whether or not the layer should be visible. - */ - setLayerVisibility(layerId: string, isVisible: boolean): void; - - /** - * Gets a layer's visibility. - * @param {string} layerId The MapDotNet map layer ID. - * @returns {boolean} Whether or not the layer is visible. - */ - getLayerVisibility(layerId: string): boolean; - - /** - * Sets a layer's outline color and thickness. - * @param {string} layerId The MapDotNet map layer ID. - * @param {number} a Alpha level. - * @param {number} r Red level. - * @param {number} g Green level. - * @param {number} b Blue level. - * @param {number} thk Outline thickness in pixels. - */ - setLayerOutline(layerId: string, a: number, r: number, g: number, b: number, thk: number): void; - - /** - * Gets a layer's outline color and thickness. - * @param {string} layerId The MapDotNet map layer ID. - * @returns {object} JavaScript object of the form {color, thickness} - * where color is the CSS style string of the outline color and - * thickness is the outline thickness in pixels. - */ - getLayerOutline(layerId: string): { color: string; thickness: number; }; - - /** - * Sets a layer's fill color. - * @param {string} layerId The MapDotNet map layer ID. - * @param {number} a Alpha level. - * @param {number} r Red level. - * @param {number} g Green level. - * @param {number} b Blue level. - */ - setLayerFill(layerId: string, a: number, r: number, g: number, b: number): void; - - /** - * Sets a layer's fill color as a SQL expression. - * @param {string} layerId The MapDotNet map layer ID. - * @param {string} exp The SQL expression to select a row's fill color. - */ - setLayerFillAsExpression(layerId: string, exp: string): void; - - /** - * Gets a layer's fill color as a CSS style string or as a SQL expression. - * @param {string} layerId The MapDotNet map layer ID. - * @returns {string} Either the CSS style string or the SQL expression, - * according to how the layer's fill color was set. - */ - getLayerFill(layerId: string): string; - - /** - * Add or replace the where clause for a layer. The where clause - * is a SQL expression used to filter rows. - * @param {string} layerId The MapDotNet map layer ID. - * @param {string} where The desired SQL where expression. - * @param {boolean} [merge] Whether to merge the new where clause - * with the existing where clause using a SQL AND or to replace - * the existing where clause with the new one. Defaults to true (merge). - */ - setLayerWhere(layerId: string, where: string, merge: boolean): void; - - /** - * Sets a separator character for the layer where clause expression - * in the query string. This is set to ',' by default, which is - * consistent with SQL. - * @param {string} sep The desired seperator, which should be a - * single character. - */ - setLayerWhereSep(sep: string): void; - - /** - * Returns the current separator for the layer where clause in the - * query string. - * @returns {string} The current seperator. - */ - getLayerWhereSep(): string; - - /** - * Gets the current layer where clause. - * @param {string} layerId The MapDotNet map layer ID. - * @returns {string} The current where clause. If no where clause - * is in use, this will return an empty string. - */ - getLayerWhere(layerId: string): string; - - /** - * Gets a tag which is used to modify the request URIs to avoid - * browser caching - * @returns {string} The map's tag. - */ - getTag(): string; - - /** - * Sets the map's tag, which is used modify request URIs to avoid - * browser caching. - * @param {string} tag The desired tag. - */ - setTag(tag: string): void; - } - - /** - * Creates an instance of a descriptor for describing content from - * a MapDotNet REST feature service. - * @class descriptorMDNRestFeature - */ - export class descriptorMDNRestFeature { - constructor(mapId: string, layerId: string, options?: { - version?: string; - bleedRatio?: number; - fieldNames?: string[]; - clipToRenderBounds?: boolean; - simplifyEnabled?: boolean; - }); - - /** - * Gets the map ID. - * @returns {string} The map ID. - */ - getMapId(): string; - - /** - * Gets the layer's ID. - * @returns {string} The layer's ID. - */ - getLayerId(): string; - - /** - * Gets the version of the REST service. - * @returns {string} The REST service version. - */ - getVersion(): string; - - /** - * Sets the REST service version number. - * @param {string} v The version number to set. - */ - setVersion(v: string): void; - - /** - * Gets the bleed ratio. - * @returns {number} The current bleed ratio. - */ - getBleedRatio(): number; - - /** - * Sets the bleed ratio. Bleeds greater than 1.0 will fetch content - * beyond the edge of the tile extents (this is useful for point features). - * @param {number} br The desired bleed ratio, a number between 1.0 and 2.0. - */ - setBleedRatio(br: number): void; - - /** - * Gets the optional field names to query. This attribute data may - * be used in dynamic client-side rendering. - * @returns {string[]} An array of field names as strings. - */ - getFieldNames(): string[]; - - /** - * Sets the optional field names to query. This attribute data may be used in - * dynamic client-side rendering. - * @param {string} names - array of strings for each field to query - */ - setFieldNames(names: string[]): void; - - /** - * Checks the flag whether to clip geometry fetched at the bounds - * of the request. - * @returns {boolean} The value of the flag. - */ - getClipToRenderBounds(): boolean; - - /** - * Sets the flag whether to clip geometry fetched at the bounds - * of the request. This can greatly improve performance with large - * complex geometries. Only supported when back-end store is SQL - * 2008/2012 or PostGIS. - * @param {boolean} flag Whether or not to clip geometries fetched - * at the bounds of the request. - */ - setClipToRenderBounds(flag: boolean): void; - - /** - * Checks the flag whether to simplify paths based on the units per - * pixel for the quad tile being requested. - * @returns {boolean} The value of the flag. - */ - getSimplifyEnabled(): boolean; - - /** - * Sets the flag whether to simplify paths based on the units per - * pixel for the quad tile being requested. - * @param {boolean} flag Whether or not to simply paths based on - * the units per pixel. - */ - setSimplifyEnabled(flag: boolean): void; - - /** - * Sets the action to perform on descriptor change. - * @param {function} action Function with signature action(). - */ - setNotifyDescriptorChangeAction(action: () => void): void; - } - - /** - * This is a generic tile requestor suitable for several third-party - * tile servers. These include open street map, map quest, cloudmade, - * Nokia, etc. - * @class requestorOpen - */ - export class requestorOpen extends requestor { - constructor(endpoint: string, subdomains: string[], options?: { - dataFormat?: string; - timeoutMs?: number; - maxAvailableZoomLevel?: number; - }); - } - - /** - * This is a requestor for local collections of data. These local collections may - * originate from inlined code or from datasources other than a MapDotNet REST - * feature service. - * @class requestorLocal - */ - export class requestorLocal extends requestor { - constructor(options?: { - dataFormat?: string; - timeoutMs?: number; - maxAvailableZoomLevel?: number; - data: {}[]; - }); - - /** - * Gets the unparsed source data. - * @returns {object} Array of source data objects. - */ - getSource(): {}[]; - - /** - * Sets source data. - * @param {object} data An array of JavaScript objects to use as - * the requestor source data. - */ - setSource(data: {}[]): void; - - /** - * Returns your source data parsed into theformat { Shapes: [], - * Values: [], Bounds: [] } This may be useful for doing client-side - * queries on the local data where all of the WKT has been parsed - * into points and geometry. There is also a bounds collection to - * do a quick spatial check for complex polygons. - * @returns {object} Parsed data object in the form {Shapes, Values, Bounds}. - */ - getParsedData(): { - Shapes: any[]; - Values: any[]; - Bounds: envelope[]; - }; - } - - /** - * Local descriptor object for describing source data when the source - * data is fecthed by a local requestor. - * @class descriptorLocal - */ - export class descriptorLocal { - constructor(options: { - valueFieldNames: string[]; - geometryFieldName: string; - bleedRatio?: number; - }); - } - } - - interface pointObject { - x: number; - y: number; - } - - interface envObject { - - /** - * @returns {number} minX as integer - */ - minX: number; - - /** - * @returns {number} minY coord as integer - */ - minY: number; - - /** - * @returns {number} maxX coord as integer - */ - maxX: number; - - /** - * @returns {number} maxY coord as integer - */ - maxY: number; - } - - interface extentChangeStatsObj { - - centerX: number; - centerY: number; - centerLat: number; - centerLon: number; - zoomLevel: number; - mapScale: number; - mapScaleProjected: number; - mapUnitsPerPixel: number; - extents: envelope; - } - - interface repositionStatsObj { - - centerX: number; - centerY: number; - zoomLevel: number; - mapUnitsPerPixel: number; - } - - interface beginDigitizeOptions { - key?: string; - shapeType: string; - geometryStyle?: geometryStyle; - styledGeometry?: styledGeometry; - nodeTapAndHoldAction?: (setIdx: number, idx: number) => boolean; - nodeMoveAction?: (x: number, y: number, actionType: string) => any; - shapeChangeAction?: () => void; - envelopeEndAction?: (env: envelope) => void; - circleEndAction?: (circle: geometry.polygon) => void; - suppressNodeAdd?: boolean; - leavePath?: boolean; - } - - - interface styleObj { - fillColor?: string; - fillOpacity?: number; - outlineColor?: string; - outlineOpacity?: number; - outlineThicknessPix?: number - dashArray?: string; - } - - interface mapsjsWidget { - - /** - * Gets the center of the map in spherical mercator. Use - * sphericalMercator.deprojectToLatLon static function to convert to a lat/lon. - * @return {point} A point map center - */ - getMapCenter(): point; - - /** - * Sets the center of the map in spherical mercator. Use - * sphericalMercator.projectFromLatLon static function to convert from a lat/lon. - * @param {point} center The map center as a point - */ - setMapCenter(center: point): void; - - /** - * Same as setMapCenter except will animate from current map center to the - * specified location - * @param {point} center The map center as a point. - * @param {number} [durationMs] Duration in miliseconds. - * @param {function} [completeAction] Callback to perform on animaton complete. - */ - setMapCenterAnimate(center: point, durationMs?: number, completeAction?: () => void): void; - - /** - * Sets the map center to the current geolocation if supported. The map is - * animated to the new location. - * @param {number} [durationMs] Duration in miliseconds. - * @param {function} [completeAction] Callback to perform on animaton complete. - */ - setMapCenterToGeolocationAnimate(durationMs?: number, completeAction?: () => void): void; - - /** - * Offsets the current map center by the specified deltas in pixels. - * @param {number} [dx] offset x in pixels. - * @param {number} [dy] offset y in pixels. - */ - offsetMapCenterByPixelDelta(dx: number, dy: number): void; - - /** - * Offsets the current map center by the specified deltas in pixels - animated version. - * @param {number} [dx] offset x in pixels. - * @param {number} [dy] offset y in pixels. - * @param {number} [durationMs] animation duration in mS. - */ - offsetMapCenterByPixelDeltaAnimate(dx: number, dy: number, durationMs?: number): void; - - /** - * Gets the current zoom level. - * @returns {number} The current zoom level. - */ - getZoomLevel(): number; - - /** - * Sets the current zoom level. - * @param {number} z1 The desired zoom level. - */ - setZoomLevel(zl: number): void; - - /** - * Sets the minimum zoom level for the map. - * @param {number} zl Desired minimum zoom level. - */ - setMinZoomLevel(zl: number): void; - - /** - * Sets the maximum zoom level for the map. - * @param {number} z1 The desired maximum zoom level. - */ - setMaxZoomLevel(zl: number): void; - - /** - * Animates the map from the current zoom level to the given zoom level. - * @param {number} zl The desired zoom level. - * @param {number} [durationMs] The duration in miliseconds. - * @param {function} [completeAction] Function to call when the animation - * completes with signature completeAction(). - */ - setZoomLevelAnimate(zl: number, durationMs?: number, completeAction?: () => void): void; - - /** - * Changes the current zoom level. - * @param {number} delta Change to be added to the current zoom level. - */ - zoomDelta(delta: number): void; - - /** - * Animates a change to the current zoom level. - * @param {number} delta Change to be added to the current zoom level. - * @param {number} [durationMs] Duration in miliseconds. - */ - zoomDeltaAnimate(delta: number, durationMs?: number): void; - - /** - * Animates parabolically from the current map center and zoom level - * to the given map center and zoom level. - * @param {point} center Desired map center as a point. - * @param {number} zl Desired zoom level. - * @param {number} [durationMs] Animation duration in miliseconds. - * @param {function} [completeAction] Function to call after the animation - * completes with signature completeAction(). - */ - flyTo(center: point, zl: number, durationMs?: number, completeAction?: () => void): void; - - /** - * Gets the current map extents in spherical mercator units. - * @return {envelope} envelope The current map extents. - */ - getMapExtents(): envelope; - - /** - * Gets the current map units per pixel. - * @returns {number} Map units (meters) per pixel. - */ - getMapUnitsPerPixel(): number; - - /** - * Gets the map extents' width and height in pixels. - * @returns {object} JavaScript object of the form {w, h} where w is - * the current extents' width in pixels and h is the current extents' - * height in pixels. - */ - getViewExtentsInPix(): { w: number; h: number; }; - - /** - * Gets the current projected map scale. This is the ratio of units on - * the screen to map units depicted. - * @returns {number} Ratio of screen units to map units. - */ - getProjectedMapScale(): number; - - /** - * Gets the current actual map scale. This is the ratio of units on - * the screen to actual units on the earth's surface at the latitude - * of the current map center. - * @returns {number} The ratio of screen units to actual meters. - */ - getActualMapScale(): number; - - /** - * Gets the best fit zoom level based on the supplied map extents for - * the current display extents in pixels. - * @param {envelope} extentsNew New map extents to fit. - * @returns {number} The zoom level which best fits the extents. - */ - getBestFitZoomLevelByExtents(extentsNew: envelope): number; - - /** - * Forces the map to redraw the currently loaded tile and geometry - * content. You should not have to call this as redraws are automatically - * handled during programatic state changes. This would be for edge cases - * where the developer is affecting internal state in an undocumented way. - */ - redraw(): void; - - /** - * Updates the map to the size of its container. This updates internal - * parameters for computing map extents and handling the amount of tile - * content to download. This is handled automatically if the browser - * window is resized. But if you are sizing the map programatically - * (e.g. resizable panel or slider) then call this after the parent - * container has resized. - */ - resize(): void; - - /** - * Pushes a supplied tile layer onto the top of the display stack. - * @param {tile.layer} tl The desired tile layer. - */ - pushTileLayer(tl: tile.layer): void; - - /** - * Removes a tile layer off the top of the display stack - * @returns {tile.layer} The removed tile layer. - */ - popTileLayer(): tile.layer; + overlaps(poly: polygon): boolean; /** - * Removes a tile layer off the display stack by reference - * @param {tile.layer} tl A tile layer to remove. - */ - removeTileLayer(tl: tile.layer): void; - - /** - * Removes all tile layers off the display stack - */ - removeAllTileLayers(): void; - - /** - * Gets the current number of tile layers in the display stack. - * @returns {number} The number of tile layers in the display stack. + * Convert this polygon into an array of OGC compliant polygons where + * the first set is a ring and all subsequent contained sets are holes. + * @returns {polygon[]} An array of OGC polygons. */ - getTileLayerCount(): number; - - /** - * Gets a tile layer from the display stack by its key. - * @param {string} key The desired tile layer's key. - * @returns {tile.layer} The tile layer associated with the key, or null - * if no tile layer is associated with the key. - */ - getTileLayer(key: string): tile.layer; - - /** - * Gets a point in map units from supplied coordinates pixel units - * with respect to the currently displayed extents. - * @param {number} x The x coordinate in pixels. - * @param {number} y The y coordinate in pixels. - * @returns {point} The generated point in map units. - */ - computeMapPointFromPixelLocation(x: number, y: number): point; - - /** - * Flags whether or not map extent changes can occur through gestures - * like mouse or touch drag, mouse wheel, or pinch zoom. - * @param {boolean} flag Whether or not gestures should affect map - * extent changes. - */ - setSuspendMapExtentChangesByGestures(flag: boolean): void; - - /** - * Sets the z-order of drawn content in relation to the gesture capture - * panel. The default behavior (false) is to have fixed content and - * geometry underneath the gesture panel in the DOM. If false, all - * pointer events are handled by the gesture capture panel and - * optionally parents of the map control. If true, drawn content will - * receive pointer events first and will block gestures to the map. If - * true, digitizing will not function and polygons will block map - * navigation. In some scenarios you may want to set this to true if you - * are placing fixed content (such as point features) on the map and - * need to handle gestures on the placed content. You can call this - * function at any time to change the order. - * @param {boolean} flag Whether or not the fixed content layer should - * reside above the gesture layer. - */ - setDrawnContentZorderToTop(flag: boolean): void; - - /** - * Add a fixed element to the content area which resides at a z-level - * above tiled map content. These elements do not scale with the map - * scale. This is used to place markers or callouts on the map - * @param {HTMLElement} element Any html that can be added to the DOM. - * @param {number} mapUnitsX The x coordinate of the insertion point in map units. - * @param {number} mapUnitsY The y coordinate of the insertion point in map units. - * @param {function} [addAction] Callback function called after the - * DOM element has been placed with signature addAction(element). - * @param {object} dragOptions JavaScript object of the form {dragEnabled, - * useElementInsteadOfNewGestureOverlay, downAction, moveAction, upAction, - * wheelAction } where dragEnabled flags whether dragging should be - * enabled on the element, and downAction, moveAction, upAction, and - * wheelAction are callback functions invoked on mousedown, mousemove, - * mouseup, and scroll events respectively. - */ - addFixedContentElement( - element: HTMLElement, - mapUnitsX: number, - mapUnitsY: number, - addAction?: (ele: HTMLElement) => void, - dragOptions?: { - dragEnabled: boolean; - useElementInsteadOfNewGestureOverlay: boolean; - downAction?: (downPoint: point) => any; - moveAction?: (movePoint: point) => void; - upAction?: (upPoint: point) => void; - wheelAction?: (delta: number) => void; - } - ): void; - - /** - * Move an existing fixed content element. - * @param {HTMLElement} element The existing DOM element to move. - * @param {number} mapUnitsX The new x coordinate in map units. - * @param {number} mapUnitsY The new y coordinate in map units. - */ - moveFixedContentElement(element: HTMLElement, mapUnitsX: number, mapUnitsY: number): void; - - /** - * Removes a fixed content element. - * @param {HTMLElement} element The DOM element to remove. Note: This - * must be the same element added by addFixedContentElement. - */ - removeFixedContentElement(element: HTMLElement): void; - - /** - * Add a styled path geometry to the content area which resides at a z-level - * above tiled map content. The geometry is converted to SVG and added to the - * content area DOM. If an attempt to add a geometry is made with the same - * key, the geometry is swapped out. You must remove using removePathGeometry - * for resource cleanup. - * @param {styleGeometry} styledGeom The styledGeometry to render. - * @param {string} key String used to tie a geometry to its SVG - * @param {function} addAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. - * @param {function} removeAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. - * rendering in the DOM. - * @returns {element} The SVG element which was added to the DOM. - */ - addPathGeometry( - styledGeom: styledGeometry, - key: string, - addAction?: (svg: SVGElement) => void, - removeAction?: (svg: SVGElement) => void): SVGElement; - - /** - * Updates an existing path geometry to reflect a style change. - * @param {geometryStyle} styleNew The new geometryStyle. - * @param {string} key The key of the geometry to receive the new style. - */ - updatePathGeometryStyle(styleNew: geometryStyle, key: string): void; - - /** - * Removes a styledGeometry from display. - * @param {string} key The key of the geometry to remove. - * @returns {element} The SVG element which was removed from the DOM. - */ - removePathGeometry(key?: string): SVGElement; - - /** - * Initiates digitization on the map control. This creates a new - * geometry and adds verticies to the geometry accord to mouse - * click locations. - * @param {object} options JavaScript object of the form { key, - * shapeType, geometryStyle, styledGeometry, nodeTapAndHoldAction, nodeMoveAction, - * shapeChangeAction, envelopeEndAction, circleEndAction, supressNodeAdd, leavePath } - * where key is a a string associated with this geometry, shapeType - * is the type of shape this geometry is, one of 'polygon', 'polyline', 'multipoint', 'envelope' or 'circle', - * geometryStyle is a geometryStyle which should be applied - * to the digitized geometry, styledGeometry is an optional styledGeometry for existing paths to edit, set this to enter edit mode, - * nodeTapAndHoldAction is a callback invoked - * when any point in the geometry is clicked and held and has the - * signature nodeTapAndHoldAction(setIdx, idx), nodeMoveAction is a - * callback invoked after any node is dragged to a new location and - * has signature nodeMoveAction(x, y, actionType), shapeChangeAction - * is a callback that is invoked after the geometry shape changes and, - * has signature shapeChangeAction(shape), envelopeEndAction is a callback - * invoked after an envelope is created and has signature envelopeEndAction(envelope), - * circleEndAction is similar to envelopeEndAction but takes a geometry.polygon representing the circle, - * and leavePath is a flag that indicates whether the digitized shape - * should be left on the map after digitization is complete. - */ - beginDigitize(options: beginDigitizeOptions): void; - endDigitize(): void; - - /** - * Gets a snapshot copy of the currently digitizing path. - * @returns {geometry} The currently digitizing path. - */ - getDigitizeSnapshot(): geometry; - - /** - * Forces additional digitized points to be pushed to a new set of the - * currently digitizing geometry. - */ - pushSetOnDigitizePath(): void; - - /** - * Removes the last set from the currently digitizing path. - * @return {number[]} The last set from the currently digitizing path - * in the form [xn,yn]. - */ - popSetFromDigitizePath(): number[]; - - /** - * Programmatically delete a node from the currently digitizing path. - * @param {number} setIdx The index of the set from which to remove the node. - * @param {number} nodeIdx The index of the node to remove. - */ - deleteNodeOnDigitizePath(setIdx: number, nodeIdx: number): void; - - /** - * Determines whether a shape is currently being digitized. - * @returns {boolean} Whether or not a shape is being digitized. - */ - isDigitizingEnabled(): boolean; - - /** - * Set the function called when the map extents have stopped changing - * (e.g. after an animated pan or zoom). - * @param {function} action The function to call when the extents - * finish changing with signature action(object) where object is of - * the form { centerX, centerY, centerLat, centerLon, zoomLevel, mapScale, - * mapScaleProjected, mapUnitsPerPixel, extents }. - */ - setExtentChangeCompleteAction(action: (vals: extentChangeStatsObj) => void): void; - - /** - * Set the function called when map content (map tiles and fixed elements) are - * re-positioned in the DOM. This is done automatically as the map is panned - * beyond existing content and zoomed to a new level requiring content. - * @param {function} action The function to call when the map content - * completes repositioning with signature action(object) where object - * is of the form { centerX, centerY, zoomLevel, mapUnitsPerPixel }. - */ - setContentRepositionAction(action: (vals: repositionStatsObj) => void): void; - - /** - * Sets function called when map is clicked or tapped. - * @param {function} action The function to call on mouse click or tap - * with signature action(point). - */ - setPointerClickAction(action: (pt: point) => void): void; - - /** - * Sets function called when the map pointer hovers over the map. - * @param {function} action The function to call on mouse hover with - * signature action(point). - */ - setPointerHoverAction(action: (pt: point) => void): void; - - /** - * Sets the margin around the map in pixels for extra content fetched so that tile - * rebuilding of the display is minimized. This is an advanced property and does not - * generally need to be adjusted. The default is 128 pixels, or half the width - * of a tile. This should be increased for maps which are very large in pixels - * or where panning is constant. This should be decreased for very small maps, - * such as on mobile devices, or where panning is minimal. - * @param {number} cem The content extent margin in pixels. - */ - setContentExtentsMarginInPixels(cem: number): void; - - /** - * Sets the background color of the map using a css color string - * @param {number} b- a css color string - */ - setBackground(b: string): void; + toMultiPolygon(): polygon[]; } } +/** + * A style specification for geometry objects. + * @class geometryStyle + */ +export class geometryStyle { + constructor(options?: styleObj); + + /** + * Gets path outline thickness in pixels. + * @returns {number} Thickness of path outline. + */ + getOutlineThicknessPix(): number; + + /** + * Sets path outline thickness in pixels. + * @param {number} t Desired thickness. + */ + setOutlineThicknessPix(t: number): void; + + /** + * Gets path outline color as a CSS style string. + * @returns {string} Outline color as a CSS style string. + */ + getOutlineColor(): string; + + /** + * Sets path outline color from a CSS style string. + * @param {string} c Outline color as a CSS style string. + */ + setOutlineColor(c: string): void; + + /** + * Gets path outline opacity in decimal format. + * @returns {number} Outline opacity. + */ + getOutlineOpacity(): number; + + /** + * Set path outline opacity to a decimal between 0 and 1. + * @param {number} o Outline opacity. + */ + setOutlineOpacity(o: number): void; + + /** + * Gets fill color as a CSS style string. + * @returns {string} Fill color as a CSS style string. + */ + getFillColor(): string; + + /** + * Sets fill color as a CSS style string. + * @param {string} c Fill color as a CSS style string. + */ + setFillColor(c: string): void; + + /** + * Gets fill opacity in decimal format. + * @returns {number} Fill opacity. + */ + getFillOpacity(): number; + + /** + * Sets fill opacity to a decimal between 0 and 1. + * @param {number} o Fill opacity. + */ + setFillOpacity(o: number): void; + + /** + * Gets the dash array as a string. + * @returns {string} Dash array as astring. + */ + getDashArray(): string; + + /** + * Sets dash array string from a CSS style string. Defaults to solid + * stroke if no dash array string is provided. + * @param {string} [da] Dash array as a CSS style string. + */ + setDashArray(da: string): void; +} + +/** + * Gets the mapsjs license. + * @returns {string} The license. + */ +export var license: string; + +/** + * A simple point class with x and y coordinates. + * @class point + */ +export class point { + + constructor(x: number, y: number); + + /** + * Returns the x coordinate. + * @returns {number} The x coordinate. + */ + getX(): number; + + /** + * Returns the y coordinate. + * @returns {number} The y coordinate. + */ + getY(): number; + + /** + * Returns the x and y coordinates of this point as a pointObject. + * @returns {pointObject} Representaton of this point as an pointObject. + */ + toProps(): pointObject; + + /** + * Equality comparer between this point and a given reference point. + * @param {point} pt Reference point. + * @returns {boolean} Result of the equality test. + */ + equals(pt: point): boolean; + + /** + * Creates a point from this point offset by a given x and y distance. + * @param {number} dx The x offset. + * @param {number} dy The y offset. + * @returns {point} The offset point. + */ + createOffsetBy(dx: number, dy: number): point; + + /** + * Creates new n-sided polygon around this point. + * @param {number} sides Number of polygon sides. + * @param {number} radius Distance to polygon points. + * @returns {polygon} The generated polygon. + */ + convertToPoly(side: number, radius: number): geometry.polygon; + + /** + * Gets the wkt representation of this point. + * @returns {string} The well known text for this point. + */ + toString(): string; + + /** + * Creates a deep copy of this point. + * @returns {point} The new cloned point. + */ + clone(): point; + + /** + * Returns this point's bounding box. + * @returns {envelope} The bounding box of the point as an envelope. + */ + getBounds(): envelope; + + /** + * Computes distance between this point and a given point in projected + * map units. + * @param {point} pt Point to which to compute distance. + * @returns {number} Distance from this point to the given point in + * projected map units. + */ + distanceTo(pt: point): number; +} + +/** + * Exposes static functions that act on points. + * @module point + */ +export module point { + + /** + * Computes the distance between two points in coordinate units. + * @param {number} x1 The x coordinate for the first point. + * @param {number} y1 The y coordinate for the first point. + * @param {number} x2 The x coordinate for the second point. + * @param {number} y2 The y coordinate for the second point. + * @returns {number} Distance in coordinate units. + */ + export function distance(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Computes the midpoint of two points. + * @param {number} x1 The x coordinate for the first point. + * @param {number} y1 The y coordinate for the first point. + * @param {number} x2 The x coordinate for the second point. + * @param {number} y2 The y coordinate for the second point. + * @return {point} Midpoint point. + */ + export function midpoint(x1: number, y1: number, x2: number, y2: number): point; +} + +/** + * Exposes static functions related to the Spherical Mercator projection. + * @module sphericalMercator + */ +export module sphericalMercator { + + /** + * Gets the EPSG number for Spherical Mercator. + * @return {number} ESPG number. + */ + export function getEpsg(): number; + + /** + * Gets the minimum zoom level for this projection. + * @returns {number} Minimum zoom level. + */ + export function getMinZoomLevel(): number; + + /** + * Sets the minimum zoom level for this projection. Normally this is + * set to 1.0 and should not be altered. + * @param {number} minZ Desired minimum zoom level. + */ + export function setMinZoomLevel(minZ: number): void; + + /** + * Gets the maxmimum zoom level for this projection. + * @returns {number} Maximum zoom level. + */ + export function getMaxZoomLevel(): number; + + /** + * Sets the maximum zoom level for this projection. Normally this is + * set to 20.0 and should not be altered. + * @param {number} maxZ1 Desired maximum zoom level. + */ + export function setMaxZoomLevel(maxZ: number): void; + + /** + * Gets the tile height and width in pixels. + * @returns {number} The height and width of the tiles in pixels. + */ + export function getTileSizePix(): number; + + /** + * Gets the display DPI, which defaults to 96. Note: The dpi is + * recomputed on page load complete. + * @returns {number} Dots per inch on display. + */ + export function getDpi(): number; + + /** + * Set the display DPI, which defaults to 96. Note: The DPI is + * recomputed on page load complete. + * @param {number} dpi Dots per inch on display. + */ + export function setDpi(dpi: number): void; + + /** + * Return the equitorial radius in meters for this projection. + * @returns {number} Equitorial radius in meters. + */ + export function getRadius(): number; + + /** + * Returns equitorial circumference in meters for this projection + * @returns {number} Equitorial circumference in meters. + */ + export function getCircumference(): number; + + /** + * Returns half the equitorial circumference in meters for this projection + * @returns {number} Half of the equitorial circumference in meters. + */ + export function getHalfCircumference(): number; + + /** + * Get the envelope in map units for a given quadtree node, i.e. tile, + * based on the given x, y, and z quadtree coordinates. + * @param {number} x The x coordinate. + * @param {number} y The y coordinate. + * @param {number} z The z coordinate. + * @returns {envelope} Envelope of the tile in map units. + */ + export function getQuadTreeNodeToMapEnvelope(x: number, y: number, z: number): envelope; + + /** + * Gets the envelope in map units of tiles in the quadtree from an + * evelope in map units and a zoom level. + * @param {envelope} env Envelope for which to find intersecting tiles. + * @param {number} z Zoom level with which to test for intersection. + * @returns {envelope} The envelope in map units of the tiles. + */ + export function getQuadTreeNodeRangeFromEnvelope(env: envelope, z: number): envelope; + + /** + * Gets projected map units per pixel for a given zoom level. + * @param {number} zoomLevel Reference zoom level. + * @returns {number} Projection units per pixel. + */ + export function getProjectionUnitsPerPixel(zoomLevel: number): number; + + /** + * Gets the required scale transform to apply to shapes so distance + * and area computations yield actual Earth-geodesic units instead of + * projected map units. + * @param {number} mapPtY Reference latitude for the computation. + * @returns {number} Scale transform multiplier. + */ + export function getActualShapeScaleTransform(mapPtY: number): number; + + /** + * Gets actual, on-the-ground meters per pixel for a given zoom level + * and map point in map units. + * @param {point} mapPt Reference location for the computation. + * @param {number} z Reference zoom level. + * @returns {number} Meters per pixel multiplier. + */ + export function getActualUnitsPerPixel(mapPt: point, zoomLevel: number): number; + + /** + * Gets the optimal zoom level for a given envelope in map units + * based on the envelope of visible device area in pixels. + * @param {envelope} envelopeMap Envelope in map units to display. + * @param {envelope} envelopeDevice Envelope in pixels of visible area. + * @returns {number} Optimal zoom level for viewing envelopeMap. + */ + export function getBestFitZoomLevelByExtents(envelopeMap: envelope, envelopeDevice: envelope): number; + + /** + * Gets a quad-key from x, y, and z coordinates. + * @param {number} x The x coordinate. + * @param {number} y The y coordinate. + * @param {number} z The z coordinate. + * @returns {string} Quad-key string. + */ + export function getQuadKeyFromXYZ(x: number, y: number, z: number): string; + + /** + * Gets x, y, and z coordinates as an object from a given quad-key. + * @param {string} key Reference quad-key. + * @return {object} JavaScript object of the form {x,y,z}. + */ + export function getXYZFromQuadKey(key: string): { x: number; y: number; z: number; }; + + /** + * Project a point from latitude/longitude to Spherical Mercator. + * @param {point} lonLat Point object in latitude/longitude. + * @returns {point} The same point in Spherical Mercator. + */ + export function projectFromLatLon(lonLat: point): point; + + /** + * Project a point from Spherical Mercator to latitude/longitude. + * @param {point} mapPt Point object in Spherical Mercator. + * @returns {point} The same point in latitude/longitude. + */ + export function deprojectToLatLon(mapPt: point): point; +} + +/** + * A geometry object decorated with a geometry style object + * @class styledGeometry + */ +export class styledGeometry { + constructor(geom: geometry, gStyle?: geometryStyle); + + /** + * Set this styledGeometry's geometry. + * @param {geometry} g A new Geometry. + */ + setGeometry(g: geometry): void; + + /** + * Set this styledGeometry's geometryStyle. + * @param {geometryStyle} gs A new styledGeometry. + */ + setGeometryStyle(gs: geometryStyle): void; + + /** + * Gets the styledGeometry's underlying geometry object. + * @returns {geometry} The underlying geometry. + */ + getGeometry(): geometry; + + /** + * Gets the styledGeometry's underlying geometryStyle object. + * @returns {geometryStyle} The underlying geometry style. + */ + getGeometryStyle(): geometryStyle; + + /** + * Gets path outline thickness in pixels. + * @returns {number} Thickness in pixels. + */ + getOutlineThicknessPix(): number; + + /** + * Sets path outline thickness in pixels. + * @param {number} t Thickness in pixels. + */ + setOutlineThicknessPix(t: number): void; + + /** + * Gets path outline color as a CSS style string. + * @returns {string} Outline color as a CSS style string. + */ + getOutlineColor(): string; + + /** + * Gets path outline opacity in decimal format. + * @param {number} Outline opacity. + */ + setOutlineColor(c: string): void; + + /** + * Gets path outline opacity in decimal format. + * @returns {number} Outline opacity. + */ + getOutlineOpacity(): number; + + /** + * Set path outline opacity to a decimal between 0 and 1. + * @param {number} o Outline opacity. + */ + setOutlineOpacity(o: number): void; + + /** + * Gets fill color as a CSS style string. + * @returns {string} Fill color as a CSS style string. + */ + getFillColor(): string; + + /** + * Sets fill color as a CSS style string. + * @param {string} c Fill color as a CSS style string. + */ + setFillColor(c: string): void; + + /** + * Gets fill opacity in decimal format. + * @returns {number} Fill opacity. + */ + getFillOpacity(): number; + + /** + * Sets fill opacity to a decimal between 0 and 1. + * @param {number} o Fill opacity. + */ + setFillOpacity(o: number): void; + + /** + * Gets the dash array as a string. + * @returns {string} Dash array as astring. + */ + getDashArray(): string; + + /** + * Sets dash array string from a CSS style string. Defaults to solid + * stroke if no dash array string is provided. + * @param {string} [da] Dash array as a CSS style string. + */ + setDashArray(da: string): void; + + /** + * Gets optional animation function called when SVG node is created. + * @returns {function} Function with the signature animation(pathElement, loopback). + */ + getAnimation(): (pathElement: HTMLElement, loopback: () => void) => void; + + /** + * You can use the loopback parameter on complete to call itself and + * create repeating animation. + * @param {function} Function with the signature animation(pathElement, loopback). + */ + setAnimation(action: (pathElement: HTMLElement, loopback: () => void) => void): void; + + /** + * Renders this geometry as an SVG path. Note: We attach original + * geometry bounds to svg doc as an expando. + * @param {string} key Identifer to keep track of the SVG DOM element. + * @param {number} mupp Map units per pixel with which to create the SVG element. + * @returns {HTMLElement} A new SVG document root. + */ + createSvgPathElement(key: string, mapUnitsPerPix: number): HTMLElement; + + /** + * Renders this to a canvas context. + * @param {CanvasRenderingContext2D} ctx Canvas context to which to render. + */ + renderPathToCanvasContext(ctx: CanvasRenderingContext2D): void; +} + +/** + * The mapjs version. + */ +export var version: string; + +/** + * Exposes static functions for working with well known text. + * @module wkt + */ +export module wkt { + + /** + * Parses WKT as a point. + * @param {string} w A WKT string. + * @returns {point} The parsed point. + */ + export function parsePoint(wkt: string): point; + + /** + * Parses WKT as a multipoint. + * @param [string} w A WKT string. + * @retuns {geometry} The parsed multipoint geometry. + */ + export function parseMultiPoint(wkt: string): geometry; + + /** + * Parses WKT as an open path geometry with a single set. + * @param {string} w A WKT string. + * @returns {geometry} The parsed open path geometry. + */ + export function parseLineString(wkt: string): geometry; + + /** + * Parses WKT as an open path geometry with multiple sets. + * @param {string} w A WKT string. + * @returns {geometry} The parsed open path geometry. + */ + export function parseMultiLineString(wkt: string): geometry; + + /** + * Parses WKT as a closed path geometry with a single set. + * @param {string} w A WKT string. + * @returns {geometry} The parsed closed path geometry. + */ + export function parsePolygon(wkt: string): geometry; + + /** + * Parses WKT as a closed path geometry with multiple sets. + * @param {string} w A WKT string. + * @returns {geometry} The parsed closed path geometry. + */ + export function parseMultiPolygon(wkt: string): geometry; + + /** + * Parses WKT as a geometry and determines its type from the string. + * @param {string} w The WKT string. + * @returns {any} The parsed shape, a point, geometry, or an array of + * polygons depending on the WKT. + */ + export function parse(wkt: string): any; + + /** + * Converts an array of polygons to an OGC compliant multipolygon WKT string. + * @param {polygon[]} polys Set of polygons to parse into WKT. + * @returns {geometry} The OGC compliant WKT for the polygons. + */ + export function toMultiPolygonString(polys: geometry.polygon[]): string; +} + +/** + * Exposes various tile-related constructors, including layers, descriptors, + * and requestors. + * @module tile + */ +export module tile { + + /** + * A tile layer is a view on the map containing an array of rectangular content. + * @class layer + */ + export class layer { + constructor(id: string, useBackdrop?: boolean, maxConcurrentRequests?: number); + + /** + * @param {number} m - number for margin in pixels + */ + // setContentExtentsMarginInPixels(m: number): void; + + /** + * Gets ID associated with this tile layer. + * @returns {string} ID of the layer. + */ + getId(): string; + + /** + * Determines whether this tile layer uses a backdrop. + * @returns {boolean} Whether or not the layer uses a backdrop. + */ + getUseBackdrop(): boolean; + + /** + * Returns the tile layer's descriptor, which describes how + * requested content is rendered or styled. + * @returns {object} The tile layer's descriptor. + */ + getDescriptor(): any; + + /** + * Sets the tile layer's descriptor, which describes how requested + * content is rendered or styled. + * @param {function} d A descriptor for this tile layer. + */ + setDescriptor(d: any): void; + + /** + * Notifies the tile layer to check for changes to its descriptor. + */ + notifyDescriptorChange(): void; + + /** + * Returns this tile layer's requestor which defines what kind of + * content to get and where to get it. + * @returns {requestor} This tile layer's requestor. + */ + getRequestor(): tile.requestor; + + /** + * Sets this tile layer's requestor, which defines what kind of + * content to get and where to get it. + * @param {tile.requestor} req A requestor object. + * @param {tile.requestor} [desc] Descriptor object so that both + * can be set in one call and incur only one content change event. + */ + setRequestor(req: tile.requestor, desc?: any): void; + + /** + * Returns this tile layer's renderer if it exists, which defines + * how geometry data for a quadView is rendered. + * @returns {renderer} The renderer object. + */ + getRenderer(): tile.renderer; + + /** + * Sets optional renderer which defines how geometry data for + * quadView is rendered. + * @param {renderer} r The renderer delegate function with + * signature renderer(quadview). + */ + setRenderer(r: any): void; + + /** + * Notifies the tile layer to check for changes to its renderer. + */ + notifyRendererChange(): void; + + /** + * Gets the visibility state of this tile layer. + * @returns {boolean} Whether or not this layer is visible. + */ + getIsVisible(): boolean; + + /** + * Sets visibility state of this tile layer. + * @param {boolean} v Whether this layer should be visible or not. + */ + setIsVisible(v: boolean): void; + + /** + * Gets the opacity of this tile layer. + * @returns {number} Opacity as a decimal. + */ + getOpacity(): number; + + /** + * Sets opacity of this tile layer. + * @param {number} o Opacity as a decimal. + */ + setOpacity(o: number): void; + + /** + * Gets minimum zoom level where this tile layer is visible. + * @returns {number} The minimum zoom level. + */ + getMinZoomLevel(): number; + + /** + * Sets minimum zoom level where this tile layer is visible. + * @param {number} minZ The desired minimum zoom level. + */ + setMinZoomLevel(minZ: number): void; + + /** + * Gets maximum zoom level where this tile layer is visible. + * @returns {number} The maximum zoom level. + */ + getMaxZoomLevel(): number; + + /** + * Sets maximum zoom level where this tile layer is visible. + * @param {number} maxZ The desired maximum zoom level. + */ + setMaxZoomLevel(maxZ: number): void; + + /** + * Sets pixel bleed on quadTiles, which defaults to 1. Setting this + * to zero for overlay layers with translucent polygon fills is + * recommended. Bleed overlap can create faint lines at tile + * boundries when fill is not opaque. + * @param {number} bleed The number of pixels to bleed. + */ + setTileBleedPix(bleed: number): void; + + /** + * Sets whether or not to retain and display previous level tile + * content as you change tile levels to provide a nice zoom level + * change effect. Once the next level is loaded the old level + * content is always discarded. This should be set to false if there + * is translucent content to display. Defaults to true (prior to + * version 9.0.0001 this value had the same state as useBackdrop.) + * @param {boolean} ret Whether or not to retain interlevel content. + */ + setRetainInterlevelContent(retain: boolean): void; + + /** + * Enables or disables the fade in on tile content, which defaults to enabled. + * @param {boolean} fadeIn Whether or not fade in on tile content + * should be enabled. + */ + setEnableTileFadeIn(fadeIn: boolean): void; + + /** + * Sets the default action to take on error. + * @param {function} action Function to execute on error. + */ + setNotifyErrorAction(action: () => void): void; + + /** + * Sets an optional function to be called when the tile loading + * queue for this layer has emptied. + * @param {function} action Callback function. + */ + setNotifyLoadingQueueHasEmptiedAction(action: () => void): void; + + /** + * Sets the optional function to be called by this layer's tile + * loader during processing. The supplied progress function takes + * tiles loaded and tiles total parameters. + * @param {function} action Callback of the signature action(tileLoaded, tilesTotal). + */ + setNotifyLoadingQueueProgressAction(action: (tilesLoaded: number, tilesTotal: number) => void): void; + + /** + * Sets optional request processor for this tile layer. This is + * an advanced feature allowing developers to tap into tile + * request pipeline for purposes of customizing requests or manage + * custom caching. This is also the mechanism used for offline + * apps with frameworks such as phonegap. + * @param {function} Processor function with signature + * processor(requestor, descriptor, quad, timeoutMs, complete, error) + */ + setRequestProcessor(processorFunc: ( + requestor: tile.requestor, + descriptor: any, + quad: tile.quad, + timeoutMs: number, + completeAction: (img: HTMLElement) => void, + errorAction: (msg: string) => void) => void): void; + + /** + * Instructs the tile loader to populate a specified tile pyramid. + * This is used to fetch content (e.g. bitmap tiles) and preload + * it into the browser cache. + * @param {envelope} extents Envelope for which to fetch content. + * @param {number} startZoomLevel Minimum zoom level for which to + * fetch content. + * @param {number} endZoomLevel Maximum zoom level for which to + * fetch content. + */ + preload(extents: envelope, startZoomLevel: number, endZoomLevel: number): void; + + /** + * Composes an array of quadtiles with composition information and + * requestor endpoints. This can be used to create static images + * or print-ready versions of this tile layer at arbitrary extents + * (both source and target) For example: If you needed a 5x3 inch + * 300 dpi output you can specify extents in device units to be + * 1500x900. This function determines the correct zoom level so + * that the source extents fits in the target extents to the + * nearest integer zoom level. + * @param {envelope} extentsMapUnits Source extents in map units. + * @param {envelope} extentsDeviceUnits Target extents in pixels. + * @returns {object} Composed object in the form + * {quadCollection, endpointCollection, idxMinX, idxMinY, ulX, ulY } + * where quadCollection is an array of quad objects, endpointCollection + * is an array of REST endpoints from which to obtain the tiled content, + * idxMinX and idxMinY are the minimum x and y tile indicies of the + * collection respectively, and ulX and ulY are the offset in pixels + * of the upper left tile from the upper left target extents. + */ + compose(extentsMapUnits: envelope, extentsDeviceUnits: envelope): { + quadCollection: tile.quad[]; + endpointCollection: string[]; + idxMinX: number; + idxMinY: number; + ulX: number; + ulY: number; + }; + + /** + * Unbind all associations with this tile layer to facilitate garbage collection + */ + dispose(): void; + } + + /** + * A layerOptions object is a method for constructing a tile layer for + * immediate use, for example by passing it to the jQuery widget or + * in the knockout binding. + * @class layerOptions + */ + export class layerOptions { + constructor(id: string, options: { + useBackdrop?: boolean; + maxConcurrentRequests?: number; + requestor?: tile.requestor; + descriptor?: any; + renderer?: tile.renderer; + requestProcessor?: any; + visible?: boolean; + opacity?: number; + minZoomLevel?: number; + maxZoomLevel?: number; + tileBleedPix?: number; + retainInterlevelContent?: boolean; + enableTileFadeIn?: boolean; + notifyErrorAction?: (msg?: string) => void; + notifyLoadingQueueHasEmptiedAction?: () => void; + }); + + /** + * Returns the underlying tile layer. + * @returns {layer} The underlying tile layer. + */ + getTileLayer(): tile.layer; + + /** + * Gets ID associated with the underlying tile layer. + * @returns {string} ID of the layer. + */ + getId(): string; + + /** + * Gets this layerOptions object as a JavaScript object. + */ + getOptions(): any; + } + + /** + * The quad class represents a quad tile within three dimensional + * coordinate space. + * @class quad + */ + export class quad { + + /** + * Gets the x coodinate of this quad tile. + * @returns {number} The x coordinate of this quad tile. + */ + getX(): number; + + /** + * Gets the y coordinate of this quad tile. + * @returns {number} The y coordinate of this quad tile. + */ + getY(): number; + + /** + * Gets the z coordinate of this quad tile, or depth. + * @returns {number} The z coordinate of this quad tile. + */ + getLevel(): number; + + /** + * Gets the envelope in map units which encompasses this quad tile. + * @returns {envelope} The encompassing envelope of this quad tile. + */ + getEnvelope(): envelope; + + /** + * Gets the string representation of this quad tile as a quad key. + * @returns {string} Quad key for this quad tile as a string. + */ + toString(): string; + + /** + * Gets the quad key for this quad tile as a string. + * @returns {string} Quad key for this quad tile as a string. + */ + getKey(): string; + + /** + * Compares this quad tile with another quad tile and determines + * whether or not they are equal. + * @param {quad} Quad tile with which to check for equality with this quad tile. + * @returns {boolean} Result of the equality test. + */ + equals(q: quad): boolean; + + /** + * Generates the quad tile which is a given number of levels above + * this tile in the pyramid and in which this quad tile is contained. + * @param {number} ancestorsBack Number of levels above this tile the + * generated tile should be. + * @returns {quad} The generated parent tile. + */ + factoryParent(ancestorsBack: number): quad; + } + + /** + * Exposes static functions for generating and handling quad tiles. + * @module quad + */ + export module quad { + + /** + * Generates a new quad tile based on a given quad key. + * @param {string} key The quad key from which to generate the quad tile. + * @returns The generated quad tile. + */ + export function factoryQuadFromKey(key: string): quad; + } + + /** + * A tile renderer handles converting JSON vector content loaded from the + * MapDotNet REST feature service into a canvas rendering on a tile. + * @class renderer + */ + export class renderer { + constructor(options? : { + renderPoint?: (pt: point, context: CanvasRenderingContext2D) => void; + renderGeometry?: (shape: geometry, context: CanvasRenderingContext2D) => void; + renderBitmap?: (img: HTMLElement, context: CanvasRenderingContext2D, contextSize: number, bleed: number) => void; + }); + + /** + * Sets the render point function which takes a point and canvas + * context and renders the point to the canvas. The points passed + * in are transformed to pixel units and offset to context origin. + * @param {function} func Function of the form func(shape, context) + * where shape is the point object to be rendered and context is the + * canvas context on which to render. + */ + setRenderPoint(func: (pt: point, context: CanvasRenderingContext2D) => void): void ; + + /** + * Sets render geometry function which takes a geometry and canvas + * context and renders the geometry to the canvas context. The + * geometries passed in are transformed to pixel units and offset + * to the context origin. + * @param {function} func Function with signature func(shape, context) + * where shape is the geometry to render and context is the canvas + * context on which to render. + */ + setRenderGeometry(func: (shape: geometry, context: CanvasRenderingContext2D) => void): void; + + /** + * Sets the render bitmap function which takes a bitmap image and + * a canvas context and renders the image to the canvas context. + * @param {function} func Function with the signature + * func(img, context, contextSize, bleed) where img is the bitmap + * image to render, context is the canvas context on which to + * render the image, contextSize is the size of the canvas context + * in pixels and bleed is the margin around each tile to bleed. + */ + setRenderBitmap(func: (img: HTMLElement, context: CanvasRenderingContext2D, contextSize: number, bleed: number) => void): void; + } + + /** + * An auto-ranging density map renderer. + * @class rendererDensityMap + */ + export class rendererDensityMap { + + constructor(); + + /** + * Sets the bleed ratio, which is the sets the percentage of the + * margin around each tile to use in the tile's computation. Note: + * some bleed (i.e., greater than 1) is required since a heat map + * relies on adjacent data. + * @param {number} bleed The desired bleed ratio. + */ + setBleed(bleed: number): void; + + /** + * Sets the number of rows and columns of cells to be used for + * computation within the grid. + * @param {number} gridSize Number of rows and columns used in + * the grid. + */ + setGridSize(gridSize: number): void; + + /** + * Sets filter radius corresponding to standard deviations. The + * filter radius is the cutoff point at which adjacent cells no + * longer contribute to a cell's calculation. + * @param {number} filterStdDevRadius Number of standard deviations + * from the mean of a normal distribution to which to give positive + * weight. + */ + setFilterStdDevRadius(filterStdDevRadius: number): void; + + /** + * Sets color ranges from cold to hot for the renderer. + * @param {number[][]} matrix Array of arrrays of numbers, each + * of the form [r,g,b,a], where each array represents a color and + * colors range from cold to hot. Note: Typically, a dozen colors + * is sufficient. + */ + setColorMatrix(matrix: number[][]): void; + + /** + * Sets the minimum required cell value for a cell to receive + * a color. Default minimum value is 0. + * @param {number} mcv The minimum cell value for painting. + */ + setMinCellValue(min: number): void; + + /** + * Sets an optional action to perform on each row. This enables + * processing the values on one or more columns for each row for + * use in the density map computations. + * @param {action} ra Function to call on each row with signature + * action(row). The value returned from the function will is added + * to the cell's value. + */ + setRowAction(action: (row: any) => number): void; + + /** + * Tells renderer to re-render density map and recompute ranges. + * This should be called if the data changes or if, due to extent + * changes, the density changes. + */ + notifyRecompute(extents?: envelope): void; + } + + /** + * This is a base requestor class. + * @class requestor + */ + export class requestor { + + constructor(); + + /** + * Gets formatted endpoint using the supplied quadtile and a descriptor. + * @param {quad} quad Quadtile for which to fetch the endpoint. + * @returns {string} The requested URI string. + */ + getFormattedEndpoint(quad: quad, descriptor: any): string; + + /** + * Gets data locally if the requestor supports it. + * @param {quad} quad Quadtile for which to fetch the endpoint. + * @returns {string} The requested JSON data. + */ + getLocalData(quad: quad, descriptor: any): string; + + /** + * Creates unique sha1 hash from this requestor and the supplied + * descriptor. This is useful in creating a unique key or folder + * for tile caching. This combined with a tile's quad-key can + * efficiently and uniquely identify a particular tile. + * @params {descriptor} The descriptor for which to create the hash. + * @returns {string} The generated sha1 hash. + */ + hash(descriptor: any): string; + + /** + * Determines whether or not this requestor returns bitmap images. + * @returns {boolean} Whether or not this requestor returns bitmap + * images. + */ + getIsRestImage(): boolean; + + /** + * Sets whether this requestor should return bitmap images. + * @param {boolean} flag Whether or not this requestor should return + * bitmap images. + */ + setIsRestImage(flag: boolean): void; + + /** + * Determines whether or not this requestor uses an endpoint + * rather than local data. + * @returns {boolean} Whether or not this requestor gets data from + * an endpoint. + */ + getUsesEndpoint(): boolean; + + /** + * Sets whether or not this requestor uses an endpoint rather than + * local data. + * @param {boolean} Whether or not this requestor should get data + * from an endpoint. + */ + setUsesEndpoint(flag: boolean): void; + + /** + * Gets format of data returned by REST service. + * @returns {string} Data format returned by the REST service. + */ + getDataFormat(): string; + + /** + * Sets format of data that should be returned by REST service. + * @param {string} df Name of the data format the REST service + * should use. + */ + setDataFormat(df: string): void; + + /** + * Returns whether or not caching is enabled for vector-based + * requestors. + * @returns {boolean} Whether or not caching is enabled. + */ + getCacheEnabled(): boolean; + + /** + * Sets whether or not caching is enabled for vector-beased requestors. + * @param {boolean} flagce - true (default) if caching is enabled + */ + setCacheEnabled(flag: boolean): void; + + /** + * Gets requestor timeout in miliseconds. + * @returns {number} Requestor timeout in miliseconds. + */ + getTimeoutMs(): number; + + /** + * Sets requestor timeout in miliseconds. + * @param {number} ms Desired requestor timeout in miliseconds. + */ + setTimeoutMs(ms: number): void; + + /** ??? + * Gets the additional + * @returns {object[]} + */ + getKeyVals(): {}[]; + + /** Set any key/value pairs that are attached to the ajax call (such as username and password) + */ + setKeyVals(options: {}[]): void; + + /** + * Gets maximum available zoom level content that can be retrieved + * from the endpoint this requestor consumes. + * @returns {number} The maximum available zoom level for this requestor. + */ + getMaxAvailableZoomLevel(): number; + + /** + * Sets maximum available zoom level content that can be retrieved + * from the endpoint this requestor consumes. Note: This defaults + * to the projection's maximum available zoom level, which is 20 + * in spherical mercator. + * @param {number} max The maximum available zoom level for this requestor. + */ + setMaxAvailableZoomLevel(max: number): void; + } + + /** + * A tile requestor for Microsoft Bing maps. + * @class requestorBing + */ + export class requestorBing extends requestor { + + constructor(options?: { + dataFormat?: string; + timeoutMs?: number; + maxAvailableZoomLevel?: number; + }); + + /** + * Gets the formatted endpoint uri for Bing maps, e.g. + * ecn.t{0}.tiles.virtualearth.net/tiles/{1}{2}{3}?g={4}&mkt={5}&shading=hill. + * @returns {string} endpoint to Bing tile server as a formatted string + */ + getEndpoint(): string; + + /** + * Gets the protocol for the endpoint, either 'http' or 'https'. + * @returns {string} The endpoint protocol. + */ + getScheme(): string; + + /** + * Sets endpoint protocol to either 'http' or 'https'. + * @param {string} s Protocol to use in endpoints. + */ + setScheme(s: string): void; + + /** + * Gets Bing tile generation + * @returns {string} the tile generation as an integer + */ + getGeneration(): string; + + /** + * Sets Bing tile generation + * @param {string} g - generation as an integer + */ + setGeneration(g: string): void; + + /** + * Gets the language code for which the tiles are rendered. The + * default code is 'en-US'. + * @returns {string} The language code for which tiles are rendered. + */ + getMarket(): string; + + /** + * Sets language code for which to render tiles. For example, + * 'en-US'. + * @param {string} m Language code for which to render tiles. + */ + setMarket(m: string): void; + + /** + * Gets the Bing key associated with this requestor. + * @returns {string} The Bing key for this requestor. + */ + getBingKey(): string; + + /** + * Sets Bing key which then calls Microsoft metadata service and + * automatically configures content endpoint. + * @param {string} key Bing key. + */ + setBingKey(key: string): void; + } + + /** + * The bitmap or vector tile requestor using MapDotNet REST services. + * @class requestorMDN + */ + export class requestorMDNRest extends requestor { + constructor(endpoint: string, options?: { + dataFormat?: string; + timeoutMs?: number; + maxAvailableZoomLevel?: number; + }); + + /** + * Gets uri endpoint for the MapDotNet REST service. + * @returns {string} Uri endpoint for the MapDotNet REST service. + */ + getEndpoint(): string; + } + + /** + * Creates an instance of a descriptor for describing content from a + * MapDotNet UX REST map service. + * @class descriptorMDNRestMap + */ + export class descriptorMDNRestMap { + constructor(mapId: string, options?: { + version?: string; + imageType?: string; + bleedRatio?: number; + mapCacheOption?: string; + mapCacheName?: string; + useQuadKeyForMapCacheName?: boolean; + backgroundColorStr?: string; + layerVisibility?: {}; + layerOutline?: {}; + layerFill?: {}; + layerWhere?: {}; + tag?: string; + }); + + /** + * Sets the flag to suspend descriptor change notifications. If + * set true, all changes to this descriptor will not cause the map + * to redraw. Setting to false will enable redraws and immediately + * force a redraw. + * @param {boolean} flag Whether or not descriptor change notifications + * should be enabled. + */ + setSuspendDescriptorChangeNotifications(flag: boolean): void; + + /** + * Gets the map ID. + * @returns {string} The map ID. + */ + getMapId(): string; + + /** + * Gets the REST service version. + * @returns {string} The REST service version. + */ + getVersion(): string; + + /** + * Sets the REST service version. + * @param {string} v The version number. + */ + setVersion(v: string): void; + + /** + * Gets image type associated with this descriptor, either 'png', + * 'png8', or 'jpg'. + * @returns {string} The image type associated with this descriptor. + */ + getImageType(): string; + + /** + * Gets image type associated with this descriptor to one of 'png', + * 'png8', or 'jpg'. + * @param {string} t The image type associated which should be + * associated with this descriptor. + */ + setImageType(t: string): void; + + /** + * Gets bleed ratio for the layer associated with this descriptor. + * @returns {number} The bleed ratio. + */ + getBleedRatio(): number; + + /** + * Sets the bleed ratio. Bleeds greater than 1.0 will fetch content + * beyond the edge of the tile extents (this is useful for point + * features). + * @param {number} br The desired bleed ratio, between 1.0 and 2.0. + */ + setBleedRatio(br: number): void; + + /** + * Gets the map's cache setting, which is one of 'None', + * 'ReadOnly', 'ReadWrite', 'ForceWrite', and 'Default.' + * @returns {string} The map's cache setting. + */ + getMapCacheOption(): string; + + /** + * Gets the map's cache setting to one of 'None', + * 'ReadOnly', 'ReadWrite', 'ForceWrite', and 'Default.' + * @param {string} mco The desired cache setting for the map. + */ + setMapCacheOption(mco: string): void; + + /** + * Gets the optional map cache name. + * @returns {string} The map cache name. + */ + getMapCacheName(): string; + + /** + * Sets the optional map cache name. + * @param {string} mcn The desired map cache name. + */ + setMapCacheName(mcn: string): void; + + /** + * Determines whether the map is flagged to use the quadkey as its + * map cache name. + * @returns {boolean} Whether or not the map has been flagged to + * use the quadkey as its map cache name. + */ + getUseQuadKeyForMapCacheName(): boolean; + + /** + * Sets the flag that uses the quadkey as its map cache name. + * @param {boolean} flag Whether or not the map should be flagged + * to use the quadkey as its map cache name. + */ + setUseQuadKeyForMapCacheName(flag: boolean): void; + + /** + * Gets map image background color. + * @returns {string} CSS style string for the map image background color. + */ + getBackgroundColorStr(): string; + + /** + * Sets the map image background color. + * @param {number} a Alpha level. + * @param {number} r Red level. + * @param {number} g Green level. + * @param {number} b Blue level. + */ + setBackgroundColor(a: number, r: number, g:number, b:number): void; + + /** + * Checks whether or not the map background is transparent. + * @returns {boolean} Whether or not the map background is transparent. + */ + getIsBackgroundTransparent(): boolean; + + /** + * Sets a layer's visibility. + * @param {string} layerId The MapDotNet map layer ID. + * @param {boolean} isVisible Whether or not the layer should be visible. + */ + setLayerVisibility(layerId: string, isVisible: boolean): void; + + /** + * Gets a layer's visibility. + * @param {string} layerId The MapDotNet map layer ID. + * @returns {boolean} Whether or not the layer is visible. + */ + getLayerVisibility(layerId: string): boolean; + + /** + * Sets a layer's outline color and thickness. + * @param {string} layerId The MapDotNet map layer ID. + * @param {number} a Alpha level. + * @param {number} r Red level. + * @param {number} g Green level. + * @param {number} b Blue level. + * @param {number} thk Outline thickness in pixels. + */ + setLayerOutline(layerId: string, a: number, r: number, g: number, b: number, thk: number): void; + + /** + * Gets a layer's outline color and thickness. + * @param {string} layerId The MapDotNet map layer ID. + * @returns {object} JavaScript object of the form {color, thickness} + * where color is the CSS style string of the outline color and + * thickness is the outline thickness in pixels. + */ + getLayerOutline(layerId: string): { color: string; thickness: number; }; + + /** + * Sets a layer's fill color. + * @param {string} layerId The MapDotNet map layer ID. + * @param {number} a Alpha level. + * @param {number} r Red level. + * @param {number} g Green level. + * @param {number} b Blue level. + */ + setLayerFill(layerId: string, a: number, r: number, g: number, b: number): void; + + /** + * Sets a layer's fill color as a SQL expression. + * @param {string} layerId The MapDotNet map layer ID. + * @param {string} exp The SQL expression to select a row's fill color. + */ + setLayerFillAsExpression(layerId: string, exp: string): void; + + /** + * Gets a layer's fill color as a CSS style string or as a SQL expression. + * @param {string} layerId The MapDotNet map layer ID. + * @returns {string} Either the CSS style string or the SQL expression, + * according to how the layer's fill color was set. + */ + getLayerFill(layerId: string): string; + + /** + * Add or replace the where clause for a layer. The where clause + * is a SQL expression used to filter rows. + * @param {string} layerId The MapDotNet map layer ID. + * @param {string} where The desired SQL where expression. + * @param {boolean} [merge] Whether to merge the new where clause + * with the existing where clause using a SQL AND or to replace + * the existing where clause with the new one. Defaults to true (merge). + */ + setLayerWhere(layerId: string, where: string, merge: boolean): void; + + /** + * Sets a separator character for the layer where clause expression + * in the query string. This is set to ',' by default, which is + * consistent with SQL. + * @param {string} sep The desired seperator, which should be a + * single character. + */ + setLayerWhereSep(sep: string): void; + + /** + * Returns the current separator for the layer where clause in the + * query string. + * @returns {string} The current seperator. + */ + getLayerWhereSep(): string; + + /** + * Gets the current layer where clause. + * @param {string} layerId The MapDotNet map layer ID. + * @returns {string} The current where clause. If no where clause + * is in use, this will return an empty string. + */ + getLayerWhere(layerId: string): string; + + /** + * Gets a tag which is used to modify the request URIs to avoid + * browser caching + * @returns {string} The map's tag. + */ + getTag(): string; + + /** + * Sets the map's tag, which is used modify request URIs to avoid + * browser caching. + * @param {string} tag The desired tag. + */ + setTag(tag: string): void; + } + + /** + * Creates an instance of a descriptor for describing content from + * a MapDotNet REST feature service. + * @class descriptorMDNRestFeature + */ + export class descriptorMDNRestFeature { + constructor(mapId: string, layerId: string, options?: { + version?: string; + bleedRatio?: number; + fieldNames?: string[]; + clipToRenderBounds?: boolean; + simplifyEnabled?: boolean; + }); + + /** + * Gets the map ID. + * @returns {string} The map ID. + */ + getMapId(): string; + + /** + * Gets the layer's ID. + * @returns {string} The layer's ID. + */ + getLayerId(): string; + + /** + * Gets the version of the REST service. + * @returns {string} The REST service version. + */ + getVersion(): string; + + /** + * Sets the REST service version number. + * @param {string} v The version number to set. + */ + setVersion(v: string): void; + + /** + * Gets the bleed ratio. + * @returns {number} The current bleed ratio. + */ + getBleedRatio(): number; + + /** + * Sets the bleed ratio. Bleeds greater than 1.0 will fetch content + * beyond the edge of the tile extents (this is useful for point features). + * @param {number} br The desired bleed ratio, a number between 1.0 and 2.0. + */ + setBleedRatio(br: number): void; + + /** + * Gets the optional field names to query. This attribute data may + * be used in dynamic client-side rendering. + * @returns {string[]} An array of field names as strings. + */ + getFieldNames(): string[]; + + /** + * Sets the optional field names to query. This attribute data may be used in + * dynamic client-side rendering. + * @param {string} names - array of strings for each field to query + */ + setFieldNames(names: string[]): void; + + /** + * Checks the flag whether to clip geometry fetched at the bounds + * of the request. + * @returns {boolean} The value of the flag. + */ + getClipToRenderBounds(): boolean; + + /** + * Sets the flag whether to clip geometry fetched at the bounds + * of the request. This can greatly improve performance with large + * complex geometries. Only supported when back-end store is SQL + * 2008/2012 or PostGIS. + * @param {boolean} flag Whether or not to clip geometries fetched + * at the bounds of the request. + */ + setClipToRenderBounds(flag: boolean): void; + + /** + * Checks the flag whether to simplify paths based on the units per + * pixel for the quad tile being requested. + * @returns {boolean} The value of the flag. + */ + getSimplifyEnabled(): boolean; + + /** + * Sets the flag whether to simplify paths based on the units per + * pixel for the quad tile being requested. + * @param {boolean} flag Whether or not to simply paths based on + * the units per pixel. + */ + setSimplifyEnabled(flag: boolean): void; + + /** + * Sets the action to perform on descriptor change. + * @param {function} action Function with signature action(). + */ + setNotifyDescriptorChangeAction(action: () => void): void; + } + + /** + * This is a generic tile requestor suitable for several third-party + * tile servers. These include open street map, map quest, cloudmade, + * Nokia, etc. + * @class requestorOpen + */ + export class requestorOpen extends requestor { + constructor(endpoint: string, subdomains: string[], options?: { + dataFormat?: string; + timeoutMs?: number; + maxAvailableZoomLevel?: number; + }); + } + + /** + * This is a requestor for local collections of data. These local collections may + * originate from inlined code or from datasources other than a MapDotNet REST + * feature service. + * @class requestorLocal + */ + export class requestorLocal extends requestor { + constructor(options?: { + dataFormat?: string; + timeoutMs?: number; + maxAvailableZoomLevel?: number; + data: {}[]; + }); + + /** + * Gets the unparsed source data. + * @returns {object} Array of source data objects. + */ + getSource(): {}[]; + + /** + * Sets source data. + * @param {object} data An array of JavaScript objects to use as + * the requestor source data. + */ + setSource(data: {}[]): void; + + /** + * Returns your source data parsed into theformat { Shapes: [], + * Values: [], Bounds: [] } This may be useful for doing client-side + * queries on the local data where all of the WKT has been parsed + * into points and geometry. There is also a bounds collection to + * do a quick spatial check for complex polygons. + * @returns {object} Parsed data object in the form {Shapes, Values, Bounds}. + */ + getParsedData(): { + Shapes: any[]; + Values: any[]; + Bounds: envelope[]; + }; + } + + /** + * Local descriptor object for describing source data when the source + * data is fecthed by a local requestor. + * @class descriptorLocal + */ + export class descriptorLocal { + constructor(options: { + valueFieldNames: string[]; + geometryFieldName: string; + bleedRatio?: number; + }); + } +} + +interface pointObject { + x: number; + y: number; +} + +interface envObject { + + /** + * @returns {number} minX as integer + */ + minX: number; + + /** + * @returns {number} minY coord as integer + */ + minY: number; + + /** + * @returns {number} maxX coord as integer + */ + maxX: number; + + /** + * @returns {number} maxY coord as integer + */ + maxY: number; +} + +interface extentChangeStatsObj { + + centerX: number; + centerY: number; + centerLat: number; + centerLon: number; + zoomLevel: number; + mapScale: number; + mapScaleProjected: number; + mapUnitsPerPixel: number; + extents: envelope; +} + +interface repositionStatsObj { + + centerX: number; + centerY: number; + zoomLevel: number; + mapUnitsPerPixel: number; +} + +interface beginDigitizeOptions { + key?: string; + shapeType: string; + geometryStyle?: geometryStyle; + styledGeometry?: styledGeometry; + nodeTapAndHoldAction?: (setIdx: number, idx: number) => boolean; + nodeMoveAction?: (x: number, y: number, actionType: string) => any; + shapeChangeAction?: () => void; + envelopeEndAction?: (env: envelope) => void; + circleEndAction?: (circle: geometry.polygon) => void; + suppressNodeAdd?: boolean; + leavePath?: boolean; +} + + +interface styleObj { + fillColor?: string; + fillOpacity?: number; + outlineColor?: string; + outlineOpacity?: number; + outlineThicknessPix?: number + dashArray?: string; +} + +interface mapsjsWidget { + + /** + * Gets the center of the map in spherical mercator. Use + * sphericalMercator.deprojectToLatLon static function to convert to a lat/lon. + * @return {point} A point map center + */ + getMapCenter(): point; + + /** + * Sets the center of the map in spherical mercator. Use + * sphericalMercator.projectFromLatLon static function to convert from a lat/lon. + * @param {point} center The map center as a point + */ + setMapCenter(center: point): void; + + /** + * Same as setMapCenter except will animate from current map center to the + * specified location + * @param {point} center The map center as a point. + * @param {number} [durationMs] Duration in miliseconds. + * @param {function} [completeAction] Callback to perform on animaton complete. + */ + setMapCenterAnimate(center: point, durationMs?: number, completeAction?: () => void): void; + + /** + * Sets the map center to the current geolocation if supported. The map is + * animated to the new location. + * @param {number} [durationMs] Duration in miliseconds. + * @param {function} [completeAction] Callback to perform on animaton complete. + */ + setMapCenterToGeolocationAnimate(durationMs?: number, completeAction?: () => void): void; + + /** + * Offsets the current map center by the specified deltas in pixels. + * @param {number} [dx] offset x in pixels. + * @param {number} [dy] offset y in pixels. + */ + offsetMapCenterByPixelDelta(dx: number, dy: number): void; + + /** + * Offsets the current map center by the specified deltas in pixels - animated version. + * @param {number} [dx] offset x in pixels. + * @param {number} [dy] offset y in pixels. + * @param {number} [durationMs] animation duration in mS. + */ + offsetMapCenterByPixelDeltaAnimate(dx: number, dy: number, durationMs?: number): void; + + /** + * Gets the current zoom level. + * @returns {number} The current zoom level. + */ + getZoomLevel(): number; + + /** + * Sets the current zoom level. + * @param {number} z1 The desired zoom level. + */ + setZoomLevel(zl: number): void; + + /** + * Sets the minimum zoom level for the map. + * @param {number} zl Desired minimum zoom level. + */ + setMinZoomLevel(zl: number): void; + + /** + * Sets the maximum zoom level for the map. + * @param {number} z1 The desired maximum zoom level. + */ + setMaxZoomLevel(zl: number): void; + + /** + * Animates the map from the current zoom level to the given zoom level. + * @param {number} zl The desired zoom level. + * @param {number} [durationMs] The duration in miliseconds. + * @param {function} [completeAction] Function to call when the animation + * completes with signature completeAction(). + */ + setZoomLevelAnimate(zl: number, durationMs?: number, completeAction?: () => void): void; + + /** + * Changes the current zoom level. + * @param {number} delta Change to be added to the current zoom level. + */ + zoomDelta(delta: number): void; + + /** + * Animates a change to the current zoom level. + * @param {number} delta Change to be added to the current zoom level. + * @param {number} [durationMs] Duration in miliseconds. + */ + zoomDeltaAnimate(delta: number, durationMs?: number): void; + + /** + * Animates parabolically from the current map center and zoom level + * to the given map center and zoom level. + * @param {point} center Desired map center as a point. + * @param {number} zl Desired zoom level. + * @param {number} [durationMs] Animation duration in miliseconds. + * @param {function} [completeAction] Function to call after the animation + * completes with signature completeAction(). + */ + flyTo(center: point, zl: number, durationMs?: number, completeAction?: () => void): void; + + /** + * Gets the current map extents in spherical mercator units. + * @return {envelope} envelope The current map extents. + */ + getMapExtents(): envelope; + + /** + * Gets the current map units per pixel. + * @returns {number} Map units (meters) per pixel. + */ + getMapUnitsPerPixel(): number; + + /** + * Gets the map extents' width and height in pixels. + * @returns {object} JavaScript object of the form {w, h} where w is + * the current extents' width in pixels and h is the current extents' + * height in pixels. + */ + getViewExtentsInPix(): { w: number; h: number; }; + + /** + * Gets the current projected map scale. This is the ratio of units on + * the screen to map units depicted. + * @returns {number} Ratio of screen units to map units. + */ + getProjectedMapScale(): number; + + /** + * Gets the current actual map scale. This is the ratio of units on + * the screen to actual units on the earth's surface at the latitude + * of the current map center. + * @returns {number} The ratio of screen units to actual meters. + */ + getActualMapScale(): number; + + /** + * Gets the best fit zoom level based on the supplied map extents for + * the current display extents in pixels. + * @param {envelope} extentsNew New map extents to fit. + * @returns {number} The zoom level which best fits the extents. + */ + getBestFitZoomLevelByExtents(extentsNew: envelope): number; + + /** + * Forces the map to redraw the currently loaded tile and geometry + * content. You should not have to call this as redraws are automatically + * handled during programatic state changes. This would be for edge cases + * where the developer is affecting internal state in an undocumented way. + */ + redraw(): void; + + /** + * Updates the map to the size of its container. This updates internal + * parameters for computing map extents and handling the amount of tile + * content to download. This is handled automatically if the browser + * window is resized. But if you are sizing the map programatically + * (e.g. resizable panel or slider) then call this after the parent + * container has resized. + */ + resize(): void; + + /** + * Pushes a supplied tile layer onto the top of the display stack. + * @param {tile.layer} tl The desired tile layer. + */ + pushTileLayer(tl: tile.layer): void; + + /** + * Removes a tile layer off the top of the display stack + * @returns {tile.layer} The removed tile layer. + */ + popTileLayer(): tile.layer; + + /** + * Removes a tile layer off the display stack by reference + * @param {tile.layer} tl A tile layer to remove. + */ + removeTileLayer(tl: tile.layer): void; + + /** + * Removes all tile layers off the display stack + */ + removeAllTileLayers(): void; + + /** + * Gets the current number of tile layers in the display stack. + * @returns {number} The number of tile layers in the display stack. + */ + getTileLayerCount(): number; + + /** + * Gets a tile layer from the display stack by its key. + * @param {string} key The desired tile layer's key. + * @returns {tile.layer} The tile layer associated with the key, or null + * if no tile layer is associated with the key. + */ + getTileLayer(key: string): tile.layer; + + /** + * Gets a point in map units from supplied coordinates pixel units + * with respect to the currently displayed extents. + * @param {number} x The x coordinate in pixels. + * @param {number} y The y coordinate in pixels. + * @returns {point} The generated point in map units. + */ + computeMapPointFromPixelLocation(x: number, y: number): point; + + /** + * Flags whether or not map extent changes can occur through gestures + * like mouse or touch drag, mouse wheel, or pinch zoom. + * @param {boolean} flag Whether or not gestures should affect map + * extent changes. + */ + setSuspendMapExtentChangesByGestures(flag: boolean): void; + + /** + * Sets the z-order of drawn content in relation to the gesture capture + * panel. The default behavior (false) is to have fixed content and + * geometry underneath the gesture panel in the DOM. If false, all + * pointer events are handled by the gesture capture panel and + * optionally parents of the map control. If true, drawn content will + * receive pointer events first and will block gestures to the map. If + * true, digitizing will not function and polygons will block map + * navigation. In some scenarios you may want to set this to true if you + * are placing fixed content (such as point features) on the map and + * need to handle gestures on the placed content. You can call this + * function at any time to change the order. + * @param {boolean} flag Whether or not the fixed content layer should + * reside above the gesture layer. + */ + setDrawnContentZorderToTop(flag: boolean): void; + + /** + * Add a fixed element to the content area which resides at a z-level + * above tiled map content. These elements do not scale with the map + * scale. This is used to place markers or callouts on the map + * @param {HTMLElement} element Any html that can be added to the DOM. + * @param {number} mapUnitsX The x coordinate of the insertion point in map units. + * @param {number} mapUnitsY The y coordinate of the insertion point in map units. + * @param {function} [addAction] Callback function called after the + * DOM element has been placed with signature addAction(element). + * @param {object} dragOptions JavaScript object of the form {dragEnabled, + * useElementInsteadOfNewGestureOverlay, downAction, moveAction, upAction, + * wheelAction } where dragEnabled flags whether dragging should be + * enabled on the element, and downAction, moveAction, upAction, and + * wheelAction are callback functions invoked on mousedown, mousemove, + * mouseup, and scroll events respectively. + */ + addFixedContentElement( + element: HTMLElement, + mapUnitsX: number, + mapUnitsY: number, + addAction?: (ele: HTMLElement) => void, + dragOptions?: { + dragEnabled: boolean; + useElementInsteadOfNewGestureOverlay: boolean; + downAction?: (downPoint: point) => any; + moveAction?: (movePoint: point) => void; + upAction?: (upPoint: point) => void; + wheelAction?: (delta: number) => void; + } + ): void; + + /** + * Move an existing fixed content element. + * @param {HTMLElement} element The existing DOM element to move. + * @param {number} mapUnitsX The new x coordinate in map units. + * @param {number} mapUnitsY The new y coordinate in map units. + */ + moveFixedContentElement(element: HTMLElement, mapUnitsX: number, mapUnitsY: number): void; + + /** + * Removes a fixed content element. + * @param {HTMLElement} element The DOM element to remove. Note: This + * must be the same element added by addFixedContentElement. + */ + removeFixedContentElement(element: HTMLElement): void; + + /** + * Add a styled path geometry to the content area which resides at a z-level + * above tiled map content. The geometry is converted to SVG and added to the + * content area DOM. If an attempt to add a geometry is made with the same + * key, the geometry is swapped out. You must remove using removePathGeometry + * for resource cleanup. + * @param {styleGeometry} styledGeom The styledGeometry to render. + * @param {string} key String used to tie a geometry to its SVG + * @param {function} addAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. + * @param {function} removeAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. + * rendering in the DOM. + * @returns {element} The SVG element which was added to the DOM. + */ + addPathGeometry( + styledGeom: styledGeometry, + key: string, + addAction?: (svg: SVGElement) => void, + removeAction?: (svg: SVGElement) => void): SVGElement; + + /** + * Updates an existing path geometry to reflect a style change. + * @param {geometryStyle} styleNew The new geometryStyle. + * @param {string} key The key of the geometry to receive the new style. + */ + updatePathGeometryStyle(styleNew: geometryStyle, key: string): void; + + /** + * Removes a styledGeometry from display. + * @param {string} key The key of the geometry to remove. + * @returns {element} The SVG element which was removed from the DOM. + */ + removePathGeometry(key?: string): SVGElement; + + /** + * Initiates digitization on the map control. This creates a new + * geometry and adds verticies to the geometry accord to mouse + * click locations. + * @param {object} options JavaScript object of the form { key, + * shapeType, geometryStyle, styledGeometry, nodeTapAndHoldAction, nodeMoveAction, + * shapeChangeAction, envelopeEndAction, circleEndAction, supressNodeAdd, leavePath } + * where key is a a string associated with this geometry, shapeType + * is the type of shape this geometry is, one of 'polygon', 'polyline', 'multipoint', 'envelope' or 'circle', + * geometryStyle is a geometryStyle which should be applied + * to the digitized geometry, styledGeometry is an optional styledGeometry for existing paths to edit, set this to enter edit mode, + * nodeTapAndHoldAction is a callback invoked + * when any point in the geometry is clicked and held and has the + * signature nodeTapAndHoldAction(setIdx, idx), nodeMoveAction is a + * callback invoked after any node is dragged to a new location and + * has signature nodeMoveAction(x, y, actionType), shapeChangeAction + * is a callback that is invoked after the geometry shape changes and, + * has signature shapeChangeAction(shape), envelopeEndAction is a callback + * invoked after an envelope is created and has signature envelopeEndAction(envelope), + * circleEndAction is similar to envelopeEndAction but takes a geometry.polygon representing the circle, + * and leavePath is a flag that indicates whether the digitized shape + * should be left on the map after digitization is complete. + */ + beginDigitize(options: beginDigitizeOptions): void; + endDigitize(): void; + + /** + * Gets a snapshot copy of the currently digitizing path. + * @returns {geometry} The currently digitizing path. + */ + getDigitizeSnapshot(): geometry; + + /** + * Forces additional digitized points to be pushed to a new set of the + * currently digitizing geometry. + */ + pushSetOnDigitizePath(): void; + + /** + * Removes the last set from the currently digitizing path. + * @return {number[]} The last set from the currently digitizing path + * in the form [xn,yn]. + */ + popSetFromDigitizePath(): number[]; + + /** + * Programmatically delete a node from the currently digitizing path. + * @param {number} setIdx The index of the set from which to remove the node. + * @param {number} nodeIdx The index of the node to remove. + */ + deleteNodeOnDigitizePath(setIdx: number, nodeIdx: number): void; + + /** + * Determines whether a shape is currently being digitized. + * @returns {boolean} Whether or not a shape is being digitized. + */ + isDigitizingEnabled(): boolean; + + /** + * Set the function called when the map extents have stopped changing + * (e.g. after an animated pan or zoom). + * @param {function} action The function to call when the extents + * finish changing with signature action(object) where object is of + * the form { centerX, centerY, centerLat, centerLon, zoomLevel, mapScale, + * mapScaleProjected, mapUnitsPerPixel, extents }. + */ + setExtentChangeCompleteAction(action: (vals: extentChangeStatsObj) => void): void; + + /** + * Set the function called when map content (map tiles and fixed elements) are + * re-positioned in the DOM. This is done automatically as the map is panned + * beyond existing content and zoomed to a new level requiring content. + * @param {function} action The function to call when the map content + * completes repositioning with signature action(object) where object + * is of the form { centerX, centerY, zoomLevel, mapUnitsPerPixel }. + */ + setContentRepositionAction(action: (vals: repositionStatsObj) => void): void; + + /** + * Sets function called when map is clicked or tapped. + * @param {function} action The function to call on mouse click or tap + * with signature action(point). + */ + setPointerClickAction(action: (pt: point) => void): void; + + /** + * Sets function called when the map pointer hovers over the map. + * @param {function} action The function to call on mouse hover with + * signature action(point). + */ + setPointerHoverAction(action: (pt: point) => void): void; + + /** + * Sets the margin around the map in pixels for extra content fetched so that tile + * rebuilding of the display is minimized. This is an advanced property and does not + * generally need to be adjusted. The default is 128 pixels, or half the width + * of a tile. This should be increased for maps which are very large in pixels + * or where panning is constant. This should be decreased for very small maps, + * such as on mobile devices, or where panning is minimal. + * @param {number} cem The content extent margin in pixels. + */ + setContentExtentsMarginInPixels(cem: number): void; + + /** + * Sets the background color of the map using a css color string + * @param {number} b- a css color string + */ + setBackground(b: string): void; +} + + interface JQuery { rimMap(): JQuery; diff --git a/maquette/index.d.ts b/maquette/index.d.ts index 085db7796c..31c18a0bbc 100644 --- a/maquette/index.d.ts +++ b/maquette/index.d.ts @@ -375,6 +375,5 @@ declare namespace maquette { } } -declare module 'maquette' { - export = maquette; -} +export = maquette; +export as namespace maquette; diff --git a/maquette/maquette-tests.ts b/maquette/maquette-tests.ts index 8d1a4b0516..be4b4f33f1 100644 --- a/maquette/maquette-tests.ts +++ b/maquette/maquette-tests.ts @@ -1,4 +1,4 @@ - +import maquette = require("maquette"); // The hello world example from the homepage of maquettejs.org: diff --git a/mariasql/index.d.ts b/mariasql/index.d.ts index fd1361910e..d0a3a5e041 100644 --- a/mariasql/index.d.ts +++ b/mariasql/index.d.ts @@ -109,7 +109,5 @@ declare namespace mariasql { } } -declare module "mariasql" { - var Client:mariasql.Client; - export = Client; -} +declare var Client:mariasql.Client; +export = Client; diff --git a/mariasql/mariasql-tests.ts b/mariasql/mariasql-tests.ts index cd83f640a0..f29fc3f2d5 100644 --- a/mariasql/mariasql-tests.ts +++ b/mariasql/mariasql-tests.ts @@ -8,7 +8,7 @@ import util = require('util'); import Client = require('mariasql'); -var c:mariasql.MariaClient = new Client(), +var c = new Client(), inspect = util.inspect; c.connect({ diff --git a/matter-js/index.d.ts b/matter-js/index.d.ts index eccd892df5..b33c40e856 100644 --- a/matter-js/index.d.ts +++ b/matter-js/index.d.ts @@ -4,9 +4,8 @@ // David Asmuth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'matter-js' { - export = Matter; -} +export = Matter; +export as namespace Matter; declare namespace Matter { /** diff --git a/matter-js/matter-js-tests.ts b/matter-js/matter-js-tests.ts index b6c8b01a83..d94a1b6bed 100644 --- a/matter-js/matter-js-tests.ts +++ b/matter-js/matter-js-tests.ts @@ -1,3 +1,4 @@ +import Matter = require("matter-js"); var Engine = Matter.Engine, World = Matter.World, Body = Matter.Body, diff --git a/mdns/index.d.ts b/mdns/index.d.ts index 2b7e77bed7..1e6466895f 100644 --- a/mdns/index.d.ts +++ b/mdns/index.d.ts @@ -289,7 +289,5 @@ declare namespace MDNS { var kDNSServiceProtocol_TCP:number; } -declare module "mdns" { - export = MDNS; -} +export = MDNS; \ No newline at end of file diff --git a/mdns/mdns-tests.ts b/mdns/mdns-tests.ts index 11ed2f007e..d934a59a87 100644 --- a/mdns/mdns-tests.ts +++ b/mdns/mdns-tests.ts @@ -4,18 +4,18 @@ -var mdns = require('mdns') +import mdns = require('mdns') -var ad:MDNS.Advertisement = mdns.createAdvertisement(mdns.tcp('http'), 4321); +var ad:mdns.Advertisement = mdns.createAdvertisement(mdns.tcp('http'), 4321); ad.start(); var browser = mdns.createBrowser(mdns.tcp('http')); -browser.on('serviceUp', function(service:MDNS.Service) { +browser.on('serviceUp', function(service:mdns.Service) { console.log("service up: ", service); }); -browser.on('serviceDown', function(service:MDNS.Service) { +browser.on('serviceDown', function(service:mdns.Service) { console.log("service down: ", service); }); @@ -32,7 +32,7 @@ var txt_record = { , chunky: true , strips: 5 }; -var ad:MDNS.Advertisement = mdns.createAdvertisement(mdns.tcp('http'), 4321, {txtRecord: txt_record}); +var ad:mdns.Advertisement = mdns.createAdvertisement(mdns.tcp('http'), 4321, {txtRecord: txt_record}); var sequence = [ mdns.rst.DNSServiceResolve() @@ -41,7 +41,7 @@ var sequence = [ var browser = mdns.createBrowser(mdns.tcp('http'), {resolverSequence: sequence}); -interface HammerTimeService extends MDNS.Service { +interface HammerTimeService extends mdns.Service { hammerTime:Date; } @@ -60,7 +60,7 @@ function MCHammer(options:any) { var browser = mdns.createBrowser( mdns.tcp('http') , { networkInterface: mdns.loopbackInterface()}); -var ad:MDNS.Advertisement; +var ad:mdns.Advertisement; function createAdvertisement() { try { @@ -72,7 +72,7 @@ function createAdvertisement() { } } -function handleError(error:MDNS.DnsSdError) { +function handleError(error:mdns.DnsSdError) { switch (error.errorCode) { case mdns.kDNSServiceErr_Unknown: console.warn(error); diff --git a/method-override/index.d.ts b/method-override/index.d.ts index a59ec55383..7037fbb99a 100644 --- a/method-override/index.d.ts +++ b/method-override/index.d.ts @@ -11,17 +11,15 @@ declare namespace Express { } } -declare module "method-override" { - import express = require('express'); +import express = require('express'); - namespace e { - export interface MethodOverrideOptions { - methods: string[]; - } +declare namespace e { + export interface MethodOverrideOptions { + methods: string[]; } - - function e(getter?: string, options?: e.MethodOverrideOptions): express.RequestHandler; - function e(getter?: (req: express.Request, res: express.Response) => string, options?: e.MethodOverrideOptions): express.RequestHandler; - - export = e; } + +declare function e(getter?: string, options?: e.MethodOverrideOptions): express.RequestHandler; +declare function e(getter?: (req: express.Request, res: express.Response) => string, options?: e.MethodOverrideOptions): express.RequestHandler; + +export = e; diff --git a/microgears/index.d.ts b/microgears/index.d.ts index 47e19b4e31..399a701eb2 100644 --- a/microgears/index.d.ts +++ b/microgears/index.d.ts @@ -20,7 +20,7 @@ declare namespace microgears { interface Plugin { name: string; - beforeChain(arguments: Array, metaInfo: MetaInformation): Array; + beforeChain(args: Array, metaInfo: MetaInformation): Array; afterChain(result: T, metaInfo: MetaInformation): T; } @@ -28,6 +28,4 @@ declare namespace microgears { function addPlugin(plugin: Plugin): void; } -declare module "microgears" { - export = microgears; -} \ No newline at end of file +export = microgears; \ No newline at end of file diff --git a/microgears/microgears-tests.ts b/microgears/microgears-tests.ts index 1e879a89b2..376d0b8172 100644 --- a/microgears/microgears-tests.ts +++ b/microgears/microgears-tests.ts @@ -1,4 +1,4 @@ - +import microgears = require("microgears"); function verify_module_file() { diff --git a/minilog/index.d.ts b/minilog/index.d.ts index a2979a9cfe..6e382f169d 100644 --- a/minilog/index.d.ts +++ b/minilog/index.d.ts @@ -97,6 +97,5 @@ declare namespace Minilog { } -declare module 'minilog' { - export = Minilog; -} +export = Minilog; +export as namespace Minilog; diff --git a/minilog/minilog-tests.ts b/minilog/minilog-tests.ts index dfebc67ba1..adf7c63ed1 100644 --- a/minilog/minilog-tests.ts +++ b/minilog/minilog-tests.ts @@ -5,7 +5,7 @@ //Following are example snippets from mixu.net/minilog - +import Minilog = require("minilog"); var log = Minilog('app'); Minilog.enable(); diff --git a/moviedb/index.d.ts b/moviedb/index.d.ts index 440641a2a8..f7e7c3558c 100644 --- a/moviedb/index.d.ts +++ b/moviedb/index.d.ts @@ -88,7 +88,5 @@ declare namespace MovieDB { } } -declare module 'moviedb' { - function apiKeyAcceptor(key: string): MovieDB.IMovieDB; - export = apiKeyAcceptor; -} +declare function apiKeyAcceptor(key: string): MovieDB.IMovieDB; +export = apiKeyAcceptor; diff --git a/moviedb/moviedb-tests.ts b/moviedb/moviedb-tests.ts index ae2e66d3d3..8bfea0bd18 100644 --- a/moviedb/moviedb-tests.ts +++ b/moviedb/moviedb-tests.ts @@ -1,20 +1,20 @@ import moviedb = require('moviedb'); export class TmbdMovieScanner { - movieDb: MovieDB.IMovieDB; + movieDb: any; constructor() { this.movieDb = moviedb('YOUR API KEY'); // For testing purposes - this.movieDb.searchMovie({ query: "Aliens" }, (err, movies) => { + this.movieDb.searchMovie({ query: "Aliens" }, (err: any, movies: any) => { if (err) { console.log('Error: ' + err); return; } console.log(movies); }); - this.movieDb.movieInfo({ id: 666 }, (err, curMovie) => { + this.movieDb.movieInfo({ id: 666 }, (err: any, curMovie: any) => { if (err) { console.log('Error: ' + err); return; diff --git a/msportalfx-test/index.d.ts b/msportalfx-test/index.d.ts index beb8657d79..073097e302 100644 --- a/msportalfx-test/index.d.ts +++ b/msportalfx-test/index.d.ts @@ -5,6 +5,8 @@ /// +export = MsPortalTestFx; + declare namespace MsPortalTestFx { export module Locators { @@ -306,9 +308,3 @@ declare namespace MsPortalTestFx { export var portal: Portal; } - - - -declare module "MsPortalFx-Test" { - export = MsPortalTestFx; -} diff --git a/multer/index.d.ts b/multer/index.d.ts index 31f7b605f0..e408e2b268 100644 --- a/multer/index.d.ts +++ b/multer/index.d.ts @@ -3,7 +3,79 @@ // Definitions by: jt000 , vilicvane , David Broder-Rodgers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import express = require('express'); +declare namespace multer { + interface Field { + /** The field name. */ + name: string; + /** Optional maximum number of files per field to accept. */ + maxCount?: number; + } + + interface Options { + /** The destination directory for the uploaded files. */ + dest?: string; + /** The storage engine to use for uploaded files. */ + storage?: StorageEngine; + /** An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods */ + limits?: { + /** Max field name size (Default: 100 bytes) */ + fieldNameSize?: number; + /** Max field value size (Default: 1MB) */ + fieldSize?: number; + /** Max number of non- file fields (Default: Infinity) */ + fields?: number; + /** For multipart forms, the max file size (in bytes)(Default: Infinity) */ + fileSize?: number; + /** For multipart forms, the max number of file fields (Default: Infinity) */ + files?: number; + /** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */ + parts?: number; + /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ + headerPairs?: number; + }; + /** A function to control which files to upload and which to skip. */ + fileFilter?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, acceptFile: boolean) => void) => void; + } + + interface StorageEngine { + _handleFile(req: express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; + _removeFile(req: express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; + } + + interface DiskStorageOptions { + /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ + destination?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void; + /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ + filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; + } + + interface Instance { + /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ + single(fieldame: string): express.RequestHandler; + /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ + array(fieldame: string, maxCount?: number): express.RequestHandler; + /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ + 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; + } +} + +interface Multer { + + (options?: multer.Options): multer.Instance; + + /* The disk storage engine gives you full control on storing files to disk. */ + diskStorage(options: multer.DiskStorageOptions): multer.StorageEngine; + /* The memory storage engine stores the files in memory as Buffer objects. */ + memoryStorage(): multer.StorageEngine; +} + +declare var multer: Multer; + +export = multer; declare namespace Express { export interface Request { @@ -36,79 +108,3 @@ declare namespace Express { } } } - -declare module "multer" { - import express = require('express'); - - namespace multer { - interface Field { - /** The field name. */ - name: string; - /** Optional maximum number of files per field to accept. */ - maxCount?: number; - } - - interface Options { - /** The destination directory for the uploaded files. */ - dest?: string; - /** The storage engine to use for uploaded files. */ - storage?: StorageEngine; - /** An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods */ - limits?: { - /** Max field name size (Default: 100 bytes) */ - fieldNameSize?: number; - /** Max field value size (Default: 1MB) */ - fieldSize?: number; - /** Max number of non- file fields (Default: Infinity) */ - fields?: number; - /** For multipart forms, the max file size (in bytes)(Default: Infinity) */ - fileSize?: number; - /** For multipart forms, the max number of file fields (Default: Infinity) */ - files?: number; - /** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */ - parts?: number; - /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ - headerPairs?: number; - }; - /** A function to control which files to upload and which to skip. */ - fileFilter?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, acceptFile: boolean) => void) => void; - } - - interface StorageEngine { - _handleFile(req: express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; - _removeFile(req: express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; - } - - interface DiskStorageOptions { - /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ - destination?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void; - /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ - filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; - } - - interface Instance { - /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ - single(fieldame: string): express.RequestHandler; - /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ - array(fieldame: string, maxCount?: number): express.RequestHandler; - /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ - 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; - } - } - - interface Multer { - - (options?: multer.Options): multer.Instance; - - /* The disk storage engine gives you full control on storing files to disk. */ - diskStorage(options: multer.DiskStorageOptions): multer.StorageEngine; - /* The memory storage engine stores the files in memory as Buffer objects. */ - memoryStorage(): multer.StorageEngine; - } - - var multer: Multer; - - export = multer; -} diff --git a/navigation/index.d.ts b/navigation/index.d.ts index 79dc718c90..3e4107983a 100644 --- a/navigation/index.d.ts +++ b/navigation/index.d.ts @@ -2,9 +2,7 @@ // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'navigation' { - export = Navigation; -} +export = Navigation; declare namespace Navigation { /** diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index 4adf892fa4..1d6019bb17 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -1,3 +1,4 @@ +import Navigation = require("navigation"); namespace NavigationTests { diff --git a/nedb/index.d.ts b/nedb/index.d.ts index 8ae1f99d1b..6eec23843a 100644 --- a/nedb/index.d.ts +++ b/nedb/index.d.ts @@ -3,155 +3,153 @@ // Definitions by: Stefan Steinhart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "nedb" { +declare class NeDBDataStore { - class NeDBDataStore { + constructor(); + constructor(path:string); + constructor(options:NeDB.DataStoreOptions); - constructor(); - constructor(path:string); - constructor(options:NeDB.DataStoreOptions); + persistence:NeDB.Persistence; - persistence:NeDB.Persistence; + /** + * Load the database from the datafile, and trigger the execution of buffered commands if any + */ + loadDatabase(cb?:(err:Error)=>void):void; - /** - * Load the database from the datafile, and trigger the execution of buffered commands if any - */ - loadDatabase(cb?:(err:Error)=>void):void; - - /** - * Get an array of all the data in the database - */ - getAllData():Array; + /** + * Get an array of all the data in the database + */ + getAllData():Array; - /** - * Reset all currently defined indexes - */ - resetIndexes(newData:any):void; + /** + * Reset all currently defined indexes + */ + resetIndexes(newData:any):void; - /** - * Ensure an index is kept for this field. Same parameters as lib/indexes - * For now this function is synchronous, we need to test how much time it takes - * We use an async API for consistency with the rest of the code - * @param {String} options.fieldName - * @param {Boolean} options.unique - * @param {Boolean} options.sparse - * @param {Function} cb Optional callback, signature: err - */ - ensureIndex(options:NeDB.EnsureIndexOptions, cb?:(err:Error)=>void):void; + /** + * Ensure an index is kept for this field. Same parameters as lib/indexes + * For now this function is synchronous, we need to test how much time it takes + * We use an async API for consistency with the rest of the code + * @param {String} options.fieldName + * @param {Boolean} options.unique + * @param {Boolean} options.sparse + * @param {Function} cb Optional callback, signature: err + */ + ensureIndex(options:NeDB.EnsureIndexOptions, cb?:(err:Error)=>void):void; - /** - * Remove an index - * @param {String} fieldName - * @param {Function} cb Optional callback, signature: err - */ - removeIndex(fieldName:string, cb?:(err:Error)=>void):void; + /** + * Remove an index + * @param {String} fieldName + * @param {Function} cb Optional callback, signature: err + */ + removeIndex(fieldName:string, cb?:(err:Error)=>void):void; - /** - * Add one or several document(s) to all indexes - */ - addToIndexes(doc:T):void; - addToIndexes(doc:Array):void; + /** + * Add one or several document(s) to all indexes + */ + addToIndexes(doc:T):void; + addToIndexes(doc:Array):void; - /** - * Remove one or several document(s) from all indexes - */ - removeFromIndexes(doc:T):void; - removeFromIndexes(doc:Array):void; + /** + * Remove one or several document(s) from all indexes + */ + removeFromIndexes(doc:T):void; + removeFromIndexes(doc:Array):void; - /** - * Update one or several documents in all indexes - * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs - * If one update violates a constraint, all changes are rolled back - */ - updateIndexes(oldDoc:T, newDoc:T):void; - updateIndexes(updates:Array<{oldDoc:T; newDoc:T;}>):void; + /** + * Update one or several documents in all indexes + * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs + * If one update violates a constraint, all changes are rolled back + */ + updateIndexes(oldDoc:T, newDoc:T):void; + updateIndexes(updates:Array<{oldDoc:T; newDoc:T;}>):void; - /** - * Return the list of candidates for a given query - * Crude implementation for now, we return the candidates given by the first usable index if any - * We try the following query types, in this order: basic match, $in match, comparison match - * One way to make it better would be to enable the use of multiple indexes if the first usable index - * returns too much data. I may do it in the future. - * - * TODO: needs to be moved to the Cursor module - */ - getCandidates(query:any):void; + /** + * Return the list of candidates for a given query + * Crude implementation for now, we return the candidates given by the first usable index if any + * We try the following query types, in this order: basic match, $in match, comparison match + * One way to make it better would be to enable the use of multiple indexes if the first usable index + * returns too much data. I may do it in the future. + * + * TODO: needs to be moved to the Cursor module + */ + getCandidates(query:any):void; - /** - * Insert a new document - * @param {Function} cb Optional callback, signature: err, insertedDoc - */ - insert(newDoc:T, cb?:(err:Error, document:T)=>void):void; + /** + * Insert a new document + * @param {Function} cb Optional callback, signature: err, insertedDoc + */ + insert(newDoc:T, cb?:(err:Error, document:T)=>void):void; - /** - * Count all documents matching the query - * @param {any} query MongoDB-style query - */ - count(query:any, callback:(err:Error, n:number)=>void):void; - count(query:any):NeDB.CursorCount; + /** + * Count all documents matching the query + * @param {any} query MongoDB-style query + */ + count(query:any, callback:(err:Error, n:number)=>void):void; + count(query:any):NeDB.CursorCount; - /** - * Find all documents matching the query - * If no callback is passed, we return the cursor so that user can limit, skip and finally exec - * @param {any} query MongoDB-style query - * @param {any} projection MongoDB-style projection - */ - find(query:any, projection:T, callback:(err:Error, documents:Array)=>void):void; - find(query:any, projection:T):NeDB.Cursor; + /** + * Find all documents matching the query + * If no callback is passed, we return the cursor so that user can limit, skip and finally exec + * @param {any} query MongoDB-style query + * @param {any} projection MongoDB-style projection + */ + find(query:any, projection:T, callback:(err:Error, documents:Array)=>void):void; + find(query:any, projection:T):NeDB.Cursor; - /** - * Find all documents matching the query - * If no callback is passed, we return the cursor so that user can limit, skip and finally exec - * * @param {any} query MongoDB-style query - */ - find(query:any, callback:(err:Error, documents:Array)=>void):void; - find(query:any):NeDB.Cursor; + /** + * Find all documents matching the query + * If no callback is passed, we return the cursor so that user can limit, skip and finally exec + * * @param {any} query MongoDB-style query + */ + find(query:any, callback:(err:Error, documents:Array)=>void):void; + find(query:any):NeDB.Cursor; - /** - * Find one document matching the query - * @param {any} query MongoDB-style query - * @param {any} projection MongoDB-style projection - */ - findOne(query:any, projection:T, callback:(err:Error, document:T)=>void):void; + /** + * Find one document matching the query + * @param {any} query MongoDB-style query + * @param {any} projection MongoDB-style projection + */ + findOne(query:any, projection:T, callback:(err:Error, document:T)=>void):void; - /** - * Find one document matching the query - * @param {any} query MongoDB-style query - */ - findOne(query:any, callback:(err:Error, document:T)=>void):void; + /** + * Find one document matching the query + * @param {any} query MongoDB-style query + */ + findOne(query:any, callback:(err:Error, document:T)=>void):void; - /** - * Update all docs matching query - * For now, very naive implementation (recalculating the whole database) - * @param {any} query - * @param {any} updateQuery - * @param {Object} options Optional options - * options.multi If true, can update multiple documents (defaults to false) - * options.upsert If true, document is inserted if the query doesn't match anything - * @param {Function} cb Optional callback, signature: err, numReplaced, upsert (set to true if the update was in fact an upsert) - * - * @api private Use Datastore.update which has the same signature - */ - update(query:any, updateQuery:any, options?:NeDB.UpdateOptions, cb?:(err:Error, numberOfUpdated:number, upsert:boolean)=>void):void; + /** + * Update all docs matching query + * For now, very naive implementation (recalculating the whole database) + * @param {any} query + * @param {any} updateQuery + * @param {Object} options Optional options + * options.multi If true, can update multiple documents (defaults to false) + * options.upsert If true, document is inserted if the query doesn't match anything + * @param {Function} cb Optional callback, signature: err, numReplaced, upsert (set to true if the update was in fact an upsert) + * + * @api private Use Datastore.update which has the same signature + */ + update(query:any, updateQuery:any, options?:NeDB.UpdateOptions, cb?:(err:Error, numberOfUpdated:number, upsert:boolean)=>void):void; - /** - * Remove all docs matching the query - * For now very naive implementation (similar to update) - * @param {Object} query - * @param {Object} options Optional options - * options.multi If true, can update multiple documents (defaults to false) - * @param {Function} cb Optional callback, signature: err, numRemoved - * - * @api private Use Datastore.remove which has the same signature - */ - remove(query:any, options:NeDB.RemoveOptions, cb?:(err:Error, n:number)=>void):void; - remove(query:any, cb?:(err:Error, n:number)=>void):void; - } - - export = NeDBDataStore; + /** + * Remove all docs matching the query + * For now very naive implementation (similar to update) + * @param {Object} query + * @param {Object} options Optional options + * options.multi If true, can update multiple documents (defaults to false) + * @param {Function} cb Optional callback, signature: err, numRemoved + * + * @api private Use Datastore.remove which has the same signature + */ + remove(query:any, options:NeDB.RemoveOptions, cb?:(err:Error, n:number)=>void):void; + remove(query:any, cb?:(err:Error, n:number)=>void):void; } +export = NeDBDataStore; +export as namespace Nedb; + declare namespace NeDB { interface Cursor { diff --git a/nedb/nedb-tests.ts b/nedb/nedb-tests.ts index bc6b78b052..14b122e64c 100644 --- a/nedb/nedb-tests.ts +++ b/nedb/nedb-tests.ts @@ -147,7 +147,7 @@ class BaseCollection { return deferred.promise; } - public update(query:Object, updateQuery:Object, options?:NeDB.UpdateOptions):Q.Promise { + public update(query:Object, updateQuery:Object, options?:any):Q.Promise { var deferred = Q.defer(); diff --git a/needle/index.d.ts b/needle/index.d.ts index e5b61b4b6a..63270e3ff8 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -5,6 +5,9 @@ /// +declare var needle: Needle.NeedleStatic; +export = needle; + declare namespace Needle { interface ReadableStream extends NodeJS.ReadableStream { } @@ -92,8 +95,3 @@ declare namespace Needle { request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; } } - -declare module "needle" { - var needle: Needle.NeedleStatic; - export = needle; -} diff --git a/ng-cordova/tsd.d.ts b/ng-cordova/index.d.ts similarity index 100% rename from ng-cordova/tsd.d.ts rename to ng-cordova/index.d.ts diff --git a/ng-dialog/index.d.ts b/ng-dialog/index.d.ts index 7c5d565e02..f164ec1b69 100644 --- a/ng-dialog/index.d.ts +++ b/ng-dialog/index.d.ts @@ -5,253 +5,255 @@ /// -declare module "ng-dialog" { - export type IDialogService = angular.dialog.IDialogService; - export type IDialogOpenResult = angular.dialog.IDialogOpenResult; - export type IDialogClosePromise = angular.dialog.IDialogClosePromise; - export type IDialogProvider = angular.dialog.IDialogProvider; - export type IDialogScope = angular.dialog.IDialogScope; - export type IDialogConfirmScope = angular.dialog.IDialogConfirmScope; - export type IDialogOptions = angular.dialog.IDialogOptions; - export type IDialogOpenOptions = angular.dialog.IDialogOpenOptions; - export type IDialogOpenConfirmOptions = angular.dialog.IDialogOpenConfirmOptions; -} +import * as angular from 'angularjs'; -declare namespace angular.dialog { +export type IDialogService = angular.dialog.IDialogService; +export type IDialogOpenResult = angular.dialog.IDialogOpenResult; +export type IDialogClosePromise = angular.dialog.IDialogClosePromise; +export type IDialogProvider = angular.dialog.IDialogProvider; +export type IDialogScope = angular.dialog.IDialogScope; +export type IDialogConfirmScope = angular.dialog.IDialogConfirmScope; +export type IDialogOptions = angular.dialog.IDialogOptions; +export type IDialogOpenOptions = angular.dialog.IDialogOpenOptions; +export type IDialogOpenConfirmOptions = angular.dialog.IDialogOpenConfirmOptions; - interface IDialogService { - getDefaults(): IDialogOptions; - open(options: IDialogOpenOptions): IDialogOpenResult; - openConfirm(options: IDialogOpenConfirmOptions): IPromise; +declare module 'angularjs' { + export namespace dialog { + + interface IDialogService { + getDefaults(): IDialogOptions; + open(options: IDialogOpenOptions): IDialogOpenResult; + openConfirm(options: IDialogOpenConfirmOptions): IPromise; + + /** + * Determine whether the specified dialog is open or not. + * @param id Dialog id to check for. + * @returns {boolean} Indicating whether it exists or not. + */ + isOpen(id: string): boolean; + close(id: string, value?: any): void; + closeAll(value?: any): void; + getOpenDialogs(): string[]; + } + + interface IDialogOpenResult { + id: string; + close: (value?: any) => void; + closePromise: IPromise; + } + + interface IDialogClosePromise { + id: string; + value: any; + } + + interface IDialogProvider extends angular.IServiceProvider { + /** + * Default options for the dialogs. + * @param defaultOptions + * @returns {} + */ + setDefaults(defaultOptions: IDialogOptions): void; + + /** + * Adds an additional listener on every $locationChangeSuccess event and gets update version of html into dialog. + * May be useful in some rare cases when you're dependant on DOM changes, defaults to false. + * @param {boolean} force + */ + setForceHtmlReload(force: boolean) : void; + + /** + * Adds additional listener on every $locationChangeSuccess event and gets updated version of body into dialog. + * Maybe useful in some rare cases when you're dependant on DOM changes, defaults to false. Use it in module's + * config as provider instance: + * @param {boolean} force + */ + setForceBodyReload(force: boolean) : void; + } /** - * Determine whether the specified dialog is open or not. - * @param id Dialog id to check for. - * @returns {boolean} Indicating whether it exists or not. + * Dialog Scope which extends the $scope. */ - isOpen(id: string): boolean; - close(id: string, value?: any): void; - closeAll(value?: any): void; - getOpenDialogs(): string[]; - } + interface IDialogScope extends angular.IScope { + /** + * This allows you to close dialog straight from handler in a popup element. + * @param value Any value passed to this function will be attached to the object which resolves on the close promise for this dialog. + * For dialogs opened with the openConfirm() method the value is used as the reject reason. + */ + closeThisDialog(value?: any): void; - interface IDialogOpenResult { - id: string; - close: (value?: any) => void; - closePromise: IPromise; - } + /** + * Any serializable data that you want to be stored in the controller's dialog scope. + * From version 0.3.6 $scope.ngDialogData keeps references to the objects instead of copying them. + */ + ngDialogData : string | {} | any[]; - interface IDialogClosePromise { - id: string; - value: any; - } + /** + * The id of the dialog. If you you ngDialogData, it'll be also available under ngDialogData.ngDialogId + */ + ngDialogId : string; + } - interface IDialogProvider extends angular.IServiceProvider { - /** - * Default options for the dialogs. - * @param defaultOptions - * @returns {} - */ - setDefaults(defaultOptions: IDialogOptions): void; + interface IDialogConfirmScope extends IDialogScope { + /** + * Use this method to close the dialog and resolve the promise that was returned when opening the modal. + * + * The function accepts a single optional parameter which is used as the value of the resolved promise. + * @param {any} [value] - The value with which the promise will resolve + */ + confirm(value?:any) : void; + } + + interface IDialogOptions { + /** + * This option allows you to control the dialog's look, you can use built-in themes or create your own styled modals. + * It will be appended with the "ngdialog" class e.g. className is "default-theme flat-ui" it will be class="ngdialog default-theme flat-ui". + */ + className?: string; + + /** + * If true then animation for the dialog will be disabled, default false. + */ + disableAnimation?: boolean; + + /** + * If false it allows to hide overlay div behind the modals, default true. + */ + overlay?: boolean; + + /** + * If false it allows to hide close button on modals, default true. + */ + showClose?: boolean; + + /** + * It allows to close modals by clicking Esc button, default true. + * This will close all open modals if there several of them open at the same time. + */ + closeByEscape?: boolean; + + /** + * It allows to close modals by clicking on overlay background, default true. If @see Hammer.js is loaded, it will listen for tap instead of click. + */ + closeByDocument?: boolean; + + /** + * Listens for $locationChangeSuccess event and closes open dialogs if true (also handles the ui.router $stateChangeSuccess event if ui.router is used) + * default : false + */ + closeByNavigation?: boolean; + + /** + * If true allows to use plain string as template, default false. + */ + plain?: boolean; + + /** + * Give a name for a dialog instance. It is useful for identifying specific dialog if there are multiple dialog boxes opened. + */ + name?: string | number; + + /** + * Provide either the name of a function or a function to be called before the dialog is closed. + * If the callback function specified in the option returns false then the dialog will not be closed. + * Alternatively, if the callback function returns a promise that gets resolved the dialog will be closed. + * + * more: https://github.com/likeastore/ngDialog#preclosecallback-string--function + */ + preCloseCallback?: string|Function; + + /** + * Pass false to disable template caching. Useful for developing purposes, default is true. + */ + cache?: boolean; + + /** + * Specify your element where to append dialog instance, accepts selector string (e.g. #yourId, .yourClass). + * If not specified appends dialog to body as default behavior. + */ + appendTo?: string; + + /** + * When true, ensures that the focused element remains within the dialog to conform to accessibility recommendations. + * Default value is true + */ + trapFocus?: boolean; + + /** + * When true, closing the dialog restores focus to the element that launched it. Designed to improve keyboard + * accessibility. Default value is true + */ + preserveFocus?: boolean; + + /** + * When true, automatically selects appropriate values for any unspecified accessibility attributes. Default value is true + */ + ariaAuto? : boolean; + + /** + * Specifies the value for the role attribute that should be applied to the dialog element. Default value is null (unspecified) + */ + ariaRole?: string; + + /** + * Specifies the value for the aria-labelledby attribute that should be applied to the dialog element. + * Default value is null (unspecified) + * + * If specified, the value is not validated against the DOM + */ + ariaLabelledById?: string; + + /** + * Specifies the CSS selector for the element to be referenced by the aria-labelledby attribute on the dialog element. Default value is null (unspecified) + * + * If specified, the first matching element is used. + */ + ariaLabelledBySelector?: string; + + /** + * Specifies the value for the aria-describedby attribute that should be applied to the dialog element. Default value is null (unspecified) + * + * If specified, the value is not validated against the DOM. + */ + ariaDescribedById?: string; + + /** + * Specifies the CSS selector for the element to be referenced by the aria-describedby attribute on the dialog element. Default value is null (unspecified) + * + * If specified, the first matching element is used. + */ + ariaDescribedBySelector?: string; + } /** - * Adds an additional listener on every $locationChangeSuccess event and gets update version of html into dialog. - * May be useful in some rare cases when you're dependant on DOM changes, defaults to false. - * @param {boolean} force + * Options which are provided to open a dialog. */ - setForceHtmlReload(force: boolean) : void; + interface IDialogOpenOptions extends IDialogOptions { + template: string; + controller?: string| any[] | any; + controllerAs?: string; - /** - * Adds additional listener on every $locationChangeSuccess event and gets updated version of body into dialog. - * Maybe useful in some rare cases when you're dependant on DOM changes, defaults to false. Use it in module's - * config as provider instance: - * @param {boolean} force - */ - setForceBodyReload(force: boolean) : void; - } + /** + * Scope object that will be passed to dialog. If you use controller with separate $scope service this object will be passed to $scope.$parent param. + */ + scope?: IDialogScope; - /** - * Dialog Scope which extends the $scope. - */ - interface IDialogScope extends angular.IScope { - /** - * This allows you to close dialog straight from handler in a popup element. - * @param value Any value passed to this function will be attached to the object which resolves on the close promise for this dialog. - * For dialogs opened with the openConfirm() method the value is used as the reject reason. - */ - closeThisDialog(value?: any): void; + /** + * An optional map of dependencies which should be injected into the controller. If any of these dependencies + * are promises, ngDialog will wait for them all to be resolved or one to be rejected before the controller + * is instantiated. + */ + resolve?: {[key : string] : string | Function}; - /** - * Any serializable data that you want to be stored in the controller's dialog scope. - * From version 0.3.6 $scope.ngDialogData keeps references to the objects instead of copying them. - */ - ngDialogData : string | {} | any[]; + /** + * Any serializable data that you want to be stored in the controller's dialog scope. ($scope.ngDialogData). + * From version 0.3.6 $scope.ngDialogData keeps references to the objects instead of copying them. + */ + data?: string | {} | any[]; + } - /** - * The id of the dialog. If you you ngDialogData, it'll be also available under ngDialogData.ngDialogId - */ - ngDialogId : string; - } - - interface IDialogConfirmScope extends IDialogScope { - /** - * Use this method to close the dialog and resolve the promise that was returned when opening the modal. - * - * The function accepts a single optional parameter which is used as the value of the resolved promise. - * @param {any} [value] - The value with which the promise will resolve - */ - confirm(value?:any) : void; - } - - interface IDialogOptions { - /** - * This option allows you to control the dialog's look, you can use built-in themes or create your own styled modals. - * It will be appended with the "ngdialog" class e.g. className is "default-theme flat-ui" it will be class="ngdialog default-theme flat-ui". - */ - className?: string; - - /** - * If true then animation for the dialog will be disabled, default false. - */ - disableAnimation?: boolean; - - /** - * If false it allows to hide overlay div behind the modals, default true. - */ - overlay?: boolean; - - /** - * If false it allows to hide close button on modals, default true. - */ - showClose?: boolean; - - /** - * It allows to close modals by clicking Esc button, default true. - * This will close all open modals if there several of them open at the same time. - */ - closeByEscape?: boolean; - - /** - * It allows to close modals by clicking on overlay background, default true. If @see Hammer.js is loaded, it will listen for tap instead of click. - */ - closeByDocument?: boolean; - - /** - * Listens for $locationChangeSuccess event and closes open dialogs if true (also handles the ui.router $stateChangeSuccess event if ui.router is used) - * default : false - */ - closeByNavigation?: boolean; - - /** - * If true allows to use plain string as template, default false. - */ - plain?: boolean; - - /** - * Give a name for a dialog instance. It is useful for identifying specific dialog if there are multiple dialog boxes opened. - */ - name?: string | number; - - /** - * Provide either the name of a function or a function to be called before the dialog is closed. - * If the callback function specified in the option returns false then the dialog will not be closed. - * Alternatively, if the callback function returns a promise that gets resolved the dialog will be closed. - * - * more: https://github.com/likeastore/ngDialog#preclosecallback-string--function - */ - preCloseCallback?: string|Function; - - /** - * Pass false to disable template caching. Useful for developing purposes, default is true. - */ - cache?: boolean; - - /** - * Specify your element where to append dialog instance, accepts selector string (e.g. #yourId, .yourClass). - * If not specified appends dialog to body as default behavior. - */ - appendTo?: string; - - /** - * When true, ensures that the focused element remains within the dialog to conform to accessibility recommendations. - * Default value is true - */ - trapFocus?: boolean; - - /** - * When true, closing the dialog restores focus to the element that launched it. Designed to improve keyboard - * accessibility. Default value is true - */ - preserveFocus?: boolean; - - /** - * When true, automatically selects appropriate values for any unspecified accessibility attributes. Default value is true - */ - ariaAuto? : boolean; - - /** - * Specifies the value for the role attribute that should be applied to the dialog element. Default value is null (unspecified) - */ - ariaRole?: string; - - /** - * Specifies the value for the aria-labelledby attribute that should be applied to the dialog element. - * Default value is null (unspecified) - * - * If specified, the value is not validated against the DOM - */ - ariaLabelledById?: string; - - /** - * Specifies the CSS selector for the element to be referenced by the aria-labelledby attribute on the dialog element. Default value is null (unspecified) - * - * If specified, the first matching element is used. - */ - ariaLabelledBySelector?: string; - - /** - * Specifies the value for the aria-describedby attribute that should be applied to the dialog element. Default value is null (unspecified) - * - * If specified, the value is not validated against the DOM. - */ - ariaDescribedById?: string; - - /** - * Specifies the CSS selector for the element to be referenced by the aria-describedby attribute on the dialog element. Default value is null (unspecified) - * - * If specified, the first matching element is used. - */ - ariaDescribedBySelector?: string; - } - - /** - * Options which are provided to open a dialog. - */ - interface IDialogOpenOptions extends IDialogOptions { - template: string; - controller?: string| any[] | any; - controllerAs?: string; - - /** - * Scope object that will be passed to dialog. If you use controller with separate $scope service this object will be passed to $scope.$parent param. - */ - scope?: IDialogScope; - - /** - * An optional map of dependencies which should be injected into the controller. If any of these dependencies - * are promises, ngDialog will wait for them all to be resolved or one to be rejected before the controller - * is instantiated. - */ - resolve?: {[key : string] : string | Function}; - - /** - * Any serializable data that you want to be stored in the controller's dialog scope. ($scope.ngDialogData). - * From version 0.3.6 $scope.ngDialogData keeps references to the objects instead of copying them. - */ - data?: string | {} | any[]; - } - - interface IDialogOpenConfirmOptions extends IDialogOpenOptions { - scope?: IDialogConfirmScope; + interface IDialogOpenConfirmOptions extends IDialogOpenOptions { + scope?: IDialogConfirmScope; + } } } diff --git a/ng-dialog/ng-dialog-tests.ts b/ng-dialog/ng-dialog-tests.ts index b56d42ca6c..4a2a144850 100644 --- a/ng-dialog/ng-dialog-tests.ts +++ b/ng-dialog/ng-dialog-tests.ts @@ -1,5 +1,6 @@ /// +import * as angular from 'angularjs'; var app = angular.module('testModule', ['ngDialog']); diff --git a/ng-file-upload/index.d.ts b/ng-file-upload/index.d.ts index dce8c408f2..b975468bfc 100644 --- a/ng-file-upload/index.d.ts +++ b/ng-file-upload/index.d.ts @@ -4,277 +4,278 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +import * as angular from 'angularjs'; -declare module "ng-file-upload" { - let angularFileUploadDefaultExport: string; - export = angularFileUploadDefaultExport; -} +declare var angularFileUploadDefaultExport: string; +export = angularFileUploadDefaultExport; -declare namespace angular.angularFileUpload { - interface ImageDimensions { - height: number; - width: number; - } +declare module 'angularjs' { + export namespace angularFileUpload { + interface ImageDimensions { + height: number; + width: number; + } - interface FileUploadOptions { - /** - * Standard HTML accept attr, browser specific select popup window - * @type {string} - */ - ngfAccept?: string; - /** - * Default true, allow dropping files only for Chrome webkit browser - * @type {boolean} - */ - ngfAllowDir?: boolean; - /** - * Default false, enable firefox image paste by making element contenteditable - * @type {boolean} - */ - ngfEnableFirefoxPaste?: boolean; - /** - * Default false, hides element if file drag&drop is not - * @type {boolean} - */ - ngfHideOnDropNotAvailable?: boolean; - /** - * Validate error name: minDuration - * @type {(number|string)} - */ - ngfMinDuration: number | string; - ngfMinSize?: number | string; - /** - * Validate error name: minRatio - * @type {(number|string)} - */ - ngfMinRatio?: number | string; - /** - * Validate error name: maxDuration - * @type {(number|string)} - */ - ngfMaxDuration?: number | string; - /** - * Maximum number of files allowed to be selected or dropped, validate error name: maxFiles - * @type {number} - */ - ngfMaxFiles?: number; - /** - * Validate error name: maxSize - * @type {(number|string)} - */ - ngfMaxSize?: number | string; - /** - * Validate error name: maxTotalSize - * @type {(number|string)} - */ - ngfMaxTotalSize?: number | string; - /** - * Allows selecting multiple files - * @type {boolean} - */ - ngfMultiple?: boolean; - /** - * List of comma separated valid aspect ratio of images in float or 2:3 format - * @type {string} - */ - ngfRatio?: string; - /** - * Default false, whether to propagate drag/drop events. - * @type {boolean} - */ - ngfStopPropagation?: boolean; - /** - * Default false, if true file.$error will be set if the dimension or duration - * values for validations cannot be calculated for example image load error or unsupported video by the browser. - * By default it would assume the file is valid if the duration or dimension cannot be calculated by the browser. - * @type {boolean} - */ - ngfValidateForce?: boolean; - } + interface FileUploadOptions { + /** + * Standard HTML accept attr, browser specific select popup window + * @type {string} + */ + ngfAccept?: string; + /** + * Default true, allow dropping files only for Chrome webkit browser + * @type {boolean} + */ + ngfAllowDir?: boolean; + /** + * Default false, enable firefox image paste by making element contenteditable + * @type {boolean} + */ + ngfEnableFirefoxPaste?: boolean; + /** + * Default false, hides element if file drag&drop is not + * @type {boolean} + */ + ngfHideOnDropNotAvailable?: boolean; + /** + * Validate error name: minDuration + * @type {(number|string)} + */ + ngfMinDuration: number | string; + ngfMinSize?: number | string; + /** + * Validate error name: minRatio + * @type {(number|string)} + */ + ngfMinRatio?: number | string; + /** + * Validate error name: maxDuration + * @type {(number|string)} + */ + ngfMaxDuration?: number | string; + /** + * Maximum number of files allowed to be selected or dropped, validate error name: maxFiles + * @type {number} + */ + ngfMaxFiles?: number; + /** + * Validate error name: maxSize + * @type {(number|string)} + */ + ngfMaxSize?: number | string; + /** + * Validate error name: maxTotalSize + * @type {(number|string)} + */ + ngfMaxTotalSize?: number | string; + /** + * Allows selecting multiple files + * @type {boolean} + */ + ngfMultiple?: boolean; + /** + * List of comma separated valid aspect ratio of images in float or 2:3 format + * @type {string} + */ + ngfRatio?: string; + /** + * Default false, whether to propagate drag/drop events. + * @type {boolean} + */ + ngfStopPropagation?: boolean; + /** + * Default false, if true file.$error will be set if the dimension or duration + * values for validations cannot be calculated for example image load error or unsupported video by the browser. + * By default it would assume the file is valid if the duration or dimension cannot be calculated by the browser. + * @type {boolean} + */ + ngfValidateForce?: boolean; + } - interface IUploadService { - /** - * Convert a single file or array of files to a single or array of - * base64 data url representation of the file(s). - * Could be used to send file in base64 format inside json to the databases - * - * @param {Array} - * @return {angular.IPromise} - */ - base64DataUrl(files: File | Array): angular.IPromise | string>; - /** - * Convert the file to blob url object or base64 data url based on boolean disallowObjectUrl value - * - * @param {File} file - * @param {boolean} [disallowObjectUrl] - * @return {angular.IPromise} - */ - dataUrl(file: File, disallowObjectUrl?: boolean): angular.IPromise; - /** - * Alternative way of uploading, send the file binary with the file's content-type. - * Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed. - * This is equivalent to angular $http() but allow you to listen to the progress event for HTML5 browsers. - * - * @param {IRequestConfig} config - * @return {angular.IPromise} - */ - http(config: IRequestConfig): IUploadPromise; - /** - * Get image file dimensions - * - * @param {File} file - * @return {angular.IPromise} - */ - imageDimensions(file: File): angular.IPromise; - /** - * Returns boolean showing if image resize is supported by this browser - * - * @return {boolean} - */ - isResizeSupported(): boolean; - /** - * Returns boolean showing if resumable upload is supported by this browser - * - * @return {boolean} - */ - isResumeSupported(): boolean; - /** - * Returns true if there is an upload in progress. Can be used to prompt user before closing browser tab - * - * @return {boolean} - */ - isUploadInProgress(): boolean; - /** - * Converts the value to json to send data as json string. Same as angular.toJson(obj) - * - * @param {Object} obj - * @return {string} - */ - json(obj: Object): string; - /** - * Converts the object to a Blob object with application/json content type - * for jsob byte streaming support - * - * @param {Object} obj - * @return {Blob} - */ - jsonBlob(obj: Object): Blob; - /** - * Returns a file which will be uploaded with the newName instead of original file name - * - * @param {File} file - * @param {string} newName - * @return {File} - */ - rename(file: File, newName: string): File; - /** - * Resizes an image. Returns a promise - * - * @param {File} file - * @param {number} [width] - * @param {number} [height] - * @param {number} [quality] - * @param {string} [type] - * @param {number} [ratio] - * @param {boolean} [centerCrop] - * @return {angular.IPromise} - */ - resize(file: File, width?: number, height?: number, quality?: number, type?: string, - ratio?: number | string, centerCrop?: boolean): angular.IPromise; - /** - * Set the default values for ngf-select and ngf-drop directives - * - * @param {FileUploadOptions} defaultFileUploadOptions - */ - setDefaults(defaultFileUploadOptions: FileUploadOptions): void; - /** - * Upload a file. Returns a Promise, - * - * @param {IFileUploadConfigFile} config - * @return {IUploadPromise} - */ - upload(config: IFileUploadConfigFile): IUploadPromise; - } + interface IUploadService { + /** + * Convert a single file or array of files to a single or array of + * base64 data url representation of the file(s). + * Could be used to send file in base64 format inside json to the databases + * + * @param {Array} + * @return {angular.IPromise} + */ + base64DataUrl(files: File | Array): angular.IPromise | string>; + /** + * Convert the file to blob url object or base64 data url based on boolean disallowObjectUrl value + * + * @param {File} file + * @param {boolean} [disallowObjectUrl] + * @return {angular.IPromise} + */ + dataUrl(file: File, disallowObjectUrl?: boolean): angular.IPromise; + /** + * Alternative way of uploading, send the file binary with the file's content-type. + * Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed. + * This is equivalent to angular $http() but allow you to listen to the progress event for HTML5 browsers. + * + * @param {IRequestConfig} config + * @return {angular.IPromise} + */ + http(config: IRequestConfig): IUploadPromise; + /** + * Get image file dimensions + * + * @param {File} file + * @return {angular.IPromise} + */ + imageDimensions(file: File): angular.IPromise; + /** + * Returns boolean showing if image resize is supported by this browser + * + * @return {boolean} + */ + isResizeSupported(): boolean; + /** + * Returns boolean showing if resumable upload is supported by this browser + * + * @return {boolean} + */ + isResumeSupported(): boolean; + /** + * Returns true if there is an upload in progress. Can be used to prompt user before closing browser tab + * + * @return {boolean} + */ + isUploadInProgress(): boolean; + /** + * Converts the value to json to send data as json string. Same as angular.toJson(obj) + * + * @param {Object} obj + * @return {string} + */ + json(obj: Object): string; + /** + * Converts the object to a Blob object with application/json content type + * for jsob byte streaming support + * + * @param {Object} obj + * @return {Blob} + */ + jsonBlob(obj: Object): Blob; + /** + * Returns a file which will be uploaded with the newName instead of original file name + * + * @param {File} file + * @param {string} newName + * @return {File} + */ + rename(file: File, newName: string): File; + /** + * Resizes an image. Returns a promise + * + * @param {File} file + * @param {number} [width] + * @param {number} [height] + * @param {number} [quality] + * @param {string} [type] + * @param {number} [ratio] + * @param {boolean} [centerCrop] + * @return {angular.IPromise} + */ + resize(file: File, width?: number, height?: number, quality?: number, type?: string, + ratio?: number | string, centerCrop?: boolean): angular.IPromise; + /** + * Set the default values for ngf-select and ngf-drop directives + * + * @param {FileUploadOptions} defaultFileUploadOptions + */ + setDefaults(defaultFileUploadOptions: FileUploadOptions): void; + /** + * Upload a file. Returns a Promise, + * + * @param {IFileUploadConfigFile} config + * @return {IUploadPromise} + */ + upload(config: IFileUploadConfigFile): IUploadPromise; + } - interface IUploadPromise extends IHttpPromise { - /** - * Cancel/abort the upload in progress. - * - * @return {IUploadPromise} - */ - abort(): IUploadPromise; - progress(callback: IHttpPromiseCallback): IUploadPromise; - /** - * Access or attach event listeners to the underlying XMLHttpRequest - * - * @param {IHttpPromiseCallback} - * @return {IUploadPromise} - */ - xhr(callback: IHttpPromiseCallback): IUploadPromise; - } + interface IUploadPromise extends IHttpPromise { + /** + * Cancel/abort the upload in progress. + * + * @return {IUploadPromise} + */ + abort(): IUploadPromise; + progress(callback: IHttpPromiseCallback): IUploadPromise; + /** + * Access or attach event listeners to the underlying XMLHttpRequest + * + * @param {IHttpPromiseCallback} + * @return {IUploadPromise} + */ + xhr(callback: IHttpPromiseCallback): IUploadPromise; + } - interface IFileUploadConfigFile extends IRequestConfig { - /** - * Specify the file and optional data to be sent to the server. - * Each field including nested objects will be sent as a form data multipart. - * Samples: {pic: file, username: username} - * {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5) - * {profiles: {[{pic: file1, username: username1}, {pic: file2, username: username2}]} nested array multiple files (html5) - * {file: file, info: Upload.json({id: id, name: name, ...})} send fields as json string - * {file: file, info: Upload.jsonBlob({id: id, name: name, ...})} send fields as json blob, 'application/json' content_type - * {picFile: Upload.rename(file, 'profile.jpg'), title: title} send file with picFile key and profile.jpg file name - * - * @type {Object} - */ - data: any; - /** - * upload.php script, node.js route, or servlet url - * @type {string} - */ - url: string; - /** - * This is to accommodate server implementations expecting nested data object keys in .key or [key] format. - * Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file - * data: {rec: {name: 'N', pic: file}, objectKey: '.k'} sent as: rec.name -> N, rec.pic -> file - * @type {string} - */ - objectKey?: string; - /** - * This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or - * ''(multiple entries with same key) format. - * Example: data: {rec: [file[0], file[1], ...]} sent as: rec[0] -> file[0], rec[1] -> file[1],... - * data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent as: rec[] -> f[0], rec[] -> f[1],... - * @type {string} - */ - arrayKey?: string; - /** - * Uploaded file size so far on the server - * @type {string} - */ - resumeSizeUrl?: string; - /** - * Reads the uploaded file size from resumeSizeUrl GET response - * @type {Function} - */ - resumeSizeResponseReader?: Function; - /** - * Function that returns a prommise which will be resolved to the upload file size on the server. - * @type {[type]} - */ - resumeSize?: Function; - /** - * Upload in chunks of specified size - * @type {(number|string)} - */ - resumeChunkSize?: number | string; - /** - * Default false, experimental as hotfix for potential library conflicts with other plugins - * @type {boolean} - */ - disableProgress?: boolean; - } + interface IFileUploadConfigFile extends IRequestConfig { + /** + * Specify the file and optional data to be sent to the server. + * Each field including nested objects will be sent as a form data multipart. + * Samples: {pic: file, username: username} + * {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5) + * {profiles: {[{pic: file1, username: username1}, {pic: file2, username: username2}]} nested array multiple files (html5) + * {file: file, info: Upload.json({id: id, name: name, ...})} send fields as json string + * {file: file, info: Upload.jsonBlob({id: id, name: name, ...})} send fields as json blob, 'application/json' content_type + * {picFile: Upload.rename(file, 'profile.jpg'), title: title} send file with picFile key and profile.jpg file name + * + * @type {Object} + */ + data: any; + /** + * upload.php script, node.js route, or servlet url + * @type {string} + */ + url: string; + /** + * This is to accommodate server implementations expecting nested data object keys in .key or [key] format. + * Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file + * data: {rec: {name: 'N', pic: file}, objectKey: '.k'} sent as: rec.name -> N, rec.pic -> file + * @type {string} + */ + objectKey?: string; + /** + * This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or + * ''(multiple entries with same key) format. + * Example: data: {rec: [file[0], file[1], ...]} sent as: rec[0] -> file[0], rec[1] -> file[1],... + * data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent as: rec[] -> f[0], rec[] -> f[1],... + * @type {string} + */ + arrayKey?: string; + /** + * Uploaded file size so far on the server + * @type {string} + */ + resumeSizeUrl?: string; + /** + * Reads the uploaded file size from resumeSizeUrl GET response + * @type {Function} + */ + resumeSizeResponseReader?: Function; + /** + * Function that returns a prommise which will be resolved to the upload file size on the server. + * @type {[type]} + */ + resumeSize?: Function; + /** + * Upload in chunks of specified size + * @type {(number|string)} + */ + resumeChunkSize?: number | string; + /** + * Default false, experimental as hotfix for potential library conflicts with other plugins + * @type {boolean} + */ + disableProgress?: boolean; + } - interface IFileProgressEvent extends ProgressEvent { - config: IFileUploadConfigFile; + interface IFileProgressEvent extends ProgressEvent { + config: IFileUploadConfigFile; + } } } diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index 06d701a739..40fe92b919 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -1,4 +1,4 @@ - +import * as angular from 'angularjs'; "use strict"; diff --git a/ngtoaster/angularjs-toaster-tests.ts b/ngtoaster/angularjs-toaster-tests.ts index a0e973a0da..73b0416e66 100644 --- a/ngtoaster/angularjs-toaster-tests.ts +++ b/ngtoaster/angularjs-toaster-tests.ts @@ -1,3 +1,5 @@ +import ngtoaster = require("ngtoaster"); +import * as angular from 'angularjs'; class NgToasterTestController { constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public toaster: ngtoaster.IToasterService) { diff --git a/ngtoaster/index.d.ts b/ngtoaster/index.d.ts index d3a40e85f3..03bcba04b7 100644 --- a/ngtoaster/index.d.ts +++ b/ngtoaster/index.d.ts @@ -5,6 +5,9 @@ /// +export = ngtoaster; +export as namespace toaster; + declare namespace ngtoaster { interface IToasterService { pop(params:IPopParams): void @@ -103,7 +106,3 @@ declare namespace ngtoaster { warning: string; } } - -declare module "ngtoaster" { - export = ngtoaster -} diff --git a/nock/index.d.ts b/nock/index.d.ts index 3319456a5e..713084514e 100644 --- a/nock/index.d.ts +++ b/nock/index.d.ts @@ -5,121 +5,120 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/nock.d.ts -declare module "nock" { - export = nock; +export = nock; - function nock (host: string, options?: nock.Options): nock.Scope; +declare function nock (host: string, options?: nock.Options): nock.Scope; - namespace nock { - export function cleanAll(): void; +declare namespace nock { + export function cleanAll(): void; - export function disableNetConnect(): void; - export function enableNetConnect(): void; - export function enableNetConnect(regex: RegExp): void; - export function enableNetConnect(domain: string): void; + export function disableNetConnect(): void; + export function enableNetConnect(): void; + export function enableNetConnect(regex: RegExp): void; + export function enableNetConnect(domain: string): void; - export var recorder: Recorder; + export var recorder: Recorder; - export interface Scope { - get(path: string, data?: string): Scope; - get(path: RegExp, data?: string): Scope; + export interface Scope { + get(path: string, data?: string): Scope; + get(path: RegExp, data?: string): Scope; - post(path: string, data?: string): Scope; - post(path: string, data?: Object): Scope; - post(path: string, regex?: RegExp): Scope; - post(path: RegExp, data?: string): Scope; - post(path: RegExp, data?: Object): Scope; - post(path: RegExp, regex?: RegExp): Scope; + post(path: string, data?: string): Scope; + post(path: string, data?: Object): Scope; + post(path: string, regex?: RegExp): Scope; + post(path: RegExp, data?: string): Scope; + post(path: RegExp, data?: Object): Scope; + post(path: RegExp, regex?: RegExp): Scope; - patch(path: string, data?: string): Scope; - patch(path: string, data?: Object): Scope; - patch(path: string, regex?: RegExp): Scope; - patch(path: RegExp, data?: string): Scope; - patch(path: RegExp, data?: Object): Scope; - patch(path: RegExp, regex?: RegExp): Scope; + patch(path: string, data?: string): Scope; + patch(path: string, data?: Object): Scope; + patch(path: string, regex?: RegExp): Scope; + patch(path: RegExp, data?: string): Scope; + patch(path: RegExp, data?: Object): Scope; + patch(path: RegExp, regex?: RegExp): Scope; - put(path: string, data?: string): Scope; - put(path: string, data?: Object): Scope; - put(path: string, regex?: RegExp): Scope; - put(path: RegExp, data?: string): Scope; - put(path: RegExp, data?: Object): Scope; - put(path: RegExp, regex?: RegExp): Scope; + put(path: string, data?: string): Scope; + put(path: string, data?: Object): Scope; + put(path: string, regex?: RegExp): Scope; + put(path: RegExp, data?: string): Scope; + put(path: RegExp, data?: Object): Scope; + put(path: RegExp, regex?: RegExp): Scope; - head(path: string): Scope; - head(path: RegExp): Scope; + head(path: string): Scope; + head(path: RegExp): Scope; - delete(path: string, data?: string): Scope; - delete(path: string, data?: Object): Scope; - delete(path: string, regex?: RegExp): Scope; - delete(path: RegExp, data?: string): Scope; - delete(path: RegExp, data?: Object): Scope; - delete(path: RegExp, regex?: RegExp): Scope; + delete(path: string, data?: string): Scope; + delete(path: string, data?: Object): Scope; + delete(path: string, regex?: RegExp): Scope; + delete(path: RegExp, data?: string): Scope; + delete(path: RegExp, data?: Object): Scope; + delete(path: RegExp, regex?: RegExp): Scope; - merge(path: string, data?: string): Scope; - merge(path: string, data?: Object): Scope; - merge(path: string, regex?: RegExp): Scope; - merge(path: RegExp, data?: string): Scope; - merge(path: RegExp, data?: Object): Scope; - merge(path: RegExp, regex?: RegExp): Scope; + merge(path: string, data?: string): Scope; + merge(path: string, data?: Object): Scope; + merge(path: string, regex?: RegExp): Scope; + merge(path: RegExp, data?: string): Scope; + merge(path: RegExp, data?: Object): Scope; + merge(path: RegExp, regex?: RegExp): Scope; - query(params: any): Scope; - query(acceptAnyParams: boolean): Scope; + query(params: any): Scope; + query(acceptAnyParams: boolean): Scope; - intercept(path: string, verb: string, body?: string, options?: any): Scope; - intercept(path: string, verb: string, body?: Object, options?: any): Scope; - intercept(path: string, verb: string, body?: RegExp, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: string, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: Object, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: RegExp, options?: any): Scope; + intercept(path: string, verb: string, body?: string, options?: any): Scope; + intercept(path: string, verb: string, body?: Object, options?: any): Scope; + intercept(path: string, verb: string, body?: RegExp, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: string, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: Object, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: RegExp, options?: any): Scope; - reply(responseCode: number, body?: string, headers?: Object): Scope; - reply(responseCode: number, body?: Object, headers?: Object): Scope; - reply(responseCode: number, callback: (uri: string, body: string) => string, headers?: Object): Scope; - replyWithFile(responseCode: number, fileName: string): Scope; - replyWithError(errorMessage: string): Scope; + reply(responseCode: number, body?: string, headers?: Object): Scope; + reply(responseCode: number, body?: Object, headers?: Object): Scope; + reply(responseCode: number, callback: (uri: string, body: string) => string, headers?: Object): Scope; + replyWithFile(responseCode: number, fileName: string): Scope; + replyWithError(errorMessage: string): Scope; - defaultReplyHeaders(headers: Object): Scope; + defaultReplyHeaders(headers: Object): Scope; - matchHeader(name: string, value: string): Scope; - matchHeader(name: string, regex: RegExp): Scope; - matchHeader(name: string, fn: (value: string) => boolean): Scope; + matchHeader(name: string, value: string): Scope; + matchHeader(name: string, regex: RegExp): Scope; + matchHeader(name: string, fn: (value: string) => boolean): Scope; - filteringPath(regex: RegExp, replace: string): Scope; - filteringPath(fn: (path: string) => string): Scope; - filteringRequestBody(regex: RegExp, replace: string): Scope; - filteringRequestBody(fn: (path: string) => string): Scope; + filteringPath(regex: RegExp, replace: string): Scope; + filteringPath(fn: (path: string) => string): Scope; + filteringRequestBody(regex: RegExp, replace: string): Scope; + filteringRequestBody(fn: (path: string) => string): Scope; - persist(): Scope; - log(out: () => void): Scope; + persist(): Scope; + log(out: () => void): Scope; - delay(timeMs: number): Scope; - delayConnection(timeMs: number): Scope; + delay(timeMs: number): Scope; + delayConnection(timeMs: number): Scope; - times(repeats: number): Scope; - once(): Scope; - twice(): Scope; - thrice(): Scope; + times(repeats: number): Scope; + once(): Scope; + twice(): Scope; + thrice(): Scope; - done(): void; - isDone(): boolean; - restore(): void; - pendingMocks(): Object[]; - } + done(): void; + isDone(): boolean; + restore(): void; + pendingMocks(): Object[]; + } - export interface Recorder { - rec(capture?: boolean): void; - rec(options?: RecorderOptions): void; - play(): any[]; - } + export interface Recorder { + rec(capture?: boolean): void; + rec(options?: RecorderOptions): void; + play(): any[]; + } - export interface Options { - allowUnmocked?: boolean; - } + export interface Options { + allowUnmocked?: boolean; + } - export interface RecorderOptions { - dont_print?: boolean; - output_objects?: boolean; - enable_reqheaders_recording?: boolean; - } + export interface RecorderOptions { + dont_print?: boolean; + output_objects?: boolean; + enable_reqheaders_recording?: boolean; } } + diff --git a/node-cache/index.d.ts b/node-cache/index.d.ts index bf9cd8c462..32b4139f7a 100644 --- a/node-cache/index.d.ts +++ b/node-cache/index.d.ts @@ -5,7 +5,7 @@ /// -declare namespace NodeCacheTypes { +declare namespace NodeCache { interface NodeCache { /** container for cached data */ data: Data; @@ -144,120 +144,119 @@ declare namespace NodeCacheTypes { } } -declare module "node-cache" { - import events = require("events"); +import events = require("events"); - import Data = NodeCacheTypes.Data; - import Options = NodeCacheTypes.Options; - import Stats = NodeCacheTypes.Stats; - import Callback = NodeCacheTypes.Callback; +import Data = NodeCache.Data; +import Options = NodeCache.Options; +import Stats = NodeCache.Stats; +import Callback = NodeCache.Callback; - class NodeCache extends events.EventEmitter implements NodeCacheTypes.NodeCache { - /** container for cached data */ - data: Data; +declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCache { + /** container for cached data */ + data: Data; - /** module options */ - options: Options; + /** module options */ + options: Options; - /** statistics container */ - stats: Stats; + /** statistics container */ + stats: Stats; - constructor(options?: Options); + constructor(options?: Options); - /** - * get a cached key and change the stats - * - * @param key cache key or an array of keys - * @param cb Callback function - */ - get( - key: string, - cb?: Callback - ): T; + /** + * get a cached key and change the stats + * + * @param key cache key or an array of keys + * @param cb Callback function + */ + get( + key: string, + cb?: Callback + ): T; - /** - * get multiple cached keys at once and change the stats - * - * @param keys an array of keys - * @param cb Callback function - */ - mget( - keys: string[], - cb?: Callback<{[key: string]: T}> - ): {[key: string]: T}; + /** + * get multiple cached keys at once and change the stats + * + * @param keys an array of keys + * @param cb Callback function + */ + mget( + keys: string[], + cb?: Callback<{[key: string]: T}> + ): {[key: string]: T}; - /** - * set a cached key and change the stats - * - * @param key cache key - * @param value A element to cache. If the option `option.forceString` is `true` the module trys to translate - * it to a serialized JSON - * @param ttl The time to live in seconds. - * @param cb Callback function - */ - set( - key: string, - value: T, - ttl: number|string, - cb?: Callback - ): boolean; + /** + * set a cached key and change the stats + * + * @param key cache key + * @param value A element to cache. If the option `option.forceString` is `true` the module trys to translate + * it to a serialized JSON + * @param ttl The time to live in seconds. + * @param cb Callback function + */ + set( + key: string, + value: T, + ttl: number|string, + cb?: Callback + ): boolean; - set( - key: string, - value: T, - cb?: Callback - ): boolean; + set( + key: string, + value: T, + cb?: Callback + ): boolean; - /** - * remove keys - * @param keys cache key to delete or a array of cache keys - * @param cb Callback function - * @returns Number of deleted keys - */ - del( - keys: string|string[], - cb?: Callback - ): number; + /** + * remove keys + * @param keys cache key to delete or a array of cache keys + * @param cb Callback function + * @returns Number of deleted keys + */ + del( + keys: string|string[], + cb?: Callback + ): number; - /** - * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` - */ - ttl( - key: string, - ttl: number, - cb?: Callback - ): boolean; + /** + * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` + */ + ttl( + key: string, + ttl: number, + cb?: Callback + ): boolean; - ttl( - key: string, - cb?: Callback, - ttl?: number - ): boolean; + ttl( + key: string, + cb?: Callback, + ttl?: number + ): boolean; - /** - * list all keys within this cache - * @param cb Callback function - * @returns An array of all keys - */ - keys(cb?: Callback): string[]; + /** + * list all keys within this cache + * @param cb Callback function + * @returns An array of all keys + */ + keys(cb?: Callback): string[]; - /** - * get the stats - * - * @returns Stats data - */ - getStats(): Stats; + /** + * get the stats + * + * @returns Stats data + */ + getStats(): Stats; - /** - * flush the hole data and reset the stats - */ - flushAll(): void; + /** + * flush the hole data and reset the stats + */ + flushAll(): void; - /** - * This will clear the interval timeout which is set on checkperiod option. - */ - close(): void; - } - - export = NodeCache; + /** + * This will clear the interval timeout which is set on checkperiod option. + */ + close(): void; } + +export = NodeCache; + diff --git a/node-cache/node-cache-tests.ts b/node-cache/node-cache-tests.ts index 9e37d65b32..7f5f917c07 100644 --- a/node-cache/node-cache-tests.ts +++ b/node-cache/node-cache-tests.ts @@ -2,9 +2,9 @@ import NodeCache = require('node-cache'); -import Options = NodeCacheTypes.Options; -import Stats = NodeCacheTypes.Stats; -import Callback = NodeCacheTypes.Callback; +import Options = NodeCache.Options; +import Stats = NodeCache.Stats; +import Callback = NodeCache.Callback; interface TypeSample { a: number; @@ -14,7 +14,7 @@ interface TypeSample { { let options: Options; - let cache: NodeCacheTypes.NodeCache; + let cache: NodeCache.NodeCache; cache = new NodeCache(); cache = new NodeCache(options); } diff --git a/noisejs/index.d.ts b/noisejs/index.d.ts index 6e3f751225..dd145dd0c6 100644 --- a/noisejs/index.d.ts +++ b/noisejs/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Noise; +export as namespace Noise; + declare class Noise { /** * Passing in seed will seed this Noise instance @@ -52,7 +55,3 @@ declare class Noise { */ seed(seed: number): void; } - -declare module "noisejs" { - export = Noise; -} diff --git a/noisejs/noisejs-tests.ts b/noisejs/noisejs-tests.ts index 31e18403c6..f61ff22560 100644 --- a/noisejs/noisejs-tests.ts +++ b/noisejs/noisejs-tests.ts @@ -1,3 +1,4 @@ +import Noise = require("noisejs"); var noise = new Noise(Math.random()); var simplex2_noise_val = noise.simplex2(0.1, 0.2); diff --git a/normalizr/index.d.ts b/normalizr/index.d.ts index 77d2f86648..90750db1cf 100644 --- a/normalizr/index.d.ts +++ b/normalizr/index.d.ts @@ -3,9 +3,7 @@ // Definitions by: Markus Peloso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "normalizr" { - export = Normalizr; -} +export = Normalizr; declare namespace Normalizr { type AttributeSetting = string | ((entity: any) => any); diff --git a/nouislider/index.d.ts b/nouislider/index.d.ts index 5f69099eab..8b75146011 100644 --- a/nouislider/index.d.ts +++ b/nouislider/index.d.ts @@ -4,6 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export = noUiSlider; +export as namespace noUiSlider; + declare namespace noUiSlider { /** * To create a slider, call noUiSlider.create() with an element and your options. @@ -174,7 +177,3 @@ declare namespace noUiSlider { noUiSlider: noUiSlider } } - -declare module "nouislider" { - export = noUiSlider; -} diff --git a/nouislider/nouislider-tests.ts b/nouislider/nouislider-tests.ts index 8dfe3ac079..9588797fcf 100644 --- a/nouislider/nouislider-tests.ts +++ b/nouislider/nouislider-tests.ts @@ -1,4 +1,4 @@ - +import noUiSlider = require("nouislider"); var testHtmlElement = document.getElementById('test'); diff --git a/npm/index.d.ts b/npm/index.d.ts index b6474631d5..1ef58a0dcd 100644 --- a/npm/index.d.ts +++ b/npm/index.d.ts @@ -5,6 +5,9 @@ /// +declare var npm: NPM.Static; +export = npm; + declare namespace NPM { export interface Static extends NodeJS.EventEmitter { config: Config; @@ -454,8 +457,3 @@ declare namespace NPM { //#endregion } - -declare module "npm" { - var npm: NPM.Static; - export = npm; -} diff --git a/object-hash/index.d.ts b/object-hash/index.d.ts index 6fab03d520..7ce1e2ce7f 100644 --- a/object-hash/index.d.ts +++ b/object-hash/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import HashStatic = ObjectHash.HashStatic; +export = HashStatic; +export as namespace objectHash; + declare namespace ObjectHash { export interface IOptions { algorithm?: string; @@ -45,8 +49,3 @@ declare namespace ObjectHash { export var HashStatic: Hash; } - -declare module 'object-hash' { - import HashStatic = ObjectHash.HashStatic; - export = HashStatic; -} diff --git a/object-hash/object-hash-tests.ts b/object-hash/object-hash-tests.ts index fde13cb04f..4fbac3f461 100644 --- a/object-hash/object-hash-tests.ts +++ b/object-hash/object-hash-tests.ts @@ -23,7 +23,7 @@ var options = { hashed = hash(obj, options); // HashTable -var table: ObjectHash.HashTable; +var table: any; table = hash.HashTable(); table = hash.HashTable(options); diff --git a/oboe/index.d.ts b/oboe/index.d.ts index 27f784895c..2f20af4eae 100644 --- a/oboe/index.d.ts +++ b/oboe/index.d.ts @@ -64,6 +64,5 @@ declare namespace oboe { declare var oboe: oboe.OboeFunction; -declare module "oboe" { - export = oboe; -} +export = oboe; +export as namespace oboe; diff --git a/observe-js/index.d.ts b/observe-js/index.d.ts index d24e8b2158..4b668bec16 100644 --- a/observe-js/index.d.ts +++ b/observe-js/index.d.ts @@ -231,20 +231,18 @@ declare namespace observejs { } } -declare module "observe-js" { - var PathObserver: typeof observejs.PathObserver; - var ArrayObserver: typeof observejs.ArrayObserver; - var ObjectObserver: typeof observejs.ObjectObserver; - var CompoundObserver: typeof observejs.CompoundObserver; - var ObserverTransform: typeof observejs.ObserverTransform; - var Path: observejs.Path; +declare var PathObserver: typeof observejs.PathObserver; +declare var ArrayObserver: typeof observejs.ArrayObserver; +declare var ObjectObserver: typeof observejs.ObjectObserver; +declare var CompoundObserver: typeof observejs.CompoundObserver; +declare var ObserverTransform: typeof observejs.ObserverTransform; +declare var Path: observejs.Path; - export { - PathObserver, - ArrayObserver, - ObjectObserver, - CompoundObserver, - ObserverTransform, - Path - }; -} +export { + PathObserver, + ArrayObserver, + ObjectObserver, + CompoundObserver, + ObserverTransform, + Path +}; diff --git a/observe-js/observe-js-tests.ts b/observe-js/observe-js-tests.ts index 3336292fc5..23dc1159f3 100644 --- a/observe-js/observe-js-tests.ts +++ b/observe-js/observe-js-tests.ts @@ -1,4 +1,4 @@ - +import {PathObserver, ArrayObserver, ObjectObserver, CompoundObserver, ObserverTransform} from 'observe-js'; namespace observejs { diff --git a/onoff/index.d.ts b/onoff/index.d.ts index 467f5f4447..c080025735 100644 --- a/onoff/index.d.ts +++ b/onoff/index.d.ts @@ -5,6 +5,8 @@ /// +export = __ONOFF; + declare namespace __ONOFF { var version:string; @@ -48,8 +50,4 @@ declare namespace __ONOFF { unexport():void; } -} - -declare module "onoff" { - export = __ONOFF; } \ No newline at end of file diff --git a/opn/index.d.ts b/opn/index.d.ts index b4fe96ce03..78a1043442 100644 --- a/opn/index.d.ts +++ b/opn/index.d.ts @@ -6,6 +6,61 @@ /// +import * as cp from "child_process"; + +interface DefaultFunction { + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * +* @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + */ + (target: string): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. + */ + (target: string, callback: (err: Error) => void): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param options - Options to be passed to opn. + */ + (target: string, options: Opn.Options): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param options - Options to be passed to opn. + * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. + */ + (target: string, options: Opn.Options, callback: (err: Error) => void): cp.ChildProcess; +} + +declare var opn: DefaultFunction; +export = opn; + declare namespace Opn { export interface Options { /** @@ -23,60 +78,3 @@ declare namespace Opn { app?: string | string[]; } } - -declare module "opn" { - import * as cp from "child_process"; - - interface DefaultFunction { - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - */ - (target: string): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, callback: (err: Error) => void): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - */ - (target: string, options: Opn.Options): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, options: Opn.Options, callback: (err: Error) => void): cp.ChildProcess; - } - - const opn: DefaultFunction; - export = opn; -} diff --git a/orchestrator/index.d.ts b/orchestrator/index.d.ts index 911627ddc5..4ca354ab69 100644 --- a/orchestrator/index.d.ts +++ b/orchestrator/index.d.ts @@ -7,121 +7,119 @@ declare type Strings = string|string[]; -declare module "orchestrator" { - class Orchestrator { - add: Orchestrator.AddMethod; - /** - * Have you defined a task with this name? - * @param name The task name to query - */ - hasTask(name: string): boolean; - start: Orchestrator.StartMethod; - stop(): void; +declare class Orchestrator { + add: Orchestrator.AddMethod; + /** + * Have you defined a task with this name? + * @param name The task name to query + */ + hasTask(name: string): boolean; + start: Orchestrator.StartMethod; + stop(): void; - /** - * Listen to orchestrator internals - * @param event Event name to listen to: - *
    - *
  • start: from start() method, shows you the task sequence - *
  • stop: from stop() method, the queue finished successfully - *
  • err: from stop() method, the queue was aborted due to a task error - *
  • task_start: from _runTask() method, task was started - *
  • task_stop: from _runTask() method, task completed successfully - *
  • task_err: from _runTask() method, task errored - *
  • task_not_found: from start() method, you're trying to start a task that doesn't exist - *
  • task_recursion: from start() method, there are recursive dependencies in your task list - *
- * @param cb Passes single argument: e: event details - */ - on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator; + /** + * Listen to orchestrator internals + * @param event Event name to listen to: + *
    + *
  • start: from start() method, shows you the task sequence + *
  • stop: from stop() method, the queue finished successfully + *
  • err: from stop() method, the queue was aborted due to a task error + *
  • task_start: from _runTask() method, task was started + *
  • task_stop: from _runTask() method, task completed successfully + *
  • task_err: from _runTask() method, task errored + *
  • task_not_found: from start() method, you're trying to start a task that doesn't exist + *
  • task_recursion: from start() method, there are recursive dependencies in your task list + *
+ * @param cb Passes single argument: e: event details + */ + on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator; + /** + * Listen to all orchestrator events from one callback + * @param cb Passes single argument: e: event details + */ + onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void; +} + +declare namespace Orchestrator { + interface AddMethodCallback { /** - * Listen to all orchestrator events from one callback - * @param cb Passes single argument: e: event details + * Accept a callback + * @param callback */ - onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void; + (callback?: Function): any; + /** + * Return a promise + */ + (): Q.Promise; + /** + * Return a stream: (task is marked complete when stream ends) + */ + (): any; //TODO: stream type should be here e.g. map-stream } - namespace Orchestrator { - interface AddMethodCallback { - /** - * Accept a callback - * @param callback - */ - (callback?: Function): any; - /** - * Return a promise - */ - (): Q.Promise; - /** - * Return a stream: (task is marked complete when stream ends) - */ - (): any; //TODO: stream type should be here e.g. map-stream - } - + /** + * Define a task + */ + interface AddMethod { /** * Define a task + * @param name The name of the task. + * @param deps An array of task names to be executed and completed before your task will run. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
    + *
  • Take in a callback
  • + *
  • Return a stream or a promise
  • + *
*/ - interface AddMethod { - /** - * Define a task - * @param name The name of the task. - * @param deps An array of task names to be executed and completed before your task will run. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
    - *
  • Take in a callback
  • - *
  • Return a stream or a promise
  • - *
- */ - (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; - /** - * Define a task - * @param name The name of the task. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
    - *
  • Take in a callback
  • - *
  • Return a stream or a promise
  • - *
- */ - (name: string, fn?: AddMethodCallback|Function): Orchestrator; - } - + (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; /** - * Start running the tasks + * Define a task + * @param name The name of the task. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
    + *
  • Take in a callback
  • + *
  • Return a stream or a promise
  • + *
*/ - interface StartMethod { - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (tasks: Strings, cb?: (error?: any) => any): Orchestrator; - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; - //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... - (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; - } - - interface OnCallbackEvent { - message: string; - task: string; - err: any; - duration?: number; - } - - interface OnAllCallbackEvent extends OnCallbackEvent { - src: string; - } - + (name: string, fn?: AddMethodCallback|Function): Orchestrator; + } + + /** + * Start running the tasks + */ + interface StartMethod { + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (tasks: Strings, cb?: (error?: any) => any): Orchestrator; + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; + //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; + } + + interface OnCallbackEvent { + message: string; + task: string; + err: any; + duration?: number; + } + + interface OnAllCallbackEvent extends OnCallbackEvent { + src: string; } - export = Orchestrator; } + +export = Orchestrator; diff --git a/p2/index.d.ts b/p2/index.d.ts index bdbac86b0e..5fb85052e6 100644 --- a/p2/index.d.ts +++ b/p2/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Clark Stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "p2" { - export = p2; -} +export = p2; +export as namespace p2; declare namespace p2 { diff --git a/p2/p2-tests.ts b/p2/p2-tests.ts index fbc4a83fac..bdad71b906 100644 --- a/p2/p2-tests.ts +++ b/p2/p2-tests.ts @@ -1,3 +1,4 @@ +import p2 = require("p2"); // Create a physics world, where bodies and constraints live var world = new p2.World({ gravity:[0, -9.82] diff --git a/pako/index.d.ts b/pako/index.d.ts index 9f7d84df39..572fe99c9f 100644 --- a/pako/index.d.ts +++ b/pako/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Denis Cappellin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Pako; +export as namespace pako; + declare namespace Pako { /** @@ -57,7 +60,3 @@ declare namespace Pako { push( data: Uint8Array | Array | ArrayBuffer | string, mode?: number | boolean ): boolean; } } - -declare module 'pako' { - export = Pako; -} diff --git a/parse-torrent/index.d.ts b/parse-torrent/index.d.ts index 2ef9df18e7..b27d911026 100644 --- a/parse-torrent/index.d.ts +++ b/parse-torrent/index.d.ts @@ -5,6 +5,9 @@ /// +declare var parseTorrentStatic:ParseTorrent.StaticInstance; +export = parseTorrentStatic; + declare namespace ParseTorrent { export interface ParsedTorrent { infoHash:string; @@ -35,8 +38,3 @@ declare namespace ParseTorrent { remote(torrentBlob:Blob, onTorrentCallback?:(err:Error, parsedTorrent:ParsedTorrent)=>void):void; } } - -declare module "parse-torrent" { - const parseTorrentStatic:ParseTorrent.StaticInstance; - export = parseTorrentStatic; -} diff --git a/pathwatcher/index.d.ts b/pathwatcher/index.d.ts index 606f3cf5b6..93aea6806b 100644 --- a/pathwatcher/index.d.ts +++ b/pathwatcher/index.d.ts @@ -60,31 +60,29 @@ declare namespace PathWatcher { } } -declare module "pathwatcher" { +import events = require("events"); - import events = require("events"); - - interface IHandleWatcher extends events.EventEmitter { - onEvent(event:any, filePath:any, oldFilePath:any):any; - start():void; - closeIfNoListener():void; - close():void; - } - - interface IPathWatcher { - isWatchingParent:boolean; - path:any; - handleWatcher:IHandleWatcher; - - close():void; - } - - function watch(path:string, callback:Function):IPathWatcher; - - function closeAllWatchers():void; - - function getWatchedPaths():string[]; - - var File:PathWatcher.IFileStatic; - var Directory:PathWatcher.IDirectoryStatic; +export interface IHandleWatcher extends events.EventEmitter { + onEvent(event:any, filePath:any, oldFilePath:any):any; + start():void; + closeIfNoListener():void; + close():void; } + +export interface IPathWatcher { + isWatchingParent:boolean; + path:any; + handleWatcher:IHandleWatcher; + + close():void; +} + +export function watch(path:string, callback:Function):IPathWatcher; + +export function closeAllWatchers():void; + +export function getWatchedPaths():string[]; + +export var File:PathWatcher.IFileStatic; +export var Directory:PathWatcher.IDirectoryStatic; + diff --git a/pegjs/index.d.ts b/pegjs/index.d.ts index 8dae497cfa..cf375cd32c 100644 --- a/pegjs/index.d.ts +++ b/pegjs/index.d.ts @@ -29,56 +29,55 @@ declare namespace PEG { } } -declare module "pegjs" { +export type Location = PEG.Location; +export type LocationRange = PEG.LocationRange; - type Location = PEG.Location; - type LocationRange = PEG.LocationRange; - - interface ExpectedItem { - type: string; - value?: string; - description: string; - } - - interface PegjsError extends Error { - name: string; - message: string; - location: LocationRange; - found?: any; - expected?: ExpectedItem[]; - stack?: any; - } - - type GrammarError = PegjsError; - var GrammarError: any; - - interface ParserOptions { - startRule: string; - tracer: any; - } - - interface Parser { - parse(input: string, options?:ParserOptions): any; - - SyntaxError: any; - } - - interface BuildOptions { - cache?: boolean; - allowedStartRules?: string[]; - optimize?: string; - plugins?: any[]; - } - - interface OutputBuildOptions extends BuildOptions { - output?: string; - } - - function buildParser(grammar: string, options?: BuildOptions): Parser; - function buildParser(grammar: string, options?: OutputBuildOptions): Parser | string; - - namespace parser { - type SyntaxError = PegjsError; - var SyntaxError: any; - } +export interface ExpectedItem { + type: string; + value?: string; + description: string; } + +export interface PegjsError extends Error { + name: string; + message: string; + location: LocationRange; + found?: any; + expected?: ExpectedItem[]; + stack?: any; +} + +export type GrammarError = PegjsError; +export var GrammarError: any; + +export interface ParserOptions { + startRule: string; + tracer: any; +} + +export interface Parser { + parse(input: string, options?:ParserOptions): any; + + SyntaxError: any; +} + +export interface BuildOptions { + cache?: boolean; + allowedStartRules?: string[]; + optimize?: string; + plugins?: any[]; +} + +export interface OutputBuildOptions extends BuildOptions { + output?: string; +} + +export function buildParser(grammar: string, options?: BuildOptions): Parser; +export function buildParser(grammar: string, options?: OutputBuildOptions): Parser | string; + +export namespace parser { + type SyntaxError = PegjsError; + var SyntaxError: any; +} +export as namespace PEG; + diff --git a/pegjs/pegjs-tests.ts b/pegjs/pegjs-tests.ts index 12035b309c..74f74ae80f 100644 --- a/pegjs/pegjs-tests.ts +++ b/pegjs/pegjs-tests.ts @@ -1,12 +1,10 @@ - +import * as pegjs from 'pegjs'; { let input: string; - let result = PEG.parse(input); + let result = pegjs.PEG.parse(input); console.log(result); } -import * as pegjs from 'pegjs'; - { let pegparser: pegjs.Parser = pegjs.buildParser("start = ('a' / 'b')+"); diff --git a/pi-spi/index.d.ts b/pi-spi/index.d.ts index cd7d6569e7..00d02e3865 100644 --- a/pi-spi/index.d.ts +++ b/pi-spi/index.d.ts @@ -5,6 +5,8 @@ /// +export = __PI_SPI; + declare namespace __PI_SPI { enum mode { @@ -38,9 +40,4 @@ declare namespace __PI_SPI { close():void; } -} - - -declare module "pi-spi" { - export = __PI_SPI; } \ No newline at end of file diff --git a/pinterest-sdk/index.d.ts b/pinterest-sdk/index.d.ts index 3a52e37a6f..b24e4bee7b 100644 --- a/pinterest-sdk/index.d.ts +++ b/pinterest-sdk/index.d.ts @@ -2,6 +2,10 @@ // Project: https://assets.pinterest.com/sdk/sdk.js // Definitions by: Adam Burmister // Definitions: https://github.com/adamburmister/DefinitelyTyped + +export = PDK; +export as namespace PDK; + declare namespace PDK { enum OAuthScopes { 'read_public', 'write_public', 'read_relationships', 'write_relationships' } @@ -140,7 +144,3 @@ declare namespace PDK { */ export function pin(imageUrl: string, note: string, url: string, callback: Function): void; } - -declare module 'pinterest-sdk' { - export = PDK; -} diff --git a/pinterest-sdk/pinterest-sdk-tests.ts b/pinterest-sdk/pinterest-sdk-tests.ts index 293d96dfdf..8846abb20c 100644 --- a/pinterest-sdk/pinterest-sdk-tests.ts +++ b/pinterest-sdk/pinterest-sdk-tests.ts @@ -1,4 +1,4 @@ - +import PDK = require("pinterest-sdk"); // Examples from https://github.com/pinterest/pinterest-api-demo diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index 179bf381ce..28c367f816 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = PIXI; +export as namespace PIXI; + declare class PIXI { static VERSION: string; @@ -1739,8 +1742,4 @@ declare namespace PIXI { } } -} - -declare module 'pixi.js' { - export = PIXI; -} +} \ No newline at end of file diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 1582f79c87..c40bdc1bd2 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,4 +1,4 @@ - +import PIXI = require("pixi.js"); namespace basics { export class Basics { diff --git a/power-assert/index.d.ts b/power-assert/index.d.ts index d4f5d4e5c3..dc636b2d6f 100644 --- a/power-assert/index.d.ts +++ b/power-assert/index.d.ts @@ -8,6 +8,9 @@ /// /// +export = assert; +export as namespace assert; + declare function assert(value:any, message?:string):void; declare namespace assert { export class AssertionError implements Error { @@ -64,7 +67,3 @@ declare namespace assert { export function customize(options:Options):typeof assert; } - -declare module "power-assert" { - export = assert; -} diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts index 4411275858..79e07067ee 100644 --- a/protractor-http-mock/index.d.ts +++ b/protractor-http-mock/index.d.ts @@ -226,7 +226,4 @@ declare namespace mock { } declare var mock: mock.ProtractorHttpMock; - -declare module "protractor-http-mock" { - export = mock; -} +export = mock; diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts index 2ab9417c9a..f556c49985 100644 --- a/protractor-http-mock/protractor-http-mock-tests.ts +++ b/protractor-http-mock/protractor-http-mock-tests.ts @@ -1,4 +1,4 @@ - +import mock = require("protractor-http-mock"); function TestConfig() { mock.config = { diff --git a/proxyquire/index.d.ts b/proxyquire/index.d.ts index 5127592b87..c6c38cb85f 100644 --- a/proxyquire/index.d.ts +++ b/proxyquire/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var p: Proxyquire; +export = p; + interface Proxyquire { (request: string, stubs: any): any; @@ -17,9 +20,3 @@ interface Proxyquire { noPreserveCache(): Proxyquire; preserveCache(): Proxyquire; } - -declare module 'proxyquire' { - - var p: Proxyquire; - export = p; -} diff --git a/purl/index.d.ts b/purl/index.d.ts index 8b4d06fca4..2849b17a8c 100644 --- a/purl/index.d.ts +++ b/purl/index.d.ts @@ -55,6 +55,5 @@ declare function purl(): purl.Url; */ declare function purl(someUrl: string): purl.Url; -declare module "purl" { - export = purl; -} +export = purl; +export as namespace purl; diff --git a/q-retry/index.d.ts b/q-retry/index.d.ts index 7a28928aa7..851f5fabe3 100644 --- a/q-retry/index.d.ts +++ b/q-retry/index.d.ts @@ -5,6 +5,8 @@ /// +export = Q; + declare namespace Q { export interface IRetryOptions { limit?: number; @@ -33,7 +35,3 @@ declare namespace Q { retry(process: (value: T) => U, options?: IRetryOptions): Promise; } } - -declare module "q-retry" { - export = Q; -} diff --git a/q/Q-tests.ts b/q/Q-tests.ts index f75ffbdb96..efd32d4b98 100644 --- a/q/Q-tests.ts +++ b/q/Q-tests.ts @@ -1,7 +1,7 @@ /// -import q = require('q'); +import Q = require('q'); Q(8).then(x => console.log(x.toExponential())); diff --git a/q/index.d.ts b/q/index.d.ts index 4cb4bfad2e..f96774b791 100644 --- a/q/index.d.ts +++ b/q/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Q; +export as namespace Q; + /** * If value is a Q promise, returns the promise. * If value is a promise from another library it is coerced into a Q promise (where possible). @@ -338,7 +341,3 @@ declare namespace Q { */ export function noConflict(): typeof Q; } - -declare module "q" { - export = Q; -} diff --git a/qajax/index.d.ts b/qajax/index.d.ts index 1ea3df18a1..31fa32d1f0 100644 --- a/qajax/index.d.ts +++ b/qajax/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export = Qajax; +export as namespace Qajax; declare function Qajax(url : string) : Q.Promise; declare function Qajax(options : any) : Q.Promise; @@ -20,8 +22,4 @@ declare namespace Qajax { export function getJSON(url : string) : Q.Promise; export function serialize(paramsObj : any) : string; -} - -declare module "qajax" { - export = Qajax; -} +} \ No newline at end of file diff --git a/qajax/qajax-tests.ts b/qajax/qajax-tests.ts index ff9ab31f47..0307bf4d0c 100644 --- a/qajax/qajax-tests.ts +++ b/qajax/qajax-tests.ts @@ -1,4 +1,4 @@ - +import Qajax = require("qajax"); // Based on https://github.com/gre/qajax/blob/master/test/qajax.js diff --git a/qrcode-generator/index.d.ts b/qrcode-generator/index.d.ts index b99e1ca510..f4517b56d4 100644 --- a/qrcode-generator/index.d.ts +++ b/qrcode-generator/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Stefan Huber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare function qrcode(type: number, errorCorrectionLevel: string) : QRCode; +export = qrcode; +export as namespace qrcode; + interface QRCode { addData(data: string) : void; make() : void; @@ -11,8 +15,3 @@ interface QRCode { createSvgTag(cellSize: number, margin: number) : string; createImageTag(cellSize: number, margin: number) : string; } - -declare module 'qrcode-generator' { - function qrcode(type: number, errorCorrectionLevel: string) : QRCode; - export = qrcode; -} diff --git a/qs/index.d.ts b/qs/index.d.ts index af18fcdb4d..41c7b0da6a 100644 --- a/qs/index.d.ts +++ b/qs/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Roman Korneev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = QueryString; +export as namespace qs; + declare namespace QueryString { interface IStringifyOptions { delimiter?: string; @@ -29,7 +32,3 @@ declare namespace QueryString { function stringify(obj: any, options?: IStringifyOptions): string; function parse(str: string, options?: IParseOptions): any; } - -declare module "qs" { - export = QueryString; -} diff --git a/rc-select/index.d.ts b/rc-select/index.d.ts index 64caa68914..b3decc23d8 100644 --- a/rc-select/index.d.ts +++ b/rc-select/index.d.ts @@ -5,6 +5,16 @@ /// +import Select = RcSelect.Select; +import Option = RcSelect.Option; +import OptGroup = RcSelect.OptGroup; + +export default Select; +export { + Option, + OptGroup +}; + declare namespace RcSelect { interface SelectProps { className?: string; @@ -53,14 +63,3 @@ declare namespace RcSelect { } export class OptGroup extends React.Component { } } -declare module 'rc-select' { - import Select = RcSelect.Select; - import Option = RcSelect.Option; - import OptGroup = RcSelect.OptGroup; - - export default Select; - export { - Option, - OptGroup - }; -} diff --git a/rc-select/rc-select-tests.ts b/rc-select/rc-select-tests.ts index 4bf0d3888a..f2ec85ae09 100644 --- a/rc-select/rc-select-tests.ts +++ b/rc-select/rc-select-tests.ts @@ -2,7 +2,7 @@ /// import React = require('react'); -import Select = require('rc-select'); +import RcSelect = require('rc-select'); class Component extends React.Component { @@ -19,7 +19,7 @@ class Component extends React.Component { console.log('input changed'); } - private defaultSelectProps: RcSelect.SelectProps = { + private defaultSelectProps = { className: "my-select", prefixCls: "prefix", animation: "slide-up", @@ -44,28 +44,28 @@ class Component extends React.Component { defaultActiveFirstOption: false }; - private defaultOptGroupProps: RcSelect.OptGroupProps = { + private defaultOptGroupProps = { label: "Option group", key: "option-group-0", value: "option-group-0" }; - private defaultOptionProps: RcSelect.OptionProps = { + private defaultOptionProps = { className: "option", disabled: true, key: "option-0", value: "option-0" }; - private createOptions(count: number): React.ReactElement[] { - let options: React.ReactElement[] = []; + private createOptions(count: number) { + let options : any = []; for (let i = 0; i < count; i++) { let props = this.defaultOptionProps; props.key = `option-${i}`; props.value = `option-${i}`; - options.push(React.createElement(Select.Option, props)); + options.push(React.createElement(RcSelect.Option, props)); } return options; @@ -73,11 +73,11 @@ class Component extends React.Component { render() { - let options: React.ReactElement[] = this.createOptions(10); + let options = this.createOptions(10); - let optionGroup: React.ReactElement = React.createElement(Select.OptGroup, this.defaultOptGroupProps, options); + let optionGroup = React.createElement(RcSelect.OptGroup, this.defaultOptGroupProps, options); - let select: React.ReactElement = React.createElement(Select.default, this.defaultSelectProps, optionGroup); + let select = React.createElement(RcSelect.default, this.defaultSelectProps, optionGroup); return select; } diff --git a/react-datagrid/index.d.ts b/react-datagrid/index.d.ts index 55e66cae60..91daf5e522 100644 --- a/react-datagrid/index.d.ts +++ b/react-datagrid/index.d.ts @@ -5,10 +5,8 @@ /// -declare module "react-datagrid" { - import DataGrid = ReactDataGrid.DataGrid; - export = DataGrid; -} +import DataGrid = ReactDataGrid.DataGrid; +export = DataGrid; declare namespace ReactDataGrid { interface DataGridProps extends React.Props { diff --git a/react-datagrid/react-datagrid-tests.tsx b/react-datagrid/react-datagrid-tests.tsx index 630adc652c..061be471f4 100644 --- a/react-datagrid/react-datagrid-tests.tsx +++ b/react-datagrid/react-datagrid-tests.tsx @@ -6,15 +6,15 @@ import ReactDataGrid = require("react-datagrid"); var data: any[] = []; -var columns: ReactDataGrid.Column[] = [ +var columns = [ { name: 'index', title: '#', width: 50 }, { name: 'firstName', style: { color: 'red' }, visible: true}, - { name: 'lastName', render: (v) => {return v + " Phd"}}, + { name: 'lastName', render: (v: any) => {return v + " Phd"}}, { name: 'city', textAlign: 'right', defaultVisible: true}, { name: 'email', defaultHidden: true } ]; var selected = {}; -var sortInfo: ReactDataGrid.SortInfo[] = [ { name: 'country', dir: 'asc'}] +var sortInfo = [ { name: 'country', dir: 'asc'}] export module X { export class ExampleBasic extends React.Component<{},{}> { @@ -69,12 +69,12 @@ class ExampleFull extends React.Component<{},{}> { page={1} pageSize={100} onPageChange={(page: number) => {}} - onPageSizeChange={(pageSize: number, props: ReactDataGrid.DataGridProps) => {}} + onPageSizeChange={(pageSize: number, props: any) => {}} onColumnOrderChange={(index: number, dropIndex: number) => {}} - onColumnResize={(firstCol: ReactDataGrid.Column, firstSize: number, secondCol: ReactDataGrid.Column, secondSize: number) => {}} + onColumnResize={(firstCol: any, firstSize: number, secondCol: any, secondSize: number) => {}} onSelectionChange={(newSelectedId: string, data: any) => {}} - onSortChange={(sortInfo: ReactDataGrid.SortInfo[]) => {}} - onFilter={(column: ReactDataGrid.Column, value: any, allFilterValues: any[]) => {} } + onSortChange={(sortInfo: any) => {}} + onFilter={(column: any, value: any, allFilterValues: any[]) => {} } /> ); } diff --git a/react-dropzone/index.d.ts b/react-dropzone/index.d.ts index fbdfaa44e2..2228e3a06a 100644 --- a/react-dropzone/index.d.ts +++ b/react-dropzone/index.d.ts @@ -5,6 +5,9 @@ /// +declare var Dropzone: typeof ReactDropzone.Dropzone; +export = Dropzone; + declare namespace ReactDropzone { interface DropzoneProps { onDrop?: Function; @@ -38,9 +41,3 @@ declare namespace ReactDropzone { } } - -declare module "react-dropzone" { - const Dropzone: typeof ReactDropzone.Dropzone; - export = Dropzone; -} - diff --git a/react-helmet/index.d.ts b/react-helmet/index.d.ts index dd201b3646..1a11567ff6 100644 --- a/react-helmet/index.d.ts +++ b/react-helmet/index.d.ts @@ -5,6 +5,13 @@ /// +declare var Helmet: { + (): ReactHelmet.HelmetComponent + rewind(): ReactHelmet.HelmetData + } + +export = Helmet; + declare namespace ReactHelmet { interface HelmetProps { title?: string; @@ -31,12 +38,3 @@ declare namespace ReactHelmet { class HelmetComponent extends React.Component {} } - -declare module "react-helmet" { - var Helmet: { - (): ReactHelmet.HelmetComponent - rewind(): ReactHelmet.HelmetData - } - - export = Helmet; -} diff --git a/react-infinite/index.d.ts b/react-infinite/index.d.ts index 91f8389312..696e0a5c7f 100644 --- a/react-infinite/index.d.ts +++ b/react-infinite/index.d.ts @@ -5,10 +5,8 @@ /// -declare module "react-infinite" { - import Infinite = ReactInfinite.Infinite; - export = Infinite; -} +import Infinite = ReactInfinite.Infinite; +export = Infinite; declare namespace ReactInfinite { interface InfiniteProps extends React.Props { diff --git a/react-notification-system/index.d.ts b/react-notification-system/index.d.ts index a467436670..b7b7438bca 100644 --- a/react-notification-system/index.d.ts +++ b/react-notification-system/index.d.ts @@ -76,7 +76,5 @@ declare namespace NotificationSystem { } -declare module 'react-notification-system' { - var component: React.ClassicComponentClass; - export = component; -} +declare var NotificationSystem: React.ClassicComponentClass; +export = NotificationSystem; diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 006cf80fb2..78c9f70c6c 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -7,6 +7,8 @@ /// /// +export = ReactRouterRedux; + declare namespace ReactRouterRedux { import R = Redux; @@ -56,7 +58,3 @@ declare namespace ReactRouterRedux { function syncHistoryWithStore(history: History.History, store: R.Store, options?: SyncHistoryWithStoreOptions): ReactRouterReduxHistory; function routerMiddleware(history: History.History): R.Middleware; } - -declare module "react-router-redux" { - export = ReactRouterRedux; -} diff --git a/redlock/index.d.ts b/redlock/index.d.ts index 423bc43563..9135b5f762 100644 --- a/redlock/index.d.ts +++ b/redlock/index.d.ts @@ -5,7 +5,7 @@ /// -declare namespace RedlockTypes { +declare namespace Redlock { interface LockError extends Error {} interface NodeifyCallback { @@ -28,35 +28,32 @@ declare namespace RedlockTypes { retryCount?: number; retryDelay?: number; } - - class Redlock { - LockError: LockError; - - driftFactor: number; - retryCount: number; - retryDelay: number; - - servers: any[]; // array of redis.RedisClient - - constructor(clients: any[], options?: RedlockOptions); - - acquire(resource: string, ttl: number, callback?: NodeifyCallback): Promise; - lock(resource: string, ttl: number, callback?: NodeifyCallback): Promise; - - disposer(resource: string, ttl: number): any; // return bluebird.Disposer - - release(lock: Lock, callback?: NodeifyCallback): Promise; - unlock(lock: Lock, callback?: NodeifyCallback): Promise; - - extend(lock: Lock, ttl: number, callback?: NodeifyCallback): Promise; - - _lock(resource: string, value: string, ttl: number, callback?: NodeifyCallback): Promise; - - _random(): string; - } } -declare module "redlock" { - import Redlock = RedlockTypes.Redlock; - export = Redlock; +declare class Redlock { + LockError: Redlock.LockError; + + driftFactor: number; + retryCount: number; + retryDelay: number; + + servers: any[]; // array of redis.RedisClient + + constructor(clients: any[], options?: Redlock.RedlockOptions); + + acquire(resource: string, ttl: number, callback?: Redlock.NodeifyCallback): Promise; + lock(resource: string, ttl: number, callback?: Redlock.NodeifyCallback): Promise; + + disposer(resource: string, ttl: number): any; // return bluebird.Disposer + + release(lock: Redlock.Lock, callback?: Redlock.NodeifyCallback): Promise; + unlock(lock: Redlock.Lock, callback?: Redlock.NodeifyCallback): Promise; + + extend(lock: Redlock.Lock, ttl: number, callback?: Redlock.NodeifyCallback): Promise; + + _lock(resource: string, value: string, ttl: number, callback?: Redlock.NodeifyCallback): Promise; + + _random(): string; } + +export = Redlock; diff --git a/redlock/redlock-tests.ts b/redlock/redlock-tests.ts index 67698003b3..a907cfe54b 100644 --- a/redlock/redlock-tests.ts +++ b/redlock/redlock-tests.ts @@ -2,9 +2,9 @@ import Redlock = require('redlock'); -import NodeifyCallback = RedlockTypes.NodeifyCallback; -import Lock = RedlockTypes.Lock; -import RedlockOptions = RedlockTypes.RedlockOptions; +import NodeifyCallback = Redlock.NodeifyCallback; +import Lock = Redlock.Lock; +import RedlockOptions = Redlock.RedlockOptions; namespace RedlockTest { // constructor diff --git a/redux-actions/index.d.ts b/redux-actions/index.d.ts index 8709bd2a02..b8859030dd 100644 --- a/redux-actions/index.d.ts +++ b/redux-actions/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Jack Hsu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = ReduxActions; + declare namespace ReduxActions { // FSA-compliant action. // See: https://github.com/acdlite/flux-standard-action @@ -29,7 +31,3 @@ declare namespace ReduxActions { export function handleActions(reducerMap: ReducerMap, initialState?: T): Reducer; } -declare module 'redux-actions' { - export = ReduxActions; -} - diff --git a/redux-actions/redux-actions-tests.ts b/redux-actions/redux-actions-tests.ts index 5081b7a90d..e76cbe711a 100644 --- a/redux-actions/redux-actions-tests.ts +++ b/redux-actions/redux-actions-tests.ts @@ -1,4 +1,4 @@ - +import ReduxActions = require("redux-actions"); const minimalAction: ReduxActions.Action = { type: 'INCREMENT' }; const richerAction: ReduxActions.Action = { diff --git a/redux-promise/index.d.ts b/redux-promise/index.d.ts index 677e2be195..2233bea641 100644 --- a/redux-promise/index.d.ts +++ b/redux-promise/index.d.ts @@ -5,14 +5,12 @@ /// +declare var promise: ReduxPromise.Promise; +export default promise; + declare namespace ReduxPromise { export interface Promise extends Redux.Middleware {} export interface PromiseInterface { (dispatch: Redux.Dispatch, getState?: () => T): any; } -} - -declare module "redux-promise" { - var promise: ReduxPromise.Promise; - export default promise; } \ No newline at end of file diff --git a/redux-promise/redux-promise-tests.ts b/redux-promise/redux-promise-tests.ts index a33d5320fa..8b8762e7b7 100644 --- a/redux-promise/redux-promise-tests.ts +++ b/redux-promise/redux-promise-tests.ts @@ -5,7 +5,6 @@ import {createAction} from 'redux-actions'; import { createStore, applyMiddleware } from 'redux'; import promise from 'redux-promise'; -import PromiseInterface = ReduxPromise.PromiseInterface; declare var userReducer: any; @@ -18,7 +17,7 @@ appStore.dispatch( listUsers() ); -function listUsers(): PromiseInterface { +function listUsers() { return createAction('LIST_USERS', () => { return Promise.resolve([{ email: 'me@definitely.typed' }]); diff --git a/redux-thunk/index.d.ts b/redux-thunk/index.d.ts index a48a4e8e21..cf7ee79cc5 100644 --- a/redux-thunk/index.d.ts +++ b/redux-thunk/index.d.ts @@ -5,14 +5,13 @@ /// +declare var thunk: ReduxThunk.Thunk; +export default thunk; +export as namespace ReduxThunk; + declare namespace ReduxThunk { export interface Thunk extends Redux.Middleware {} export interface ThunkInterface { (dispatch: Redux.Dispatch, getState?: () => T): any; } } - -declare module "redux-thunk" { - var thunk: ReduxThunk.Thunk; - export default thunk; -} diff --git a/redux-thunk/redux-thunk-tests.ts b/redux-thunk/redux-thunk-tests.ts index c7034196ad..09e507ee89 100644 --- a/redux-thunk/redux-thunk-tests.ts +++ b/redux-thunk/redux-thunk-tests.ts @@ -4,7 +4,6 @@ import { createStore, applyMiddleware, Store, Dispatch } from 'redux'; import thunk from 'redux-thunk'; -import ThunkInterface = ReduxThunk.ThunkInterface; declare var rootReducer: Function; declare var fetch: any; @@ -58,7 +57,7 @@ store.dispatch(withdrawMoney(100)); // A thunk is a function that returns a function. // This is a thunk. -function makeASandwichWithSecretSauce(forPerson: any): ThunkInterface { +function makeASandwichWithSecretSauce(forPerson: any) { // Invert control! // Return a function that accepts `dispatch` so we can dispatch later. @@ -92,7 +91,7 @@ store.dispatch( // actions and async actions from other action creators, // and I can build my control flow with Promises. -function makeSandwichesForEverybody(): ThunkInterface { +function makeSandwichesForEverybody() { return function (dispatch: Dispatch, getState: () => any): any { if (!getState().sandwiches.isShopOpen) { diff --git a/redux/index.d.ts b/redux/index.d.ts index 3327236c14..7d5bdf22e0 100644 --- a/redux/index.d.ts +++ b/redux/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: William Buchwalter , Vincent Prouillet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Redux; +export as namespace Redux; + declare namespace Redux { interface ActionCreator extends Function { @@ -45,8 +48,4 @@ declare namespace Redux { function combineReducers(reducers: any): Reducer; function applyMiddleware(...middlewares: Middleware[]): Function; function compose(...functions: Function[]): T; -} - -declare module "redux" { - export = Redux; -} +} \ No newline at end of file diff --git a/redux/redux-tests.ts b/redux/redux-tests.ts index cb158c80fe..83e56d5e81 100644 --- a/redux/redux-tests.ts +++ b/redux/redux-tests.ts @@ -1,4 +1,4 @@ - +import Redux = require("redux"); function counter(state: any, action: any) { if (!state) { diff --git a/reflux/index.d.ts b/reflux/index.d.ts index f7395b175e..0da53914bf 100644 --- a/reflux/index.d.ts +++ b/reflux/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Maurice de Beijer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = RefluxCore; +export as namespace Reflux; + declare module RefluxCore { interface StoreDefinition { @@ -56,8 +59,3 @@ declare module RefluxCore { function listenTo(store: Store, handler: string):void; function setState(state: any):void; } - -declare module "reflux" { - export = RefluxCore; -} - diff --git a/replace-ext/index.d.ts b/replace-ext/index.d.ts index d66680e7ca..f1e4e9806c 100644 --- a/replace-ext/index.d.ts +++ b/replace-ext/index.d.ts @@ -6,6 +6,4 @@ declare function replaceExt(npath: string, ext: string): string; -declare module 'replace-ext' { - export = replaceExt; -} +export = replaceExt; diff --git a/requirejs-domready/domready-tests.ts b/requirejs-domready/domready-tests.ts index fac3a18d7f..7900e7af36 100644 --- a/requirejs-domready/domready-tests.ts +++ b/requirejs-domready/domready-tests.ts @@ -1,5 +1,5 @@ -import domReady = require("domReady"); +import domReady = require("requirejs-domready"); domReady(() => { return domReady.version; diff --git a/requirejs-domready/index.d.ts b/requirejs-domready/index.d.ts index f094a63682..c0f094a869 100644 --- a/requirejs-domready/index.d.ts +++ b/requirejs-domready/index.d.ts @@ -3,13 +3,13 @@ // Definitions by: Nobuhiro Nakamura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "domReady" { - interface DomReady { - (callback: () => any): DomReady; - version: string; - } - let domReady: DomReady; - - export = domReady; +interface DomReady { + (callback: () => any): DomReady; + version: string; } + +declare var domReady: DomReady; + +export = domReady; + diff --git a/resolve-from/index.d.ts b/resolve-from/index.d.ts index a8d0441136..e74aa1da2a 100644 --- a/resolve-from/index.d.ts +++ b/resolve-from/index.d.ts @@ -4,6 +4,4 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function resolveFrom(fromDir: string, moduleId: string): string; -declare module "resolve-from" { - export = resolveFrom; -} +export = resolveFrom; diff --git a/resolve-from/resolve-from-tests.ts b/resolve-from/resolve-from-tests.ts index ae071d8aa5..ed803bd0cf 100644 --- a/resolve-from/resolve-from-tests.ts +++ b/resolve-from/resolve-from-tests.ts @@ -1,4 +1,4 @@ - +import resolveFrom = require("resolve-from"); // Much better testing in https://github.com/typed-typings/typed-resolve-from if (typeof resolveFrom !== 'function') { diff --git a/restangular/index.d.ts b/restangular/index.d.ts index 85652f8d4b..0410d32cd1 100644 --- a/restangular/index.d.ts +++ b/restangular/index.d.ts @@ -8,11 +8,9 @@ // Support AMD require (copying angular.d.ts approach) // allows for import {IRequestConfig} from 'restangular' ES6 approach -declare module 'restangular' { - export = restangular; -} - - +import * as angular from 'angularjs'; +export = restangular; +export as namespace Restangular; declare namespace restangular { diff --git a/restangular/restangular-tests.ts b/restangular/restangular-tests.ts index 906008eced..8e8893f4fd 100644 --- a/restangular/restangular-tests.ts +++ b/restangular/restangular-tests.ts @@ -1,5 +1,5 @@ - - +import restangular = require("restangular"); +import * as angular from 'angularjs'; var myApp = angular.module('testModule'); diff --git a/restify/index.d.ts b/restify/index.d.ts index d2edfc8137..561671d936 100644 --- a/restify/index.d.ts +++ b/restify/index.d.ts @@ -5,365 +5,364 @@ /// -declare module "restify" { - import http = require('http'); - import bunyan = require('bunyan'); +import http = require('http'); +import bunyan = require('bunyan'); - interface addressInterface { - port: number; - family: string; - address: string; - } - - interface requestFileInterface { - path: string; - type: string; - } +interface addressInterface { + port: number; + family: string; + address: string; +} + +interface requestFileInterface { + path: string; + type: string; +} + +/** + * Comes from authorizationParser plugin + */ +interface requestAuthorization { + scheme: string; + credentials: string; + basic?: { + username: string; + password: string; + } +} + +interface Request extends http.ServerRequest { + header: (key: string, defaultValue?: string) => any; + accepts: (type: string) => boolean; + is: (type: string) => boolean; + getLogger: (component: string) => any; + contentLength: number; + contentType: string; + href: () => string; + log: bunyan.Logger; + id: string; + path: () => string; + query: any; + secure: boolean; + time: number; + params: any; + files?: { [name: string]: requestFileInterface }; + isSecure: () => boolean; + /** available when bodyParser plugin is used */ + body?: any; + /** available when authorizationParser plugin is used */ + username?: string; + /** available when authorizationParser plugin is used */ + authorization?: requestAuthorization; +} + +interface Response extends http.ServerResponse { + header: (key: string, value ?: any) => any; + cache: (type?: any, options?: Object) => any; + status: (code: number) => any; + send: (status?: any, body?: any, headers?: { [header: string]: string }) => any; + json: (status?: any, body?: any, headers?: { [header: string]: string }) => any; + code: number; + contentLength: number; + charSet(value: string): void; + contentType: string; + headers: Object; + id: string; +} + +interface RouteSpec { + method: string; + name: string; + path: string; + versions: string[]; +} + +interface Route { + name: string; + method: string; + path: RoutePathRegex; + spec: RouteSpec; + types: string[]; + versions: string[]; +} + +interface RouteOptions { + name: string; + method: string; + path?: string | RegExp; + url?: string | RegExp; + urlParamPattern?: RegExp; + contentType?: string | string[]; + versions?: string | string[]; +} + +interface RoutePathRegex extends RegExp { + restifyParams: string[]; +} + +interface Router { + name: string; + mounts: { [routeName: string]: Route }; + versions: string[]; + contentType: string[]; + routes: { + DELETE: Route[]; + GET: Route[]; + HEAD: Route[]; + OPTIONS: Route[]; + PATCH: Route[]; + POST: Route[]; + PUT: Route[]; + }; + log?: any; + toString: () => string; /** - * Comes from authorizationParser plugin + * Takes an object of route params and query params, and 'renders' a URL + * @param {String} routeName the route name + * @param {Object} params an object of route params + * @param {Object} query an object of query params + * @returns {String} */ - interface requestAuthorization { - scheme: string; - credentials: string; - basic?: { - username: string; - password: string; - } - } - - interface Request extends http.ServerRequest { - header: (key: string, defaultValue?: string) => any; - accepts: (type: string) => boolean; - is: (type: string) => boolean; - getLogger: (component: string) => any; - contentLength: number; - contentType: string; - href: () => string; - log: bunyan.Logger; - id: string; - path: () => string; - query: any; - secure: boolean; - time: number; - params: any; - files?: { [name: string]: requestFileInterface }; - isSecure: () => boolean; - /** available when bodyParser plugin is used */ - body?: any; - /** available when authorizationParser plugin is used */ - username?: string; - /** available when authorizationParser plugin is used */ - authorization?: requestAuthorization; - } - - interface Response extends http.ServerResponse { - header: (key: string, value ?: any) => any; - cache: (type?: any, options?: Object) => any; - status: (code: number) => any; - send: (status?: any, body?: any, headers?: { [header: string]: string }) => any; - json: (status?: any, body?: any, headers?: { [header: string]: string }) => any; - code: number; - contentLength: number; - charSet(value: string): void; - contentType: string; - headers: Object; - id: string; - } + render: (routeName: string, params: Object, query?: Object) => string; - interface RouteSpec { - method: string; - name: string; - path: string; - versions: string[]; - } - - interface Route { - name: string; - method: string; - path: RoutePathRegex; - spec: RouteSpec; - types: string[]; - versions: string[]; - } + /** + * adds a route. + * @param {Object} options an options object + * @returns {String} returns the route name if creation is successful. + */ + mount: (options: Object) => string; - interface RouteOptions { - name: string; - method: string; - path?: string | RegExp; - url?: string | RegExp; - urlParamPattern?: RegExp; - contentType?: string | string[]; - versions?: string | string[]; - } - - interface RoutePathRegex extends RegExp { - restifyParams: string[]; - } - - interface Router { - name: string; - mounts: { [routeName: string]: Route }; - versions: string[]; - contentType: string[]; - routes: { - DELETE: Route[]; - GET: Route[]; - HEAD: Route[]; - OPTIONS: Route[]; - PATCH: Route[]; - POST: Route[]; - PUT: Route[]; - }; - log?: any; - toString: () => string; - - /** - * Takes an object of route params and query params, and 'renders' a URL - * @param {String} routeName the route name - * @param {Object} params an object of route params - * @param {Object} query an object of query params - * @returns {String} - */ - render: (routeName: string, params: Object, query?: Object) => string; - - /** - * adds a route. - * @param {Object} options an options object - * @returns {String} returns the route name if creation is successful. - */ - mount: (options: Object) => string; - - /** - * unmounts a route. - * @param {String} name the route name - * @returns {String} the name of the deleted route (or false if it was not matched) - */ - unmount: (name: string) => string | boolean; - } - - interface Server extends http.Server { - use(handler: RequestHandler, ...handlers: RequestHandler[]): Server; - use(handler: RequestHandler[], ...handlers: RequestHandler[]): Server; - use(handler: RequestHandler, ...handlers: RequestHandler[][]): Server; - use(handler: RequestHandler[], ...handlers: RequestHandler[][]): Server; - - post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - opts(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; - opts(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; - opts(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; - opts(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; - - name: string; - version: string; - log: Object; - acceptable: string[]; - url: string; - address: () => addressInterface; - listen(... args: any[]): any; - close(... args: any[]): any; - pre(routeCallBack: RequestHandler): Server; - server: http.Server; - router: Router; - routes: Route[]; - toString: () => string; - } - - interface ServerOptions { - certificate ?: string; - key ?: string; - formatters ?: Object; - log ?: Object; - name ?: string; - spdy ?: Object; - version ?: string; - responseTimeHeader ?: string; - responseTimeFormatter ?: (durationInMilliseconds: number) => any; - handleUpgrades ?: boolean; - router ?: Router; - } - - interface ClientOptions { - accept?: string; - connectTimeout?: number; - dtrace?: Object; - gzip?: Object; - headers?: Object; - log?: Object; - retry?: Object; - signRequest?: Function; - url?: string; - userAgent?: string; - version?: string; - } - - interface Client { - get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; - basicAuth: (username: string, password: string) => any; - } - - interface HttpClient extends Client { - get: (path?: any, callback?: Function) => any; - head: (path?:any, callback?: Function) => any; - post: (opts?: any, callback?: Function) => any; - put: (opts?: any, callback?: Function) => any; - del: (opts?: any, callback?: Function) => any; - } - - interface ThrottleOptions { - burst?: number; - rate?: number; - ip?: boolean; - xff?: boolean; - username?: boolean; - tokensTable?: Object; - maxKeys?: number; - overrides?: Object; - } - - interface Next { - (err?: any): any; - ifError: (err?: any) => any; - } - - interface RequestHandler { - (req: Request, res: Response, next: Next): any; - } - - interface CORS { - (cors?: { - origins?: string[]; - credentials?: boolean; - headers?: string[]; - }): RequestHandler; - origins: string[]; - ALLOW_HEADERS: string[]; - credentials: boolean; - } - - export function createServer(options?: ServerOptions): Server; - - export function createJsonClient(options?: ClientOptions): Client; - export function createStringClient(options?: ClientOptions): Client; - export function createClient(options?: ClientOptions): HttpClient; - - export class HttpError { constructor(cause: any, message?: any); } - - class DefiniteHttpError { - constructor(message?: any); - constructor(cause: any, message?: any); - } - - export class BadRequestError extends DefiniteHttpError {} - export class UnauthorizedError extends DefiniteHttpError {} - export class PaymentRequiredError extends DefiniteHttpError {} - export class ForbiddenError extends DefiniteHttpError {} - export class NotFoundError extends DefiniteHttpError {} - export class MethodNotAllowedError extends DefiniteHttpError {} - export class NotAcceptableError extends DefiniteHttpError {} - export class ProxyAuthenticationRequiredError extends DefiniteHttpError {} - export class RequestTimeoutError extends DefiniteHttpError {} - export class ConflictError extends DefiniteHttpError {} - export class GoneError extends DefiniteHttpError {} - export class LengthRequiredError extends DefiniteHttpError {} - export class RequestEntityTooLargeError extends DefiniteHttpError {} - export class RequesturiTooLargeError extends DefiniteHttpError {} - export class UnsupportedMediaTypeError extends DefiniteHttpError {} - export class RequestedRangeNotSatisfiableError extends DefiniteHttpError {} - export class ExpectationFailedError extends DefiniteHttpError {} - export class ImATeapotError extends DefiniteHttpError {} - export class UnprocessableEntityError extends DefiniteHttpError {} - export class LockedError extends DefiniteHttpError {} - export class FailedDependencyError extends DefiniteHttpError {} - export class UnorderedCollectionError extends DefiniteHttpError {} - export class UpgradeRequiredError extends DefiniteHttpError {} - export class PreconditionRequiredError extends DefiniteHttpError {} - export class TooManyRequestsError extends DefiniteHttpError {} - export class RequestHeaderFieldsTooLargeError extends DefiniteHttpError {} - export class InternalServerError extends DefiniteHttpError {} - export class NotImplementedError extends DefiniteHttpError {} - export class BadGatewayError extends DefiniteHttpError {} - export class ServiceUnavailableError extends DefiniteHttpError {} - export class GatewayTimeoutError extends DefiniteHttpError {} - export class HttpVersionNotSupportedError extends DefiniteHttpError {} - export class VariantAlsoNegotiatesError extends DefiniteHttpError {} - export class InsufficientStorageError extends DefiniteHttpError {} - export class BandwidthLimitExceededError extends DefiniteHttpError {} - export class NotExtendedError extends DefiniteHttpError {} - export class NetworkAuthenticationRequiredError extends DefiniteHttpError {} - export class RestError extends DefiniteHttpError {} - - export class PreconditionFailedError extends RestError {} - export class BadDigestError extends RestError {} - export class BadMethodError extends RestError {} - export class InternalError extends RestError {} - export class InvalidArgumentError extends RestError {} - export class InvalidContentError extends RestError {} - export class InvalidCredentialsError extends RestError {} - export class InvalidHeaderError extends RestError {} - export class InvalidVersionError extends RestError {} - export class MissingParameterError extends RestError {} - export class NotAuthorizedError extends RestError {} - export class RequestExpiredError extends RestError {} - export class RequestThrottledError extends RestError {} - export class ResourceNotFoundError extends RestError {} - export class WrongAcceptError extends RestError {} - - - export function acceptParser(parser: any): RequestHandler; - export function authorizationParser(): RequestHandler; - export function dateParser(skew?: number): RequestHandler; - export function queryParser(options?: Object): RequestHandler; - export function urlEncodedBodyParser(options?: Object): RequestHandler[]; - export function jsonp(): RequestHandler; - export function gzipResponse(options?: Object): RequestHandler; - export function bodyParser(options?: Object): RequestHandler[]; - export function requestLogger(options?: Object): RequestHandler; - export function serveStatic(options?: Object): RequestHandler; - export function throttle(options?: ThrottleOptions): RequestHandler; - export function conditionalRequest(): RequestHandler[]; - export function auditLogger(options?: Object): Function; - export function fullResponse(): RequestHandler; - export var defaultResponseHeaders : any; - export var CORS: CORS; - - export module pre { - export function pause(): RequestHandler; - export function sanitizePath(options?: any): RequestHandler; - export function userAgentConnection(options?: any): RequestHandler; - } + /** + * unmounts a route. + * @param {String} name the route name + * @returns {String} the name of the deleted route (or false if it was not matched) + */ + unmount: (name: string) => string | boolean; } + +interface Server extends http.Server { + use(handler: RequestHandler, ...handlers: RequestHandler[]): Server; + use(handler: RequestHandler[], ...handlers: RequestHandler[]): Server; + use(handler: RequestHandler, ...handlers: RequestHandler[][]): Server; + use(handler: RequestHandler[], ...handlers: RequestHandler[][]): Server; + + post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + opts(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): Route; + opts(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): Route; + opts(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): Route; + opts(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): Route; + + name: string; + version: string; + log: Object; + acceptable: string[]; + url: string; + address: () => addressInterface; + listen(... args: any[]): any; + close(... args: any[]): any; + pre(routeCallBack: RequestHandler): Server; + server: http.Server; + router: Router; + routes: Route[]; + toString: () => string; +} + +interface ServerOptions { + certificate ?: string; + key ?: string; + formatters ?: Object; + log ?: Object; + name ?: string; + spdy ?: Object; + version ?: string; + responseTimeHeader ?: string; + responseTimeFormatter ?: (durationInMilliseconds: number) => any; + handleUpgrades ?: boolean; + router ?: Router; +} + +interface ClientOptions { + accept?: string; + connectTimeout?: number; + dtrace?: Object; + gzip?: Object; + headers?: Object; + log?: Object; + retry?: Object; + signRequest?: Function; + url?: string; + userAgent?: string; + version?: string; +} + +interface Client { + get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; + basicAuth: (username: string, password: string) => any; +} + +interface HttpClient extends Client { + get: (path?: any, callback?: Function) => any; + head: (path?:any, callback?: Function) => any; + post: (opts?: any, callback?: Function) => any; + put: (opts?: any, callback?: Function) => any; + del: (opts?: any, callback?: Function) => any; +} + +interface ThrottleOptions { + burst?: number; + rate?: number; + ip?: boolean; + xff?: boolean; + username?: boolean; + tokensTable?: Object; + maxKeys?: number; + overrides?: Object; +} + +interface Next { + (err?: any): any; + ifError: (err?: any) => any; +} + +interface RequestHandler { + (req: Request, res: Response, next: Next): any; +} + +interface CORS { + (cors?: { + origins?: string[]; + credentials?: boolean; + headers?: string[]; + }): RequestHandler; + origins: string[]; + ALLOW_HEADERS: string[]; + credentials: boolean; +} + +export function createServer(options?: ServerOptions): Server; + +export function createJsonClient(options?: ClientOptions): Client; +export function createStringClient(options?: ClientOptions): Client; +export function createClient(options?: ClientOptions): HttpClient; + +export class HttpError { constructor(cause: any, message?: any); } + +declare class DefiniteHttpError { + constructor(message?: any); + constructor(cause: any, message?: any); +} + +export class BadRequestError extends DefiniteHttpError {} +export class UnauthorizedError extends DefiniteHttpError {} +export class PaymentRequiredError extends DefiniteHttpError {} +export class ForbiddenError extends DefiniteHttpError {} +export class NotFoundError extends DefiniteHttpError {} +export class MethodNotAllowedError extends DefiniteHttpError {} +export class NotAcceptableError extends DefiniteHttpError {} +export class ProxyAuthenticationRequiredError extends DefiniteHttpError {} +export class RequestTimeoutError extends DefiniteHttpError {} +export class ConflictError extends DefiniteHttpError {} +export class GoneError extends DefiniteHttpError {} +export class LengthRequiredError extends DefiniteHttpError {} +export class RequestEntityTooLargeError extends DefiniteHttpError {} +export class RequesturiTooLargeError extends DefiniteHttpError {} +export class UnsupportedMediaTypeError extends DefiniteHttpError {} +export class RequestedRangeNotSatisfiableError extends DefiniteHttpError {} +export class ExpectationFailedError extends DefiniteHttpError {} +export class ImATeapotError extends DefiniteHttpError {} +export class UnprocessableEntityError extends DefiniteHttpError {} +export class LockedError extends DefiniteHttpError {} +export class FailedDependencyError extends DefiniteHttpError {} +export class UnorderedCollectionError extends DefiniteHttpError {} +export class UpgradeRequiredError extends DefiniteHttpError {} +export class PreconditionRequiredError extends DefiniteHttpError {} +export class TooManyRequestsError extends DefiniteHttpError {} +export class RequestHeaderFieldsTooLargeError extends DefiniteHttpError {} +export class InternalServerError extends DefiniteHttpError {} +export class NotImplementedError extends DefiniteHttpError {} +export class BadGatewayError extends DefiniteHttpError {} +export class ServiceUnavailableError extends DefiniteHttpError {} +export class GatewayTimeoutError extends DefiniteHttpError {} +export class HttpVersionNotSupportedError extends DefiniteHttpError {} +export class VariantAlsoNegotiatesError extends DefiniteHttpError {} +export class InsufficientStorageError extends DefiniteHttpError {} +export class BandwidthLimitExceededError extends DefiniteHttpError {} +export class NotExtendedError extends DefiniteHttpError {} +export class NetworkAuthenticationRequiredError extends DefiniteHttpError {} +export class RestError extends DefiniteHttpError {} + +export class PreconditionFailedError extends RestError {} +export class BadDigestError extends RestError {} +export class BadMethodError extends RestError {} +export class InternalError extends RestError {} +export class InvalidArgumentError extends RestError {} +export class InvalidContentError extends RestError {} +export class InvalidCredentialsError extends RestError {} +export class InvalidHeaderError extends RestError {} +export class InvalidVersionError extends RestError {} +export class MissingParameterError extends RestError {} +export class NotAuthorizedError extends RestError {} +export class RequestExpiredError extends RestError {} +export class RequestThrottledError extends RestError {} +export class ResourceNotFoundError extends RestError {} +export class WrongAcceptError extends RestError {} + + +export function acceptParser(parser: any): RequestHandler; +export function authorizationParser(): RequestHandler; +export function dateParser(skew?: number): RequestHandler; +export function queryParser(options?: Object): RequestHandler; +export function urlEncodedBodyParser(options?: Object): RequestHandler[]; +export function jsonp(): RequestHandler; +export function gzipResponse(options?: Object): RequestHandler; +export function bodyParser(options?: Object): RequestHandler[]; +export function requestLogger(options?: Object): RequestHandler; +export function serveStatic(options?: Object): RequestHandler; +export function throttle(options?: ThrottleOptions): RequestHandler; +export function conditionalRequest(): RequestHandler[]; +export function auditLogger(options?: Object): Function; +export function fullResponse(): RequestHandler; +export var defaultResponseHeaders : any; +export var CORS: CORS; + +export module pre { + export function pause(): RequestHandler; + export function sanitizePath(options?: any): RequestHandler; + export function userAgentConnection(options?: any): RequestHandler; +} + diff --git a/rewire/index.d.ts b/rewire/index.d.ts index 8644b3df88..eca8d7b322 100644 --- a/rewire/index.d.ts +++ b/rewire/index.d.ts @@ -33,6 +33,4 @@ declare namespace RewireInterfaces { } declare var rewire: RewireInterfaces.Rewire; -declare module "rewire" { - export = rewire; -} +export = rewire; diff --git a/rewire/rewire-tests.ts b/rewire/rewire-tests.ts index c4f4e78d62..3815ceb873 100644 --- a/rewire/rewire-tests.ts +++ b/rewire/rewire-tests.ts @@ -1,4 +1,4 @@ - +import rewire = require("rewire"); var myModule = rewire("../lib/myModule.js"); diff --git a/riotcontrol/index.d.ts b/riotcontrol/index.d.ts index 64c397ffcf..2f32739ddb 100644 --- a/riotcontrol/index.d.ts +++ b/riotcontrol/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Ilya Mochalov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = RiotControl; +export as namespace RiotControl; + declare namespace RiotControl { interface Store { on(events: string, fn: Function): Store; @@ -20,7 +23,3 @@ declare namespace RiotControl { function off(events: string, fn?: Function): void; function trigger(name: string, ...args: any[]): void; } - -declare module "riotcontrol" { - export = RiotControl; -} diff --git a/riotcontrol/riotcontrol-tests.ts b/riotcontrol/riotcontrol-tests.ts index 7e732b6653..5a31bd0e66 100644 --- a/riotcontrol/riotcontrol-tests.ts +++ b/riotcontrol/riotcontrol-tests.ts @@ -3,7 +3,7 @@ import riotcontrol = require('riotcontrol'); { - let store: RiotControl.Store; + let store: riotcontrol.Store; let result: void; result = riotcontrol.addStore(store); } diff --git a/rosie/index.d.ts b/rosie/index.d.ts index a92359c3d9..86adc245ca 100644 --- a/rosie/index.d.ts +++ b/rosie/index.d.ts @@ -197,6 +197,5 @@ declare namespace rosie { declare var rosie: { Factory: rosie.IFactoryStatic }; -declare module 'rosie' { - export = rosie; -} +export = rosie; +export as namespace Factory; diff --git a/roslib/index.d.ts b/roslib/index.d.ts index 72af3a60ab..58d3292533 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -10,6 +10,8 @@ ---------------------------------- */ +export = ROSLIB; + declare namespace ROSLIB { export class Ros { /** @@ -417,7 +419,3 @@ declare namespace ROSLIB { cancel():void; } } - -declare module "ROSLIB" { - export = ROSLIB; -} diff --git a/roslib/roslib-tests.ts b/roslib/roslib-tests.ts index 4ef0b94f40..b67578536a 100644 --- a/roslib/roslib-tests.ts +++ b/roslib/roslib-tests.ts @@ -1,4 +1,4 @@ - +import ROSLIB = require("roslib"); var ros = new ROSLIB.Ros({ url: 'ws://localhost:9090' diff --git a/route-recognizer/index.d.ts b/route-recognizer/index.d.ts index a7dd48107b..0d47c4818e 100644 --- a/route-recognizer/index.d.ts +++ b/route-recognizer/index.d.ts @@ -3,22 +3,20 @@ // Definitions by: Dave Keen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "route-recognizer" { - - class RouteRecognizer { - constructor() - add: (routes: Route[]) => void - recognize: (path: string) => MatchedRoute[] - } - - interface Route { - path: string - handler: H - } - - export = RouteRecognizer +declare class RouteRecognizer { +constructor() + add: (routes: Route[]) => void + recognize: (path: string) => MatchedRoute[] } +interface Route { + path: string + handler: H +} + +export = RouteRecognizer; +export as namespace RouteRecognizer; + interface MatchedRoute { handler: H params: { [key: string]: string } diff --git a/rsmq/index.d.ts b/rsmq/index.d.ts index 622c015714..b10c6c30a1 100644 --- a/rsmq/index.d.ts +++ b/rsmq/index.d.ts @@ -68,25 +68,24 @@ declare namespace RedisSMQ { } } -declare module 'rsmq' { - import redis = require('redis'); +import redis = require('redis'); - interface RedisSMQStatic { - new (options:ClientOptions): Client; - } - - interface Client extends RedisSMQ.Client{ - redis: redis.RedisClient; - } - - interface ClientOptions { - host?: string; - port?: number; - options?: redis.ClientOpts; - client?: redis.RedisClient; - ns?: string; - } - - var rsmq: RedisSMQStatic; - export = rsmq; +interface RedisSMQStatic { + new (options:ClientOptions): Client; } + +interface Client extends RedisSMQ.Client{ + redis: redis.RedisClient; +} + +interface ClientOptions { + host?: string; + port?: number; + options?: redis.ClientOpts; + client?: redis.RedisClient; + ns?: string; +} + +declare var rsmq: RedisSMQStatic; +export = rsmq; + diff --git a/rsmq/rsmq-tests.ts b/rsmq/rsmq-tests.ts index 3575d0d3ca..4f2260a333 100644 --- a/rsmq/rsmq-tests.ts +++ b/rsmq/rsmq-tests.ts @@ -15,9 +15,9 @@ rsmq.createQueue({qname: "my-queue"}, (e: Error, success: number) => { rsmq.sendMessage({qname: "my-queue", message: "first message"}, (e: Error, id: string) => { rsmq.changeMessageVisibility({qname: "my-queue", id: id, vt: 100}, (e: Error, success: number) => {}); }); -rsmq.getQueueAttributes({qname: 'my-queue'}, (e: Error, attr: RedisSMQ.QueueAttributes) =>{} ); -rsmq.setQueueAttributes({qname: "my-queue", vt: 20}, (e: Error, attr: RedisSMQ.QueueAttributes) => {}); -rsmq.receiveMessage({qname: "my-queue"}, (e: Error, message: RedisSMQ.Message) => { +rsmq.getQueueAttributes({qname: 'my-queue'}, (e: Error, attr: any) =>{} ); +rsmq.setQueueAttributes({qname: "my-queue", vt: 20}, (e: Error, attr: any) => {}); +rsmq.receiveMessage({qname: "my-queue"}, (e: Error, message: any) => { rsmq.deleteMessage(message, (e: Error, success: number) => {}); }); rsmq.listQueues((e: Error, list: string[]) => {}); diff --git a/rss/index.d.ts b/rss/index.d.ts index 58b46b4d07..bd5653bf8f 100644 --- a/rss/index.d.ts +++ b/rss/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Second Datke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var factory: NodeRSS.RSSFactory; +export = factory; + declare namespace NodeRSS { interface FeedOptions { /** @@ -202,8 +205,3 @@ declare namespace NodeRSS { new(feedOptions: FeedOptions): RSS; } } - -declare module 'rss' { - var factory: NodeRSS.RSSFactory; - export = factory; -} diff --git a/s3-uploader/index.d.ts b/s3-uploader/index.d.ts index 2a8e6a10d7..166d98a663 100644 --- a/s3-uploader/index.d.ts +++ b/s3-uploader/index.d.ts @@ -5,62 +5,63 @@ //NOTE: Does require GM (https://github.com/aheckmann/gm) thus requires GraphicsMagick (http://www.graphicsmagick.org/) or ImageMagick (http://www.imagemagick.org/) -declare module "s3-uploader" { - export = Upload; -} -interface S3UploaderVersion { - original?: boolean; - suffix?: string; - quality?: number; - maxWidth?: number; - maxHeight?: number; -} +export = Upload; -interface S3UploaderOptions { - awsAccessKeyId?: string; - awsSecretAccessKey?: string; - awsBucketRegion?: string; - awsBucketPath?: string; - awsBucketAcl?: string; - awsMaxRetries?: number; - awsHttpTimeout?: number; - resizeQuality?: number; - returnExif?: boolean; - tmpDir?: string; - workers?: number; - url?: string; - versions?: S3UploaderVersion; -} +declare namespace Upload { + interface S3UploaderVersion { + original?: boolean; + suffix?: string; + quality?: number; + maxWidth?: number; + maxHeight?: number; + } -declare class Meta { - public format: string; - public fileSize: string; - public imageSize: imageSize; - public orientation: string; - public colorSpace: string; - public compression: string; - public quallity: string; -} + interface S3UploaderOptions { + awsAccessKeyId?: string; + awsSecretAccessKey?: string; + awsBucketRegion?: string; + awsBucketPath?: string; + awsBucketAcl?: string; + awsMaxRetries?: number; + awsHttpTimeout?: number; + resizeQuality?: number; + returnExif?: boolean; + tmpDir?: string; + workers?: number; + url?: string; + versions?: S3UploaderVersion; + } -declare class imageSize { - public height: number; - public width: number; -} + interface Meta { + format: string; + fileSize: string; + imageSize: imageSize; + orientation: string; + colorSpace: string; + compression: string; + quallity: string; + } -declare class image { - public etag: string; - public format: string; - public height: number; - public original: boolean; - public path: string; - public size: string; - public src: string; - public url: string; - public width: number; + interface imageSize { + height: number; + width: number; + } + + interface image { + etag: string; + format: string; + height: number; + original: boolean; + path: string; + size: string; + src: string; + url: string; + width: number; + } } declare class Upload { - public constructor(awsBucketName: string, opts: S3UploaderOptions); + public constructor(awsBucketName: string, opts: Upload.S3UploaderOptions); - public upload(src: string, opts?: S3UploaderOptions, cb?: (err: string, images: image[], meta: Meta) => void): void; + public upload(src: string, opts?: Upload.S3UploaderOptions, cb?: (err: string, images: Upload.image[], meta: Upload.Meta) => void): void; } diff --git a/s3-uploader/s3-uploader-tests.ts b/s3-uploader/s3-uploader-tests.ts index 312b8629b9..6f7fdffa88 100644 --- a/s3-uploader/s3-uploader-tests.ts +++ b/s3-uploader/s3-uploader-tests.ts @@ -5,18 +5,18 @@ import Upload = require('s3-uploader'); -var s3VersionOriginal: S3UploaderVersion = { +var s3VersionOriginal = { original: true }; -var s3VersionHeader: S3UploaderVersion = { +var s3VersionHeader = { suffix: '-header', quality: 100, maxHeight: 300, maxWidth: 600 } -var s3Config: S3UploaderOptions = { +var s3Config = { awsAccessKeyId: 'awsKeyId', awsSecretAccessKey: 'awsSecretAccessKey', awsBucketPath: '', diff --git a/scalike/index.d.ts b/scalike/index.d.ts index 8fa1b07685..1aa1c55899 100644 --- a/scalike/index.d.ts +++ b/scalike/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: ryoppy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = scalike; +export as namespace scalike; + declare namespace scalike { export interface Either { @@ -263,7 +266,3 @@ declare namespace scalike { run(f: (a: A, b: B, c: C, d: D, e: E, f: F) => G): Future; } } - -declare module "scalike" { - export = scalike -} diff --git a/scrypt-async/index.d.ts b/scrypt-async/index.d.ts index 367e1b06c7..e4a1867a1f 100644 --- a/scrypt-async/index.d.ts +++ b/scrypt-async/index.d.ts @@ -34,6 +34,4 @@ declare namespace ScryptAsync { declare var scrypt: ScryptAsync.ScryptStatic; -declare module "scrypt-async" { - export = scrypt; -} +export = scrypt; \ No newline at end of file diff --git a/scrypt-async/scrypt-async-tests.ts b/scrypt-async/scrypt-async-tests.ts index f1ae758524..ed12c9a5e5 100644 --- a/scrypt-async/scrypt-async-tests.ts +++ b/scrypt-async/scrypt-async-tests.ts @@ -1,5 +1,5 @@ // Tests by: Kaur Kuut - +import scrypt = require("scrypt-async"); var callback = function(key: string | number[]) { }; scrypt("abc", "def", 10, 8, 32, 1000, callback, "base64"); diff --git a/seedrandom/index.d.ts b/seedrandom/index.d.ts index c161556f7e..4db50058bc 100644 --- a/seedrandom/index.d.ts +++ b/seedrandom/index.d.ts @@ -3,41 +3,43 @@ // Definitions by: Kern Handa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type seedrandomStateType = boolean | (() => prng); +declare namespace seedrandom { -interface prng { - new(seed?: string, options?: seedRandomOptions, callback?: any): prng; - (): number; - quick(): number; - int32(): number; - double(): number; - state(): () => prng; + export type seedrandomStateType = boolean | (() => prng); + + interface prng { + new (seed?: string, options?: seedRandomOptions, callback?: any): prng; + (): number; + quick(): number; + int32(): number; + double(): number; + state(): () => prng; + } + + interface seedrandom_prng { + (seed?: string, options?: seedRandomOptions, callback?: any): prng; + alea: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xor128: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + tychei: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xorwow: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xor4096: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xorshift7: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + quick: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + } + + interface seedrandomCallback { + (prng?: prng, shortseed?: string, global?: boolean, state?: seedrandomStateType): prng; + } + + interface seedRandomOptions { + entropy?: boolean; + 'global'?: boolean; + state?: seedrandomStateType; + pass?: seedrandomCallback; + } } -interface seedrandom_prng { - (seed?: string, options?: seedRandomOptions, callback?: any): prng; - alea: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xor128: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - tychei: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xorwow: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xor4096: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xorshift7: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - quick: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; -} +declare var seedrandom: seedrandom.seedrandom_prng; -interface seedrandomCallback { - (prng?: prng, shortseed?: string, global?: boolean, state?: seedrandomStateType): prng; -} - -interface seedRandomOptions { - entropy?: boolean; - 'global'?: boolean; - state?: seedrandomStateType; - pass?: seedrandomCallback; -} - -declare var seedrandom: seedrandom_prng; - -declare module "seedrandom" { - export = seedrandom; -} +export = seedrandom; +export as namespace seedrandom; diff --git a/sendgrid/index.d.ts b/sendgrid/index.d.ts index 602e3de4fd..841e2ac21c 100644 --- a/sendgrid/index.d.ts +++ b/sendgrid/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Maxime LUCE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var ctor: Sendgrid.Constructor; +export = ctor; + declare namespace Sendgrid { //#region Options @@ -162,8 +165,3 @@ declare namespace Sendgrid { //#endregion } - -declare module "sendgrid" { - var ctor: Sendgrid.Constructor; - export = ctor; -} diff --git a/showdown/index.d.ts b/showdown/index.d.ts index 2a34defcb5..3316a1faba 100644 --- a/showdown/index.d.ts +++ b/showdown/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: cbowdon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Showdown; +export as namespace showdown; + declare namespace Showdown { /** Defined for information only - used in union type */ @@ -82,7 +85,3 @@ declare namespace Showdown { */ function forEach(obj: T[], callback: (value: T, index: number, array: T[]) => any): void; } - -declare module "showdown" { - export = Showdown; -} diff --git a/signals/index.d.ts b/signals/index.d.ts index 1825999fe7..879aa189f1 100644 --- a/signals/index.d.ts +++ b/signals/index.d.ts @@ -3,108 +3,110 @@ // Definitions by: Diullei Gomes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var signals: SignalWrapper; +declare var signals: signals.SignalWrapper; -declare module "signals" { - export = signals; -} - -interface SignalWrapper { - Signal: Signal -} - -interface SignalBinding { - active: boolean; - context: any; - params: any; - detach(): Function; - execute(paramsArr?:any[]): any; - getListener(): Function; - getSignal(): Signal; - isBound(): boolean; - isOnce(): boolean; -} - -interface Signal { - /** - * Custom event broadcaster - *
- inspired by Robert Penner's AS3 Signals. - * @name Signal - * @author Miller Medeiros - * @constructor - */ - new(): Signal; - - /** - * If Signal is active and should broadcast events. - */ - active: boolean; - - /** - * If Signal should keep record of previously dispatched parameters and automatically - * execute listener during add()/addOnce() if Signal was already dispatched before. - */ - memorize: boolean; - - /** - * Signals Version Number - */ - VERSION: string; - - /** - * Add a listener to the signal. - * - * @param listener Signal handler function. - * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - */ - add(listener: Function, listenerContext?: any, priority?: Number): SignalBinding; - - /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * - * @param listener Signal handler function. - * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - */ - addOnce(listener: Function, listenerContext?: any, priority?: Number): SignalBinding; - - /** - * Dispatch/Broadcast Signal to all listeners added to the queue. - * - * @param params Parameters that should be passed to each handler. - */ - dispatch(...params: any[]): void; - - /** - * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). - */ - dispose(): void; - - /** - * Forget memorized arguments. - */ - forget(): void; - - /** - * Returns a number of listeners attached to the Signal. - */ - getNumListeners(): number; - - /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - */ - halt(): void; - - /** - * Check if listener was attached to Signal. - */ - has(listener: Function, context?: any): boolean; - - /** - * Remove a single listener from the dispatch queue. - */ - remove(listener: Function, context?: any): Function; - - removeAll(): void; +export = signals; +export as namespace signals; + +declare namespace signals { + + interface SignalWrapper { + Signal: Signal + } + + interface SignalBinding { + active: boolean; + context: any; + params: any; + detach(): Function; + execute(paramsArr?: any[]): any; + getListener(): Function; + getSignal(): Signal; + isBound(): boolean; + isOnce(): boolean; + } + + interface Signal { + /** + * Custom event broadcaster + *
- inspired by Robert Penner's AS3 Signals. + * @name Signal + * @author Miller Medeiros + * @constructor + */ + new (): Signal; + + /** + * If Signal is active and should broadcast events. + */ + active: boolean; + + /** + * If Signal should keep record of previously dispatched parameters and automatically + * execute listener during add()/addOnce() if Signal was already dispatched before. + */ + memorize: boolean; + + /** + * Signals Version Number + */ + VERSION: string; + + /** + * Add a listener to the signal. + * + * @param listener Signal handler function. + * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + */ + add(listener: Function, listenerContext?: any, priority?: Number): SignalBinding; + + /** + * Add listener to the signal that should be removed after first execution (will be executed only once). + * + * @param listener Signal handler function. + * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + */ + addOnce(listener: Function, listenerContext?: any, priority?: Number): SignalBinding; + + /** + * Dispatch/Broadcast Signal to all listeners added to the queue. + * + * @param params Parameters that should be passed to each handler. + */ + dispatch(...params: any[]): void; + + /** + * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). + */ + dispose(): void; + + /** + * Forget memorized arguments. + */ + forget(): void; + + /** + * Returns a number of listeners attached to the Signal. + */ + getNumListeners(): number; + + /** + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + */ + halt(): void; + + /** + * Check if listener was attached to Signal. + */ + has(listener: Function, context?: any): boolean; + + /** + * Remove a single listener from the dispatch queue. + */ + remove(listener: Function, context?: any): Function; + + removeAll(): void; + } } diff --git a/signals/js-signals-tests.ts b/signals/js-signals-tests.ts index 5b1215280e..a0fa8e34f1 100644 --- a/signals/js-signals-tests.ts +++ b/signals/js-signals-tests.ts @@ -1,7 +1,8 @@ +import signals = require("signals"); // lifted from https://github.com/millermedeiros/js-signals/wiki/Examples interface TestObject { - started: Signal; - stopped: Signal; + started: signals.Signal; + stopped: signals.Signal; } namespace Signals.Tests { @@ -143,11 +144,11 @@ namespace Signals.AdvancedTests { var handler = function(){ alert('foo bar'); }; - var binding:SignalBinding = myObject.started.add(handler); //methods `add()` and `addOnce()` returns a SignalBinding object + var binding: signals.SignalBinding = myObject.started.add(handler); //methods `add()` and `addOnce()` returns a SignalBinding object binding.execute(); //will alert "foo bar" //Retrieve anonymous listener - var binding:SignalBinding = myObject.started.add(function(){ + var binding:signals.SignalBinding = myObject.started.add(function(){ alert('foo bar'); }); @@ -156,7 +157,7 @@ namespace Signals.AdvancedTests { var anonymousHandler = binding.getListener(); //reference to the anonymous function //Remove / Detach anonymous listener - var binding:SignalBinding = myObject.started.add(function(){ + var binding:signals.SignalBinding = myObject.started.add(function(){ alert('foo bar'); }); myObject.started.dispatch(); //will alert "foo bar" @@ -165,10 +166,10 @@ namespace Signals.AdvancedTests { myObject.started.dispatch(); //nothing happens //Check if binding will execute only once - var binding1:SignalBinding = myObject.started.add(function(){ + var binding1:signals.SignalBinding = myObject.started.add(function(){ alert('foo bar'); }); - var binding2:SignalBinding = myObject.started.addOnce(function(){ + var binding2:signals.SignalBinding = myObject.started.addOnce(function(){ alert('foo bar'); }); alert(binding1.isOnce()); //alert "false" @@ -179,7 +180,7 @@ namespace Signals.AdvancedTests { var obj = { foo : "it's over 9000!" }; - var binding:SignalBinding = myObject.started.add(function(){ + var binding:signals.SignalBinding = myObject.started.add(function(){ alert(this.foo); }); myObject.started.dispatch(); //will alert "bar" @@ -187,7 +188,7 @@ namespace Signals.AdvancedTests { myObject.started.dispatch(); //will alert "it's over 9000!" //Add default parameters to Signal dispatch (v0.6.3+) - var binding:SignalBinding = myObject.started.add(function(a:string, b:string, c:string){ + var binding:signals.SignalBinding = myObject.started.add(function(a:string, b:string, c:string){ alert(a +' '+ b +' '+ c); }); binding.params = ['lorem', 'ipsum']; //set default parameters of the binding diff --git a/simple-mock/index.d.ts b/simple-mock/index.d.ts index 3a5aa9a684..dd95b6159f 100644 --- a/simple-mock/index.d.ts +++ b/simple-mock/index.d.ts @@ -188,7 +188,6 @@ declare namespace Simple { } } -declare module "simple-mock" { - var simple: Simple.Static; - export = simple; -} +declare var Simple: Simple.Static; +export = Simple; + diff --git a/simple-mock/simple-mock-tests.ts b/simple-mock/simple-mock-tests.ts index 4da625f063..7bea9ca625 100644 --- a/simple-mock/simple-mock-tests.ts +++ b/simple-mock/simple-mock-tests.ts @@ -4,31 +4,31 @@ 'use strict'; -import simple = require('simple-mock'); +import Simple = require('Simple-mock'); import assert = require('assert'); import Bluebird = require('bluebird'); -// Following code is a TypeScript convertion of the test suite bundled with simple-mock. +// Following code is a TypeScript convertion of the test suite bundled with Simple-mock. // Original test in MIT license -describe('simple', function () { - describe('spy()', function () { - describe('for noop function', function () { +describe('Simple', function() { + describe('spy()', function() { + describe('for noop function', function() { let spyFn: Simple.Spy; - beforeEach(function () { - spyFn = simple.spy(function () {}) + beforeEach(function() { + spyFn = Simple.spy(function() { }) }) - it('can be queried without having been called', function () { + it('can be queried without having been called', function() { assert.equal(spyFn.callCount, 0) assert.deepEqual(spyFn.calls, []) assert(spyFn.lastCall) assert.deepEqual(spyFn.lastCall.args, []) }) - it('can be queried for arguments on a single call', function () { + it('can be queried for arguments on a single call', function() { let context = { spyFn: spyFn } @@ -45,7 +45,7 @@ describe('simple', function () { assert.equal(spyFn.lastCall.context, context) }) - it('can be queried for arguments over multiple calls', function () { + it('can be queried for arguments over multiple calls', function() { let context = { spyFn: spyFn } @@ -69,20 +69,20 @@ describe('simple', function () { }) }) - describe('for a throwing function', function () { + describe('for a throwing function', function() { let originalFn: () => void; let spyFn: Simple.Spy; - beforeEach(function () { + beforeEach(function() { let i = 0 - originalFn = function () { + originalFn = function() { throw new Error(`${i++}`) } - spyFn = simple.spy(originalFn) + spyFn = Simple.spy(originalFn) }) - it('can be queried without having been called', function () { + it('can be queried without having been called', function() { assert(!spyFn.called) assert.equal(spyFn.callCount, 0) assert.deepEqual(spyFn.calls, []) @@ -90,7 +90,7 @@ describe('simple', function () { assert.equal(spyFn.lastCall.threw, undefined) }) - it('can be queried for what it threw on a single call', function () { + it('can be queried for what it threw on a single call', function() { let threw: Error; try { spyFn() @@ -105,7 +105,7 @@ describe('simple', function () { assert.equal(spyFn.firstCall.threw, threw) }) - it('can be queried for what it threw over multiple calls', function () { + it('can be queried for what it threw over multiple calls', function() { let threw: Error[] = [] try { spyFn() @@ -133,20 +133,20 @@ describe('simple', function () { }) }) - describe('for a returning function', function () { + describe('for a returning function', function() { let originalFn: () => number; let spyFn: Simple.Spy; - beforeEach(function () { + beforeEach(function() { let i = 1 originalFn = () => { return i++ } - spyFn = simple.spy(originalFn) + spyFn = Simple.spy(originalFn) }) - it('can be queried without having been called', function () { + it('can be queried without having been called', function() { assert(!spyFn.called) assert.equal(spyFn.callCount, 0) assert.deepEqual(spyFn.calls, []) @@ -154,7 +154,7 @@ describe('simple', function () { assert.equal(spyFn.lastCall.returned, undefined) }) - it('can be queried for what it threw on a single call', function () { + it('can be queried for what it threw on a single call', function() { let returned: number returned = spyFn() @@ -165,7 +165,7 @@ describe('simple', function () { assert.equal(spyFn.firstCall.returned, returned) }) - it('can be queried for what it threw over multiple calls', function () { + it('can be queried for what it threw over multiple calls', function() { let returned: number[] = [] returned.push(spyFn()) @@ -182,11 +182,11 @@ describe('simple', function () { }) }) - describe('calls of multiple spies', function () { - it('can be compared to determine the order they were called in', function () { - let spy1 = simple.spy(function () {}) - let spy2 = simple.spy(function () {}) - let spy3 = simple.spy(function () {}) + describe('calls of multiple spies', function() { + it('can be compared to determine the order they were called in', function() { + let spy1 = Simple.spy(function() { }) + let spy2 = Simple.spy(function() { }) + let spy3 = Simple.spy(function() { }) spy1() spy3() @@ -201,11 +201,11 @@ describe('simple', function () { }) }) - describe('stub()', function () { - describe('with no configuration', function () { + describe('stub()', function() { + describe('with no configuration', function() { let stubFn: Simple.Stub; - it('is also a spy', function () { - stubFn = simple.stub() + it('is also a spy', function() { + stubFn = Simple.stub() stubFn('etc') assert(stubFn.called) @@ -213,15 +213,15 @@ describe('simple', function () { }) }) - describe('for a single callback configuration', function () { + describe('for a single callback configuration', function() { let stubFn: Simple.Stub; - describe('with default index', function () { - beforeEach(function () { - stubFn = simple.stub().callbackWith(1, 2, 3) + describe('with default index', function() { + beforeEach(function() { + stubFn = Simple.stub().callbackWith(1, 2, 3) }) - it('can call back with arguments', function () { - stubFn('a', function () { + it('can call back with arguments', function() { + stubFn('a', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 1) assert.equal(stubFn.lastCall.args[0], 'a') @@ -232,9 +232,9 @@ describe('simple', function () { }) }) - it('can call back with arguments, over multiple calls', function () { - stubFn('a', function () {}) - stubFn('b', function () { + it('can call back with arguments, over multiple calls', function() { + stubFn('a', function() { }) + stubFn('b', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 2) assert.equal(stubFn.lastCall.args[0], 'b') @@ -246,13 +246,13 @@ describe('simple', function () { }) }) - describe('with specified index', function () { - beforeEach(function () { - stubFn = simple.stub().callbackArgWith(1, 2, 3) + describe('with specified index', function() { + beforeEach(function() { + stubFn = Simple.stub().callbackArgWith(1, 2, 3) }) - it('can call back with arguments', function () { - stubFn('a', function () { + it('can call back with arguments', function() { + stubFn('a', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 1) assert.equal(stubFn.lastCall.args[0], 'a') @@ -262,9 +262,9 @@ describe('simple', function () { }) }) - it('can call back with arguments, over multiple calls', function () { - stubFn('a', function () {}) - stubFn('b', function () { + it('can call back with arguments, over multiple calls', function() { + stubFn('a', function() { }) + stubFn('b', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 2) assert.equal(stubFn.lastCall.args[0], 'b') @@ -275,13 +275,13 @@ describe('simple', function () { }) }) - describe('with context specified', function () { - beforeEach(function () { - stubFn = simple.stub().callback().inThisContext({ a: 'a' }) + describe('with context specified', function() { + beforeEach(function() { + stubFn = Simple.stub().callback().inThisContext({ a: 'a' }) }) - it('should do what...', function (done) { - stubFn(function () { + it('should do what...', function(done) { + stubFn(function() { assert.equal(this.a, 'a') done() }) @@ -289,14 +289,14 @@ describe('simple', function () { }) }) - describe('for a multiple callback configurations', function () { + describe('for a multiple callback configurations', function() { let stubFn: Simple.Stub; - beforeEach(function () { - stubFn = simple.stub().callbackWith(1).callbackWith(2).callbackWith(3) + beforeEach(function() { + stubFn = Simple.stub().callbackWith(1).callbackWith(2).callbackWith(3) }) - it('can call back once with arguments', function () { - stubFn('a', function () { + it('can call back once with arguments', function() { + stubFn('a', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 1) assert.equal(stubFn.lastCall.args[0], 'a') @@ -304,57 +304,57 @@ describe('simple', function () { }) }) - it('can call back with arguments, over multiple calls, looping per default', function () { - stubFn('a', function () {}) - stubFn('b', function () { + it('can call back with arguments, over multiple calls, looping per default', function() { + stubFn('a', function() { }) + stubFn('b', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 2) assert.equal(stubFn.lastCall.args[0], 'b') assert.equal(arguments[0], 2) }) - stubFn('c', function () { + stubFn('c', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 3) assert.equal(stubFn.lastCall.args[0], 'c') assert.equal(arguments[0], 3) }) - stubFn('d', function () { + stubFn('d', function() { assert.equal(stubFn.callCount, 4) assert.equal(stubFn.lastCall.args[0], 'd') assert.equal(arguments[0], 1) }) }) - it('can call back with arguments, over multiple calls, looping turned off', function () { + it('can call back with arguments, over multiple calls, looping turned off', function() { stubFn.loop = false - stubFn('a', function () {}) - stubFn('b', function () { + stubFn('a', function() { }) + stubFn('b', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 2) assert.equal(stubFn.lastCall.args[0], 'b') assert.equal(arguments[0], 2) }) - stubFn('c', function () { + stubFn('c', function() { assert(stubFn.called) assert.equal(stubFn.callCount, 3) assert.equal(stubFn.lastCall.args[0], 'c') assert.equal(arguments[0], 3) }) let neverCalled = true - stubFn('d', function () { + stubFn('d', function() { neverCalled = false }) assert(neverCalled) }) }) - describe('for a single throwing configuration', function () { + describe('for a single throwing configuration', function() { let stubFn: Simple.Stub; - beforeEach(function () { - stubFn = simple.stub().throwWith(new Error('example')) + beforeEach(function() { + stubFn = Simple.stub().throwWith(new Error('example')) }) - it('can throw', function () { + it('can throw', function() { let threw: Error try { stubFn() @@ -368,7 +368,7 @@ describe('simple', function () { assert.equal(threw.message, 'example') }) - it('can throw over multiple calls, looping per default', function () { + it('can throw over multiple calls, looping per default', function() { let threw: Error[] = [] try { stubFn() @@ -389,13 +389,13 @@ describe('simple', function () { }) }) - describe('for a multiple throwing configurations', function () { + describe('for a multiple throwing configurations', function() { let stubFn: Simple.Stub; - beforeEach(function () { - stubFn = simple.stub().throwWith(new Error('a')).throwWith(new Error('b')) + beforeEach(function() { + stubFn = Simple.stub().throwWith(new Error('a')).throwWith(new Error('b')) }) - it('can throw', function () { + it('can throw', function() { let threw: Error try { stubFn() @@ -409,7 +409,7 @@ describe('simple', function () { assert.equal(threw.message, 'a') }) - it('can throw over multiple calls, looping per default', function () { + it('can throw over multiple calls, looping per default', function() { let threw: Error[] = [] try { stubFn() @@ -435,7 +435,7 @@ describe('simple', function () { assert.equal(threw[2].message, 'a') }) - it('can throw over multiple calls, looping turned off', function () { + it('can throw over multiple calls, looping turned off', function() { stubFn.loop = false let threw: Error[] = [] @@ -463,13 +463,13 @@ describe('simple', function () { }) }) - describe('for a single returning configuration', function () { + describe('for a single returning configuration', function() { let stubFn: Simple.Stub; - beforeEach(function () { - stubFn = simple.stub() + beforeEach(function() { + stubFn = Simple.stub() }) - it('can return', function () { + it('can return', function() { stubFn.returnWith('example') let returned: string @@ -480,7 +480,7 @@ describe('simple', function () { assert.equal(returned, 'example') }) - it('can return an empty string', function () { + it('can return an empty string', function() { stubFn.returnWith('') let returned: string @@ -490,7 +490,7 @@ describe('simple', function () { assert.equal(returned, '') }) - it('can return over multiple calls, looping per default', function () { + it('can return over multiple calls, looping per default', function() { stubFn.returnWith('example-a') stubFn.returnWith('example-b') @@ -510,13 +510,13 @@ describe('simple', function () { }) }) - describe('for a multiple returning configurations', function () { + describe('for a multiple returning configurations', function() { let stubFn: Simple.Stub; - beforeEach(function () { - stubFn = simple.stub().returnWith('a').returnWith('b') + beforeEach(function() { + stubFn = Simple.stub().returnWith('a').returnWith('b') }) - it('can return', function () { + it('can return', function() { let returned: string returned = stubFn() @@ -525,7 +525,7 @@ describe('simple', function () { assert.equal(returned, 'a') }) - it('can return over multiple calls, looping per default', function () { + it('can return over multiple calls, looping per default', function() { let returned: string[] = [] returned.push(stubFn()) returned.push(stubFn()) @@ -539,7 +539,7 @@ describe('simple', function () { assert.equal(returned[2], 'a') }) - it('can return over multiple calls, looping turned off', function () { + it('can return over multiple calls, looping turned off', function() { stubFn.loop = false let returned: string[] = [] @@ -556,9 +556,9 @@ describe('simple', function () { }) }) - describe('for a specified function to call', function () { - it('should be called with arguments and return', function () { - let stubFn = simple.stub().callFn(function () { + describe('for a specified function to call', function() { + it('should be called with arguments and return', function() { + let stubFn = Simple.stub().callFn(function() { return arguments }) @@ -569,22 +569,22 @@ describe('simple', function () { assert.equal(returned[1], 'x') }) - it('should be able to throw', function () { - let stubFn = simple.stub().callFn(function () { + it('should be able to throw', function() { + let stubFn = Simple.stub().callFn(function() { throw new Error('my message') }) try { stubFn() - } catch(e) { + } catch (e) { assert(e instanceof Error) assert.equal(e.message, 'my message') } }) - it('should be called in context', function () { + it('should be called in context', function() { let mockObj = { - stubFn: simple.stub().callFn(function () { + stubFn: Simple.stub().callFn(function() { return this }) } @@ -594,11 +594,11 @@ describe('simple', function () { assert.equal(returned, mockObj) }) - it('can be called in specified context', function () { + it('can be called in specified context', function() { let anotherMockObj = {} let mockObj = { - stubFn: simple.stub().callFn(function () { + stubFn: Simple.stub().callFn(function() { return this }).inThisContext(anotherMockObj) } @@ -609,13 +609,13 @@ describe('simple', function () { }) }) - describe('for custom/when-conforming promises', function () { + describe('for custom/when-conforming promises', function() { let fulfilledStub: Simple.Stub let rejectedStub: Simple.Stub - beforeEach(function () { - fulfilledStub = simple.stub().returnWith(true) - rejectedStub = simple.stub().returnWith(true) + beforeEach(function() { + fulfilledStub = Simple.stub().returnWith(true) + rejectedStub = Simple.stub().returnWith(true) interface MockPromise { resolveValue: T, @@ -626,22 +626,22 @@ describe('simple', function () { let mockPromise: MockPromise = { resolveValue: null as boolean, rejectValue: null as boolean, - then: function (fulfilledFn: (value: any) => boolean, rejectedFn: (error: any) => boolean) { + then: function(fulfilledFn: (value: any) => boolean, rejectedFn: (error: any) => boolean) { let self = this - process.nextTick(function () { + process.nextTick(function() { if (self.resolveValue) return fulfilledFn(self.resolveValue) if (self.rejectValue) return rejectedFn(self.rejectValue) }) } } - simple.mock(simple, 'Promise', { - when: function(value: T) { + Simple.mock(Simple, 'Promise', { + when: function (value: T) { let promise: MockPromise = Object.create(mockPromise) promise.resolveValue = value return promise }, - reject: function(value: T) { + reject: function (value: T) { let promise: MockPromise = Object.create(mockPromise) promise.rejectValue = value return promise @@ -649,20 +649,20 @@ describe('simple', function () { }) }) - describe('with a single resolving configuration', function () { + describe('with a single resolving configuration', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().resolveWith('example') + beforeEach(function() { + stubFn = Simple.stub().resolveWith('example') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 1) assert.equal(fulfilledStub.lastCall.arg, 'example') assert.equal(rejectedStub.callCount, 0) @@ -671,20 +671,20 @@ describe('simple', function () { }) }) - describe('with a multiple resolving configurations', function () { + describe('with a multiple resolving configurations', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().resolveWith('a').resolveWith('b') + beforeEach(function() { + stubFn = Simple.stub().resolveWith('a').resolveWith('b') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 1) assert.equal(fulfilledStub.lastCall.arg, 'a') assert.equal(rejectedStub.callCount, 0) @@ -692,12 +692,12 @@ describe('simple', function () { }, 0) }) - it('can return over multiple calls, looping per default', function (done) { + it('can return over multiple calls, looping per default', function(done) { stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 3) assert.equal(fulfilledStub.calls[0].arg, 'a') assert.equal(fulfilledStub.calls[1].arg, 'b') @@ -708,20 +708,20 @@ describe('simple', function () { }) }) - describe('with a single rejecting configuration', function () { + describe('with a single rejecting configuration', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().rejectWith('example') + beforeEach(function() { + stubFn = Simple.stub().rejectWith('example') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 1) assert.equal(rejectedStub.lastCall.arg, 'example') @@ -730,20 +730,20 @@ describe('simple', function () { }) }) - describe('with a multiple rejecting configurations', function () { + describe('with a multiple rejecting configurations', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().rejectWith('a').rejectWith('b') + beforeEach(function() { + stubFn = Simple.stub().rejectWith('a').rejectWith('b') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 1) assert.equal(rejectedStub.lastCall.arg, 'a') @@ -751,12 +751,12 @@ describe('simple', function () { }, 0) }) - it('can return over multiple calls, looping per default', function (done) { + it('can return over multiple calls, looping per default', function(done) { stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 3) assert.equal(rejectedStub.calls[0].arg, 'a') @@ -768,29 +768,29 @@ describe('simple', function () { }) }) - describe('for native/conforming promises', function () { + describe('for native/conforming promises', function() { let fulfilledStub: Simple.Stub let rejectedStub: Simple.Stub - beforeEach(function () { - fulfilledStub = simple.stub().returnWith(true) - rejectedStub = simple.stub().returnWith(true) + beforeEach(function() { + fulfilledStub = Simple.stub().returnWith(true) + rejectedStub = Simple.stub().returnWith(true) }) - describe('with a single resolving configuration', function () { + describe('with a single resolving configuration', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().resolveWith('example') + beforeEach(function() { + stubFn = Simple.stub().resolveWith('example') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 1) assert.equal(fulfilledStub.lastCall.arg, 'example') assert.equal(rejectedStub.callCount, 0) @@ -799,20 +799,20 @@ describe('simple', function () { }) }) - describe('with a multiple resolving configurations', function () { + describe('with a multiple resolving configurations', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().resolveWith('a').resolveWith('b') + beforeEach(function() { + stubFn = Simple.stub().resolveWith('a').resolveWith('b') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 1) assert.equal(fulfilledStub.lastCall.arg, 'a') assert.equal(rejectedStub.callCount, 0) @@ -820,12 +820,12 @@ describe('simple', function () { }, 0) }) - it('can return over multiple calls, looping per default', function (done) { + it('can return over multiple calls, looping per default', function(done) { stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 3) assert.equal(fulfilledStub.calls[0].arg, 'a') assert.equal(fulfilledStub.calls[1].arg, 'b') @@ -836,20 +836,20 @@ describe('simple', function () { }) }) - describe('with a single rejecting configuration', function () { + describe('with a single rejecting configuration', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().rejectWith('example') + beforeEach(function() { + stubFn = Simple.stub().rejectWith('example') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 1) assert.equal(rejectedStub.lastCall.arg, 'example') @@ -858,20 +858,20 @@ describe('simple', function () { }) }) - describe('with a multiple rejecting configurations', function () { + describe('with a multiple rejecting configurations', function() { let stubFn: Simple.Stub>; - beforeEach(function () { - stubFn = simple.stub().rejectWith('a').rejectWith('b') + beforeEach(function() { + stubFn = Simple.stub().rejectWith('a').rejectWith('b') }) - it('can return a promise', function (done) { + it('can return a promise', function(done) { let returned = stubFn() assert(returned) returned.then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 1) assert.equal(rejectedStub.lastCall.arg, 'a') @@ -879,12 +879,12 @@ describe('simple', function () { }, 0) }) - it('can return over multiple calls, looping per default', function (done) { + it('can return over multiple calls, looping per default', function(done) { stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) stubFn().then(fulfilledStub, rejectedStub) - setTimeout(function () { + setTimeout(function() { assert.equal(fulfilledStub.callCount, 0) assert.equal(rejectedStub.callCount, 3) assert.equal(rejectedStub.calls[0].arg, 'a') @@ -897,8 +897,8 @@ describe('simple', function () { }) }) - describe('mock()', function () { - describe('on a object with prototype', function () { + describe('mock()', function() { + describe('on a object with prototype', function() { class ProtoKlass { protoValue: string = 'x' protoFn() { @@ -908,96 +908,96 @@ describe('simple', function () { let obj: any - before(function () { + before(function() { }) - beforeEach(function () { + beforeEach(function() { obj = new ProtoKlass() }) - it('can mock instance values over its prototype\'s and restore', function () { - simple.mock(obj, 'protoValue', 'y') + it('can mock instance values over its prototype\'s and restore', function() { + Simple.mock(obj, 'protoValue', 'y') assert.equal(obj.protoValue, 'y') - simple.restore() + Simple.restore() assert.equal(obj.protoValue, 'x') }) - it('can mock with custom instance functions over its prototype\'s and restore', function () { - simple.mock(obj, 'protoFn', function () { + it('can mock with custom instance functions over its prototype\'s and restore', function() { + Simple.mock(obj, 'protoFn', function() { return 'y' }) assert.equal(obj.protoFn(), 'y') assert(obj.protoFn.called) - simple.restore() + Simple.restore() assert.equal(obj.protoFn(), 'x') }) - it('can mock with stubbed functions over its prototype\'s and restore', function () { - simple.mock(obj, 'protoFn').returnWith('y') + it('can mock with stubbed functions over its prototype\'s and restore', function() { + Simple.mock(obj, 'protoFn').returnWith('y') assert.equal(obj.protoFn(), 'y') assert(obj.protoFn.called) - simple.restore() + Simple.restore() assert.equal(obj.protoFn(), 'x') }) - it('can mock with stubbed functions and prototype\'s original over its prototype\'s and restore', function () { - simple.mock(obj, 'protoFn').returnWith('y').callOriginal().returnWith('z') + it('can mock with stubbed functions and prototype\'s original over its prototype\'s and restore', function() { + Simple.mock(obj, 'protoFn').returnWith('y').callOriginal().returnWith('z') assert.equal(obj.protoFn(), 'y') assert.equal(obj.protoFn(), 'x') assert.equal(obj.protoFn(), 'z') assert.equal(obj.protoFn.callCount, 3) - simple.restore() + Simple.restore() assert.equal(obj.protoFn(), 'x') }) }) - describe('on an anonymous object', function () { + describe('on an anonymous object', function() { let obj: any - beforeEach(function () { + beforeEach(function() { obj = { a: 'a', b: 'b', c: 'c', - fnD: function () { + fnD: function() { return 'd' } } }) - it('can mock instance values and restore', function () { + it('can mock instance values and restore', function() { let beforeKeys = Object.keys(obj) - simple.mock(obj, 'a', 'd') - simple.mock(obj, 'd', 'a') + Simple.mock(obj, 'a', 'd') + Simple.mock(obj, 'd', 'a') assert.equal(obj.a, 'd') assert.equal(obj.d, 'a') - simple.restore() + Simple.restore() assert.equal(obj.a, 'a') assert.equal(obj.d, undefined) assert.deepEqual(Object.keys(obj), beforeKeys) }) - it('can mock with spy on pre-existing functions and restore', function () { - simple.mock(obj, 'fnD').returnWith('a') + it('can mock with spy on pre-existing functions and restore', function() { + Simple.mock(obj, 'fnD').returnWith('a') assert.equal(obj.fnD(), 'a') assert(obj.fnD.called) - simple.restore() + Simple.restore() assert.equal(obj.fnD(), 'd') }) - it('can mock with newly stubbed functions and restore', function () { - simple.mock(obj, 'fnA').returnWith('a') + it('can mock with newly stubbed functions and restore', function() { + Simple.mock(obj, 'fnA').returnWith('a') assert.equal(obj.fnA(), 'a') assert(obj.fnA.called) - simple.restore() + Simple.restore() assert.equal(obj.fnA, undefined) }) }) - describe('with one argument', function () { - it('returns a spy', function () { + describe('with one argument', function() { + it('returns a spy', function() { let called = 0 - let spy = simple.mock(function () { + let spy = Simple.mock(function() { called++ }) @@ -1007,9 +1007,9 @@ describe('simple', function () { }) }) - describe('with no arguments', function () { - it('returns a stub', function () { - let stub = simple.mock().returnWith('x') + describe('with no arguments', function() { + it('returns a stub', function() { + let stub = Simple.mock().returnWith('x') let x = stub() assert(stub.called) @@ -1019,4 +1019,5 @@ describe('simple', function () { }) }) -simple.Promise = Bluebird; +Simple.Promise = Bluebird; + diff --git a/simplestorage.js/index.d.ts b/simplestorage.js/index.d.ts index 145fffcdcb..9710f42e8c 100644 --- a/simplestorage.js/index.d.ts +++ b/simplestorage.js/index.d.ts @@ -96,9 +96,8 @@ declare namespace simplestoragejs { } -declare module "simplestorage.js" { - export = simpleStorage; -} +export = simpleStorage; +export as namespace simpleStorage; /** * Cross-browser key-value store database to store data locally in the browser. diff --git a/simplestorage.js/simplestorage.js-tests.ts b/simplestorage.js/simplestorage.js-tests.ts index 237910c035..b5405d3775 100644 --- a/simplestorage.js/simplestorage.js-tests.ts +++ b/simplestorage.js/simplestorage.js-tests.ts @@ -1,3 +1,4 @@ +import simpleStorage = require("simplestorage.js") var versionTest: string = simpleStorage.version; var canUseTest: boolean = simpleStorage.canUse(); var simpleStorageTest1: boolean|Error = simpleStorage.set("string", 7); diff --git a/sinon/index.d.ts b/sinon/index.d.ts index 719ed6405c..77de211994 100644 --- a/sinon/index.d.ts +++ b/sinon/index.d.ts @@ -430,6 +430,5 @@ declare namespace Sinon { declare var sinon: Sinon.SinonStatic; -declare module "sinon" { - export = sinon; -} +export = sinon; + diff --git a/sinon/sinon-tests.ts b/sinon/sinon-tests.ts index 2466c75bf1..fa1f313d7b 100644 --- a/sinon/sinon-tests.ts +++ b/sinon/sinon-tests.ts @@ -1,4 +1,4 @@ - +import sinon = require("sinon"); function once(fn: Function) { var returnValue: any, called = false; @@ -110,7 +110,7 @@ testSeven(); testEight(); testNine(); -var clock: Sinon.SinonFakeTimers = sinon.useFakeTimers(); +var clock = sinon.useFakeTimers(); clock.setSystemTime(1000); clock.setSystemTime(new Date()); diff --git a/sjcl/index.d.ts b/sjcl/index.d.ts index e63c7b35b4..875bb6163d 100644 --- a/sjcl/index.d.ts +++ b/sjcl/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Eugene Chernyshov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = sjcl; +export as namespace sjcl; + declare namespace sjcl { export var bn: BigNumberStatic; @@ -554,7 +557,3 @@ declare namespace sjcl { } } } - -declare module "sjcl" { - export = sjcl; -} diff --git a/sjcl/sjcl-tests.ts b/sjcl/sjcl-tests.ts index f9bc0adde1..8b876736ab 100644 --- a/sjcl/sjcl-tests.ts +++ b/sjcl/sjcl-tests.ts @@ -1,4 +1,4 @@ - +import sjcl = require("sjcl"); var b: boolean; var n: number; diff --git a/slideout/index.d.ts b/slideout/index.d.ts index 28c317d0c6..cc358bf190 100644 --- a/slideout/index.d.ts +++ b/slideout/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Markus Peloso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "slideout" { - export = Slideout; -} +export = Slideout; +export as namespace Slideout; declare namespace Slideout { /** diff --git a/slideout/slideout-tests.ts b/slideout/slideout-tests.ts index ed1047e3aa..0c6bdb5798 100644 --- a/slideout/slideout-tests.ts +++ b/slideout/slideout-tests.ts @@ -1,4 +1,4 @@ - +import Slideout = require("slideout"); // Slideout(options) var slideout = new Slideout({ diff --git a/smtpapi/index.d.ts b/smtpapi/index.d.ts index 6d7ca1e0a3..d35f9dbc4c 100644 --- a/smtpapi/index.d.ts +++ b/smtpapi/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Antonio Morales // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var smtp: SmtpApi.Constructor; +export = smtp; + declare namespace SmtpApi { interface Header { @@ -57,8 +60,3 @@ declare namespace SmtpApi { setIpPool(ip_pool: string): void; } } - -declare module 'smtpapi' { - var smtp: SmtpApi.Constructor; - export = smtp; -} diff --git a/socketty/index.d.ts b/socketty/index.d.ts index da7f825071..344312eb50 100644 --- a/socketty/index.d.ts +++ b/socketty/index.d.ts @@ -3,55 +3,57 @@ // Definitions by: Nax // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var socketty: Socketty; +declare var socketty: socketty.Socketty; -declare module 'socketty' { - export = socketty; -} - -interface Socketty { - /** - * Connect to a socketty server. - * @param url The server url - * @param callback The callback to be run when the connection is open - * @return A Socket - */ - connect(url: string, callback: (socket: SockettySocket) => void): SockettySocket; - - /** - * Create a socketty server. - * @param httpServer The HTTP server to use - * @return A socketty server - */ - createServer(httpServer: any): SockettyServer; -} - -interface SockettySocket { - /** - * Listen for an action. - * @param action The action to listen to - * @param callback A callback to be run when the action is fired - */ - on(action: string, callback: (message?: any) => void): void; - - /** - * Send an action, as well as an optional message. - * @param action The action to send - * @param message The message to send - */ - send(action: string, message?: any): void; - - /** - * Specify a callback to be run when the socket is disconnected. - * @param callback The disconnect callback - */ - disconnect(callback: () => void): void; -} - -interface SockettyServer { - /** - * Specify a callback to be run when a new socket connects to the server. - * @param callback The callback - */ - connection(callback: (socket: SockettySocket) => void): void; +export = socketty; +export as namespace socketty; + +declare namespace socketty { + + interface Socketty { + /** + * Connect to a socketty server. + * @param url The server url + * @param callback The callback to be run when the connection is open + * @return A Socket + */ + connect(url: string, callback: (socket: SockettySocket) => void): SockettySocket; + + /** + * Create a socketty server. + * @param httpServer The HTTP server to use + * @return A socketty server + */ + createServer(httpServer: any): SockettyServer; + } + + interface SockettySocket { + /** + * Listen for an action. + * @param action The action to listen to + * @param callback A callback to be run when the action is fired + */ + on(action: string, callback: (message?: any) => void): void; + + /** + * Send an action, as well as an optional message. + * @param action The action to send + * @param message The message to send + */ + send(action: string, message?: any): void; + + /** + * Specify a callback to be run when the socket is disconnected. + * @param callback The disconnect callback + */ + disconnect(callback: () => void): void; + } + + interface SockettyServer { + /** + * Specify a callback to be run when a new socket connects to the server. + * @param callback The callback + */ + connection(callback: (socket: SockettySocket) => void): void; + } } diff --git a/socketty/socketty-tests.ts b/socketty/socketty-tests.ts index b91d568721..09a8ea80f7 100644 --- a/socketty/socketty-tests.ts +++ b/socketty/socketty-tests.ts @@ -1,4 +1,4 @@ - +import socketty = require("socketty"); /* Server */ @@ -6,7 +6,7 @@ var httpServer = {}; // Assume it's a real HTTP server object var webSocketServer = socketty.createServer(httpServer); -webSocketServer.connection((socket: SockettySocket) => { +webSocketServer.connection((socket: socketty.SockettySocket) => { console.log('Client connected'); socket.on('msg', (message?: any) => { console.log('Client said' + message); @@ -18,7 +18,7 @@ webSocketServer.connection((socket: SockettySocket) => { /* Client */ -socketty.connect('ws://localhost:8080', (socket: SockettySocket) => { +socketty.connect('ws://localhost:8080', (socket: socketty.SockettySocket) => { console.log('Connected !'); socket.send('msg', 'Hello server!'); }); diff --git a/sockjs-client/index.d.ts b/sockjs-client/index.d.ts index 87bb0a8501..b5728a3042 100644 --- a/sockjs-client/index.d.ts +++ b/sockjs-client/index.d.ts @@ -46,20 +46,20 @@ declare namespace __SockJSClient { } } -declare module 'sockjs-client' { - import SockJSClass = __SockJSClient.SockJSClass; - import Options = __SockJSClient.Options; - import State = __SockJSClient.State; +import SockJSClass = __SockJSClient.SockJSClass; +import Options = __SockJSClient.Options; +import State = __SockJSClient.State; - var SockJS: { - new(url: string, _reserved?: any, options?: Options): SockJSClass; - (url: string, _reserved?: any, options?: Options): SockJSClass; - prototype: SockJSClass; - CONNECTING: State; - OPEN: State; - CLOSING: State; - CLOSED: State; - }; +declare var SockJS: { + new(url: string, _reserved?: any, options?: Options): SockJSClass; + (url: string, _reserved?: any, options?: Options): SockJSClass; + prototype: SockJSClass; + CONNECTING: State; + OPEN: State; + CLOSING: State; + CLOSED: State; +}; + +export = SockJS; +export as namespace SockJS; - export = SockJS; -} diff --git a/sockjs-client/sockjs-client-tests.ts b/sockjs-client/sockjs-client-tests.ts index ac0ac15418..b7f6b3ab62 100644 --- a/sockjs-client/sockjs-client-tests.ts +++ b/sockjs-client/sockjs-client-tests.ts @@ -1,10 +1,8 @@ import * as SockJS from 'sockjs-client'; -import BaseEvent = __SockJSClient.BaseEvent; -import SockJSClass = __SockJSClient.SockJSClass; -let sockJs: SockJSClass; +let sockJs: any; sockJs = new SockJS('url'); sockJs = SockJS('url'); @@ -18,9 +16,9 @@ sockJs = SockJS('url', null, { transports: ['websocket', 'eventsource'] }); -let listener = (e: BaseEvent) => e; +let listener = (e: any) => e; let listenerObj = { - handleEvent: (e: BaseEvent) => e + handleEvent: (e: any) => e }; sockJs.addEventListener('onopen', listener); @@ -33,9 +31,9 @@ sockJs.removeEventListener('onclose', listener, true); sockJs.removeEventListener('onopen', listenerObj); sockJs.removeEventListener('onclose', listenerObj, true); -sockJs.onopen = e => console.log(e); -sockJs.onmessage = e => console.log(e.data); -sockJs.onclose = e => console.log(e.code, e.reason, e.wasClean); +sockJs.onopen = (e: any) => console.log(e); +sockJs.onmessage = (e: any) => console.log(e.data); +sockJs.onclose = (e: any) => console.log(e.code, e.reason, e.wasClean); let testStates = SockJS.CONNECTING !== -1 && SockJS.OPEN !== -1 && SockJS.CLOSING !== -1 && SockJS.CLOSED !== -1; diff --git a/sortablejs/index.d.ts b/sortablejs/index.d.ts index 87ca56e7c3..4fdc27cd61 100644 --- a/sortablejs/index.d.ts +++ b/sortablejs/index.d.ts @@ -201,8 +201,5 @@ declare namespace Sortablejs { } import Sortable = Sortablejs.Sortable; - -declare module 'sortablejs' { - import Sortable = Sortablejs.Sortable; - export = Sortable; -} +export = Sortable; +export as namespace Sortable; diff --git a/sortablejs/sortablejs-tests.ts b/sortablejs/sortablejs-tests.ts index 1ac43b0c68..73c32ea862 100644 --- a/sortablejs/sortablejs-tests.ts +++ b/sortablejs/sortablejs-tests.ts @@ -1,5 +1,5 @@ // Examples from project repo used for tests. - +import Sortable = require("sortablejs"); var simpleList = document.getElementById('list'); diff --git a/source-map/index.d.ts b/source-map/index.d.ts index cbdccc80d6..eed01d5387 100644 --- a/source-map/index.d.ts +++ b/source-map/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Morten Houston Ludvigsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = SourceMap; +export as namespace sourceMap; + declare namespace SourceMap { interface StartOfSourceMap { file?: string; @@ -84,7 +87,3 @@ declare namespace SourceMap { public toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; } } - -declare module 'source-map' { - export = SourceMap; -} diff --git a/srp/index.d.ts b/srp/index.d.ts index e516a48caa..f13add89ff 100644 --- a/srp/index.d.ts +++ b/srp/index.d.ts @@ -6,6 +6,8 @@ /// /// +export = SRP; + declare namespace SRP { export interface Params { N_length_bits: number; @@ -68,8 +70,4 @@ declare namespace SRP { checkM1(M1: Buffer): Buffer; computeK(): Buffer; } -} - -declare module "srp" { - export = SRP; -} +} \ No newline at end of file diff --git a/steam/index.d.ts b/steam/index.d.ts index 4d5edbed5a..92399d8bc8 100644 --- a/steam/index.d.ts +++ b/steam/index.d.ts @@ -5,6 +5,8 @@ /// +export = Steam; + declare namespace Steam { export var servers: any; @@ -60,7 +62,3 @@ declare namespace Steam { } } -declare module "steam" { - export = Steam; -} - diff --git a/steam/steam-tests.ts b/steam/steam-tests.ts index c8909d2aca..260761719e 100644 --- a/steam/steam-tests.ts +++ b/steam/steam-tests.ts @@ -3,7 +3,7 @@ // Definitions by: Andrey Kurdyumov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +import Steam = require("steam"); var bot = new Steam.SteamClient(); bot.logOn({ diff --git a/string/index.d.ts b/string/index.d.ts index 889197eccc..dbf3120e09 100644 --- a/string/index.d.ts +++ b/string/index.d.ts @@ -122,13 +122,12 @@ interface StringJS { wrapHTML(element?: string, attributes?: Object): StringJS; } -declare module "string" { - var S: { - (o: any): StringJS; - VERSION: string; - TMPL_OPEN: string; - TMPL_CLOSE: string; - } - - export = S; -} \ No newline at end of file +declare var S: { + (o: any): StringJS; + VERSION: string; + TMPL_OPEN: string; + TMPL_CLOSE: string; +} + +export = S; +export as namespace S; diff --git a/stylus/index.d.ts b/stylus/index.d.ts index 9065c15827..836c2b00a9 100644 --- a/stylus/index.d.ts +++ b/stylus/index.d.ts @@ -5,6 +5,9 @@ /// +declare var stylus: Stylus.Static; +export = stylus; + declare namespace Stylus { export interface Static { @@ -1440,8 +1443,3 @@ declare namespace Stylus { //#endregion } - -declare module "stylus" { - var stylus: Stylus.Static; - export = stylus; -} diff --git a/stylus/stylus-tests.ts b/stylus/stylus-tests.ts index 84d2589e7a..4f17d26a9c 100644 --- a/stylus/stylus-tests.ts +++ b/stylus/stylus-tests.ts @@ -89,7 +89,7 @@ stylus(str) * .use(fn) * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#usefn */ -var mylib = function (style: Stylus.Renderer) { +var mylib = function (style: any) { style.define('number', 15.5); style.define('get-list', function () { return ['foo', 'bar', 'baz']; diff --git a/svg-injector/index.d.ts b/svg-injector/index.d.ts index 2fd41caa86..809f983280 100644 --- a/svg-injector/index.d.ts +++ b/svg-injector/index.d.ts @@ -3,41 +3,43 @@ // Definitions by: Patrick Westerhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare interface SVGInjector { - /** - * Replace the given elements with their full inline SVG DOM elements. - * - * @param elements Array of or single DOM element. - * @param options Injector options. - * @param done Callback that receives the injected element count as parameter. - */ - (elements: Node | NodeList | Array, options?: SVGInjectorOptions, done?: (elementCount: number) => void): void; +declare namespace SVGInjector { + interface SVGInjector { + /** + * Replace the given elements with their full inline SVG DOM elements. + * + * @param elements Array of or single DOM element. + * @param options Injector options. + * @param done Callback that receives the injected element count as parameter. + */ + (elements: Node | NodeList | Array, options?: SVGInjectorOptions, done?: (elementCount: number) => void): void; + } + + interface SVGInjectorOptions { + /** + * Whether to run scripts blocks found in the SVG. + * + * Possible values: + * 'always' — Run scripts every time. + * 'once' — Only run scripts once for each SVG. + * 'never' — Ignore scripts (default) + */ + evalScripts?: string; + + /** + * Location of fallback pngs, if desired. + */ + pngFallback?: string; + + /** + * Callback to run during each SVG injection. The SVG element is passed if + * the injection was successful. + */ + each?: (svg: SVGElement | string) => void; + } } -declare interface SVGInjectorOptions { - /** - * Whether to run scripts blocks found in the SVG. - * - * Possible values: - * 'always' — Run scripts every time. - * 'once' — Only run scripts once for each SVG. - * 'never' — Ignore scripts (default) - */ - evalScripts?: string; - /** - * Location of fallback pngs, if desired. - */ - pngFallback?: string; - - /** - * Callback to run during each SVG injection. The SVG element is passed if - * the injection was successful. - */ - each?: (svg: SVGElement | string) => void; -} - -declare module "svg-injector" { - var SVGInjector: SVGInjector; - export = SVGInjector; -} +declare var SVGInjector: SVGInjector.SVGInjector; +export = SVGInjector; +export as namespace SVGInjector; \ No newline at end of file diff --git a/svg-injector/svg-injector-tests.ts b/svg-injector/svg-injector-tests.ts index dfcf3a08be..cec4bbd0b2 100644 --- a/svg-injector/svg-injector-tests.ts +++ b/svg-injector/svg-injector-tests.ts @@ -1,6 +1,6 @@ +import svgInjector = require("svg-injector"); - -var SVGInjector: SVGInjector; +var SVGInjector: svgInjector.SVGInjector; // Simple example var mySVGsToInject = document.querySelectorAll('img.inject-me'); diff --git a/svg2png/index.d.ts b/svg2png/index.d.ts index 25cdb18d1b..326ef4d17c 100644 --- a/svg2png/index.d.ts +++ b/svg2png/index.d.ts @@ -7,6 +7,4 @@ declare function svg2png(srcFile: string, destFile: string, scale: number, cb: ( declare function svg2png(srcFile: string, destFile: string, cb: (err:Error) => void):void; -declare module "svg2png" { - export = svg2png; -} +export = svg2png; diff --git a/swag/index.d.ts b/swag/index.d.ts index b2c69c4871..29ba129fe5 100644 --- a/swag/index.d.ts +++ b/swag/index.d.ts @@ -11,6 +11,6 @@ interface SwagStatic { declare var Swag: SwagStatic; -declare module 'swag' { - export = Swag; -} +export = Swag; +export as namespace Swag; + diff --git a/switchery/index.d.ts b/switchery/index.d.ts index d17802d5b2..5ddaff456f 100644 --- a/switchery/index.d.ts +++ b/switchery/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Bruno Grieder , Clayton Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var switchery: Switchery.SwitcheryStatic; +export default switchery; +export as namespace Switchery; + declare namespace Switchery { interface SwitcheryStatic { @@ -86,8 +90,3 @@ interface Switchery { */ isDisabled(): boolean; } - -declare module "switchery" { - var switchery: Switchery.SwitcheryStatic; - export default switchery; -} diff --git a/systemjs/index.d.ts b/systemjs/index.d.ts index 0128ff5844..7f845c0028 100644 --- a/systemjs/index.d.ts +++ b/systemjs/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: Ludovic HENIN , Nathan Walker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var System: System; + +export = System; +export as namespace System; + interface System { import(name: string): any; defined: any; @@ -14,9 +19,3 @@ interface System { config: any; _nodeRequire: (name: string) => any; } - -declare var System: System; - -declare module "systemjs" { - export = System; -} diff --git a/tabris/index.d.ts b/tabris/index.d.ts index 31a12d05a5..351ae56a7b 100644 --- a/tabris/index.d.ts +++ b/tabris/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Tabris.js team // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = tabris; + declare namespace tabris { // Types @@ -1440,7 +1442,3 @@ declare namespace tabris { export var ui: UI; } - -declare module "tabris" { - export = tabris; -} diff --git a/tabris/tabris-tests.ts b/tabris/tabris-tests.ts index 7a18d7fb0c..c67f71dd5a 100644 --- a/tabris/tabris-tests.ts +++ b/tabris/tabris-tests.ts @@ -1,4 +1,4 @@ - +import tabris = require("tabris"); var page = tabris.create("Page", {}); diff --git a/temp-fs/index.d.ts b/temp-fs/index.d.ts index ae1d0b4a0b..3202d8ab3e 100644 --- a/temp-fs/index.d.ts +++ b/temp-fs/index.d.ts @@ -6,6 +6,8 @@ /** * A temporary file and directory creator. */ +export = tempfs; + declare namespace tempfs { /** @@ -201,11 +203,4 @@ declare namespace tempfs { * and directories will be removed no matter it is on or off. */ function track(on?:Boolean):void; -} - -/** - * A temporary file and directory creator. - */ -declare module "temp-fs" { - export = tempfs; -} +} \ No newline at end of file diff --git a/temp-fs/temp-fs-tests.ts b/temp-fs/temp-fs-tests.ts index ca27dd7b85..c973e553d7 100644 --- a/temp-fs/temp-fs-tests.ts +++ b/temp-fs/temp-fs-tests.ts @@ -1,6 +1,6 @@ // Copied from https://github.com/jakwings/node-temp-fs/blob/60a4d2586a81a7057bd4a395ec8c00b4100f84fe/README.md // and slightly modified. - +import tempfs = require("temp-fs"); // Create a tempfile in the system-provided tempdir. diff --git a/tether/index.d.ts b/tether/index.d.ts index 50d7a8bad2..ae00278d9b 100644 --- a/tether/index.d.ts +++ b/tether/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Adi Dahiya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Tether; +export as namespace Tether; + // global Tether constructor declare class Tether { constructor(options: Tether.ITetherOptions); @@ -40,8 +43,3 @@ declare namespace Tether { to?: string | HTMLElement | number[]; } } - -declare module "tether" { - export = Tether; -} - diff --git a/tether/tether-tests.ts b/tether/tether-tests.ts index e00990055f..5f78bb3b99 100644 --- a/tether/tether-tests.ts +++ b/tether/tether-tests.ts @@ -1,4 +1,5 @@ /// +import Tether = require("tether"); var yellowBox = document.querySelector(".yellow"); var greenBox = document.querySelector(".green"); diff --git a/traverson/index.d.ts b/traverson/index.d.ts index 687d3ebc84..8028a172ec 100644 --- a/traverson/index.d.ts +++ b/traverson/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Marcin Porębski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var traverson: Traverson.TraversonMethods; + +export = traverson; + declare namespace Traverson { interface TraversonMethods @@ -51,10 +55,3 @@ declare namespace Traverson } - -declare module "traverson" -{ - var traverson: Traverson.TraversonMethods; - - export = traverson; -} diff --git a/turf/index.d.ts b/turf/index.d.ts index 8b7f1eab3b..03eccd7641 100644 --- a/turf/index.d.ts +++ b/turf/index.d.ts @@ -5,6 +5,9 @@ /// +export= turf; +export as namespace turf; + declare namespace turf { ////////////////////////////////////////////////////// // Aggregation @@ -574,7 +577,3 @@ declare namespace turf { */ function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; } - -declare module 'turf' { - export= turf; -} diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index 1737de1870..e2c8fbeb6b 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -2,6 +2,8 @@ // Tests data initialisation /////////////////////////////////////////// +import turf = require("turf"); + var point1 = { "type": "Feature", "properties": {}, diff --git a/tv4/index.d.ts b/tv4/index.d.ts index 9171b953d7..52b4121c67 100644 --- a/tv4/index.d.ts +++ b/tv4/index.d.ts @@ -97,7 +97,6 @@ declare namespace tv4 { } } -declare module "tv4" { - var out: tv4.TV4 - export = out; -} +declare var tv4: tv4.TV4; +export = tv4; +export as namespace tv4; diff --git a/tv4/tv4-tests.ts b/tv4/tv4-tests.ts index 4d3d46aecc..f1cf61171c 100644 --- a/tv4/tv4-tests.ts +++ b/tv4/tv4-tests.ts @@ -1,3 +1,4 @@ +import tv4 = require("tv4"); var str:string; var strArr:string[]; var bool:boolean; diff --git a/type-name/index.d.ts b/type-name/index.d.ts index e09dab022e..1e6f7aa7cf 100644 --- a/type-name/index.d.ts +++ b/type-name/index.d.ts @@ -6,6 +6,6 @@ declare function typeName(anyVar: any): string; declare namespace typeName {} -declare module "type-name" { - export = typeName; -} +export = typeName; +export as namespace typeName; + \ No newline at end of file diff --git a/ua-parser-js/index.d.ts b/ua-parser-js/index.d.ts index be212a7ba2..aaf86d7596 100644 --- a/ua-parser-js/index.d.ts +++ b/ua-parser-js/index.d.ts @@ -3,6 +3,61 @@ // Definitions by: Viktor Miroshnikov , Lucas Woo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export class UAParser { + static VERSION: string; + static BROWSER: UAParser.BROWSER; + static CPU: UAParser.CPU; + static DEVICE: UAParser.DEVICE; + static ENGINE: UAParser.ENGINE; + static OS: UAParser.OS; + + /** + * Returns browser information + */ + getBrowser(): UAParser.IBrowser; + /** + * Returns OS information + */ + getOS(): UAParser.IOS; + + /** + * Returns browsers engine information + */ + getEngine(): UAParser.IEngine; + + /** + * Returns device information + */ + getDevice(): UAParser.IDevice; + + /** + * Returns parsed CPU information + */ + getCPU(): UAParser.ICPU; + + /** + * Returns UA string of current instance + */ + getUA(): string; + + /** + * Set & parse UA string + */ + setUA(uastring: string): UAParser; + + /** + * Returns parse result + */ + getResult(): UAParser.IResult; + + /** + * Create a new parser with UA prepopulated and extensions extended + */ + constructor(uastring?: string, extensions?: any); +} +export as namespace UAParser; + + declare namespace UAParser { export interface IBrowser { @@ -131,60 +186,3 @@ declare namespace UAParser { } } - -declare module "ua-parser-js" { - - export class UAParser { - static VERSION: string; - static BROWSER: UAParser.BROWSER; - static CPU: UAParser.CPU; - static DEVICE: UAParser.DEVICE; - static ENGINE: UAParser.ENGINE; - static OS: UAParser.OS; - - /** - * Returns browser information - */ - getBrowser(): UAParser.IBrowser; - /** - * Returns OS information - */ - getOS(): UAParser.IOS; - - /** - * Returns browsers engine information - */ - getEngine(): UAParser.IEngine; - - /** - * Returns device information - */ - getDevice(): UAParser.IDevice; - - /** - * Returns parsed CPU information - */ - getCPU(): UAParser.ICPU; - - /** - * Returns UA string of current instance - */ - getUA(): string; - - /** - * Set & parse UA string - */ - setUA(uastring: string): UAParser; - - /** - * Returns parse result - */ - getResult(): UAParser.IResult; - - /** - * Create a new parser with UA prepopulated and extensions extended - */ - constructor(uastring?: string, extensions?: any); - } - -} diff --git a/ui-grid/index.d.ts b/ui-grid/index.d.ts index 75673a983b..5c7fa7ff54 100644 --- a/ui-grid/index.d.ts +++ b/ui-grid/index.d.ts @@ -17,6 +17,9 @@ /// /// +export = uiGrid; +export as namespace uiGrid; + declare namespace uiGrid { export interface IUiGridConstants { LOG_DEBUG_MESSAGES: boolean; @@ -3891,7 +3894,3 @@ declare namespace uiGrid { caseSensitive?: boolean; } } - -declare module 'angular-ui-grid' { - export = uiGrid; -} diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 83f2ce2789..4e4b56064d 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -1,4 +1,4 @@ - +import uiGrid = require("ui-grid"); /// interface IMyEntity { diff --git a/ui-router-extras/index.d.ts b/ui-router-extras/index.d.ts index 675c37f6e1..37b06fc9a4 100644 --- a/ui-router-extras/index.d.ts +++ b/ui-router-extras/index.d.ts @@ -5,147 +5,147 @@ /// -// Support for AMD require -declare module 'angular-ui-router-extras' { - var _: string; - export = _; -} +import * as angular from 'angularjs'; -declare namespace angular.ui { +declare module 'angularjs' { + export namespace ui { - /* - * $deepStateRedirect - */ - interface IDeepStateRedirectService { /* - * This method resets stored $deepStateRedirect data so following transitions will behave like there have not been previous transitions. - * @param stateParams Can be passed in to select specific states to reset: - * { - * 'paramName': 'paramvalue' | ['list', 'of', 'possible', 'paramvalues'] - * } + * $deepStateRedirect */ - reset(stateName: string, stateParams?: { [key: string]: string | string[] }): void; - } + interface IDeepStateRedirectService { + /* + * This method resets stored $deepStateRedirect data so following transitions will behave like there have not been previous transitions. + * @param stateParams Can be passed in to select specific states to reset: + * { + * 'paramName': 'paramvalue' | ['list', 'of', 'possible', 'paramvalues'] + * } + */ + reset(stateName: string, stateParams?: { [key: string]: string | string[] }): void; + } - /* - * Docs: http://christopherthielen.github.io/ui-router-extras/#/dsr - */ - interface IDeepStateRedirectConfig { /* - * If no deep state has been recorded, DSR will instead redirect to the default substate and params that you specify. - * If default is a string it is interpreted as the substate. - */ - default?: string | IRedirectParams; - /* - * Specify params: true if your DSR state takes parameters. - * If only a subset of the parameters should be included in the parameter grouping for recording deep states, - * specify an array of parameter names. - */ - params?: boolean | string[]; - /* - * A callback function that determines whether or not the redirect should actually occur, or changes the redirect to some other state. - * Return an object: IRedirectParams to change the redirect - */ - fn?($dsr$: { redirect: IRedirectParams; to: IRedirectParams }): boolean | IRedirectParams; - } - - interface IRedirectParams { - state: string; - params?: ui.IStateParamsService; - } - - /* - * Previous state - */ - interface IPreviousState { - state: IState; - params?: ui.IStateParamsService; - } - - /** - * Previous state service - */ - interface IPreviousStateService { - - /** - * Get a previous state - * @param memoName Memo name - * @return Previous state - */ - get(memoName?: string): IPreviousState; - - /** - * Go to a state - * @param memoName Memo name - * @param options State options - * @return Promise - */ - go(memoName: string, options?: IStateOptions): angular.IPromise; - - /** - * Memorize a state - * @param memoName Memo name - * @param defaultStateName Default state name - * @param defaultStateParams Default state parameters - */ - memo(memoName: string, defaultStateName?: string, defaultStateParams?: {}): void; - - /** - * Forget a memorized name - * @param memoName Memo name - */ - forget(memoName: string): void; - } - - /** - * Sticky state - */ - interface IStickyState extends angular.ui.IState { - /* - * When marking a state sticky, the state must target its own unique named ui-view. - * Docs: http://christopherthielen.github.io/ui-router-extras/#/sticky - */ - sticky?: boolean; - /* - * The most-recently-activate substate of the DSR marked state is remembered. - * When the DSR marked state is transitioned to directly, UI-Router Extras will instead redirect to the remembered state and parameters. * Docs: http://christopherthielen.github.io/ui-router-extras/#/dsr */ - deepStateRedirect?: boolean | IDeepStateRedirectConfig; + interface IDeepStateRedirectConfig { + /* + * If no deep state has been recorded, DSR will instead redirect to the default substate and params that you specify. + * If default is a string it is interpreted as the substate. + */ + default?: string | IRedirectParams; + /* + * Specify params: true if your DSR state takes parameters. + * If only a subset of the parameters should be included in the parameter grouping for recording deep states, + * specify an array of parameter names. + */ + params?: boolean | string[]; + /* + * A callback function that determines whether or not the redirect should actually occur, or changes the redirect to some other state. + * Return an object: IRedirectParams to change the redirect + */ + fn?($dsr$: { redirect: IRedirectParams; to: IRedirectParams }): boolean | IRedirectParams; + } + + interface IRedirectParams { + state: string; + params?: ui.IStateParamsService; + } + /* - * Shortname deepStateRedirect prop + * Previous state */ - dsr?: boolean | IDeepStateRedirectConfig; - /* - * Function (injectable). Called when a sticky state is navigated away from (inactivated). + interface IPreviousState { + state: IState; + params?: ui.IStateParamsService; + } + + /** + * Previous state service */ - onInactivate?: Function; - /* - * Function (injectable). Called when an inactive sticky state is navigated to (reactivated). + interface IPreviousStateService { + + /** + * Get a previous state + * @param memoName Memo name + * @return Previous state + */ + get(memoName?: string): IPreviousState; + + /** + * Go to a state + * @param memoName Memo name + * @param options State options + * @return Promise + */ + go(memoName: string, options?: IStateOptions): angular.IPromise; + + /** + * Memorize a state + * @param memoName Memo name + * @param defaultStateName Default state name + * @param defaultStateParams Default state parameters + */ + memo(memoName: string, defaultStateName?: string, defaultStateParams?: {}): void; + + /** + * Forget a memorized name + * @param memoName Memo name + */ + forget(memoName: string): void; + } + + /** + * Sticky state + */ + interface IStickyState extends angular.ui.IState { + /* + * When marking a state sticky, the state must target its own unique named ui-view. + * Docs: http://christopherthielen.github.io/ui-router-extras/#/sticky + */ + sticky?: boolean; + /* + * The most-recently-activate substate of the DSR marked state is remembered. + * When the DSR marked state is transitioned to directly, UI-Router Extras will instead redirect to the remembered state and parameters. + * Docs: http://christopherthielen.github.io/ui-router-extras/#/dsr + */ + deepStateRedirect?: boolean | IDeepStateRedirectConfig; + /* + * Shortname deepStateRedirect prop + */ + dsr?: boolean | IDeepStateRedirectConfig; + /* + * Function (injectable). Called when a sticky state is navigated away from (inactivated). + */ + onInactivate?: Function; + /* + * Function (injectable). Called when an inactive sticky state is navigated to (reactivated). + */ + onReactivate?: Function; + /* + * Note: named views are mandatory when using sticky states! + */ + views?: { [name:string]: angular.ui.IState }; + } + + + /** + * Sticky state service */ - onReactivate?: Function; - /* - * Note: named views are mandatory when using sticky states! + interface IStickyStateService { + getInactiveStates(): IStickyState[]; + } + + /** + * Sticky state provider */ - views?: { [name:string]: angular.ui.IState }; + interface IStickyStateProvider extends angular.IServiceProvider { + debugMode(): boolean; + enableDebug(enabled: boolean): boolean; + registerStickyState(state: IStickyState): void; + } + } - - - /** - * Sticky state service - */ - interface IStickyStateService { - getInactiveStates(): IStickyState[]; - } - - /** - * Sticky state provider - */ - interface IStickyStateProvider extends angular.IServiceProvider { - debugMode(): boolean; - enableDebug(enabled: boolean): boolean; - registerStickyState(state: IStickyState): void; - } - } + + diff --git a/ui-router-extras/ui-router-extras-tests.ts b/ui-router-extras/ui-router-extras-tests.ts index 290ef37dad..db6f69d486 100644 --- a/ui-router-extras/ui-router-extras-tests.ts +++ b/ui-router-extras/ui-router-extras-tests.ts @@ -1,3 +1,4 @@ +import * as angular from 'angularjs'; var myApp = angular.module('testModule') myApp.config(($stateProvider: angular.ui.IStateProvider, $stickyStateProvider: angular.ui.IStickyStateProvider) => { diff --git a/ui-select/index.d.ts b/ui-select/index.d.ts index 1d3846ec53..6e4cad78a7 100644 --- a/ui-select/index.d.ts +++ b/ui-select/index.d.ts @@ -5,15 +5,14 @@ /// -declare module "ui-select" { - var _: string; - export = _; -} +import * as angular from 'angularjs'; -declare namespace angular.ui.select { - interface ISelectConfig { - appendToBody: boolean; - resetSearchInput: boolean; - theme: string; - } -} +declare module 'angularjs' { + export namespace ui.select { + interface ISelectConfig { + appendToBody: boolean; + resetSearchInput: boolean; + theme: string; + } + } +} \ No newline at end of file diff --git a/ui-select/ui-select-tests.ts b/ui-select/ui-select-tests.ts index c7a8d6c93d..6bb9e3de80 100644 --- a/ui-select/ui-select-tests.ts +++ b/ui-select/ui-select-tests.ts @@ -1,4 +1,4 @@ - +import * as angular from 'angularjs'; angular .module('main', ['ui-select']) diff --git a/universal-analytics/index.d.ts b/universal-analytics/index.d.ts index f1e1490121..3642d1558d 100644 --- a/universal-analytics/index.d.ts +++ b/universal-analytics/index.d.ts @@ -7,6 +7,8 @@ interface UniversalAnalytics { (accountID:string, uuid?:string, opts?:Object):UniversalAnalytics.Client; } +export = UniversalAnalytics; + declare namespace UniversalAnalytics { interface Client { @@ -88,7 +90,3 @@ declare namespace UniversalAnalytics { middleware(accountID:string, options?:any):any; } } - -declare module 'universal-analytics' { -export = UniversalAnalytics; -} diff --git a/universal-analytics/universal-analytics-tests.ts b/universal-analytics/universal-analytics-tests.ts index e33118b759..1f37e27a66 100644 --- a/universal-analytics/universal-analytics-tests.ts +++ b/universal-analytics/universal-analytics-tests.ts @@ -1,4 +1,4 @@ - +import UniversalAnalytics = require("universal-analytics"); var ui:UniversalAnalytics; diff --git a/unorm/index.d.ts b/unorm/index.d.ts index cd9a9a6a06..a4fbde61c6 100644 --- a/unorm/index.d.ts +++ b/unorm/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: Christopher Brown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var unorm: unorm.Static; +export = unorm; +export as namespace unorm; + declare namespace unorm { interface Static { nfd(str: string): string; @@ -10,10 +15,4 @@ declare namespace unorm { nfc(str: string): string; nfkc(str: string): string; } -} - -declare var unorm: unorm.Static; - -declare module "unorm" { - export = unorm; -} +} \ No newline at end of file diff --git a/url-template/index.d.ts b/url-template/index.d.ts index 14b3ece407..5f3d896002 100644 --- a/url-template/index.d.ts +++ b/url-template/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: Marcin Porębski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var urlTemplate: UrlTemplate.TemplateParser; + +export = urlTemplate; +export as namespace urltemplate; + declare namespace UrlTemplate { interface TemplateParser { @@ -14,11 +19,4 @@ declare namespace UrlTemplate } } -declare module "url-template" -{ - var urlTemplate: UrlTemplate.TemplateParser; - - export = urlTemplate; -} - diff --git a/vex-js/index.d.ts b/vex-js/index.d.ts index 40c2621ccb..ffd1d04dbf 100644 --- a/vex-js/index.d.ts +++ b/vex-js/index.d.ts @@ -5,6 +5,9 @@ /// +export = vex; +export as namespace vex; + declare namespace vex { interface ICSSAttributes { @@ -38,8 +41,4 @@ declare namespace vex { } -declare module "vex" { - export = vex; -} - declare var vex: vex.Vex; diff --git a/vex-js/vex-tests.ts b/vex-js/vex-tests.ts index b3a76a8650..d4af6e9e6a 100644 --- a/vex-js/vex-tests.ts +++ b/vex-js/vex-tests.ts @@ -1,4 +1,5 @@ /// +import vex = require("vex-js"); var vexContent = vex.open({ afterClose: (() => null), diff --git a/voximplant-websdk/index.d.ts b/voximplant-websdk/index.d.ts index fb92f77b3f..c292338743 100644 --- a/voximplant-websdk/index.d.ts +++ b/voximplant-websdk/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Alexey Aylarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = VoxImplant; +export as namespace VoxImplant; + declare namespace VoxImplant { /** @@ -2031,7 +2034,3 @@ declare namespace VoxImplant { function version(): String; } - -declare module "voximplant-websdk" { - export = VoxImplant; -} diff --git a/voximplant-websdk/voximplant-websdk-tests.ts b/voximplant-websdk/voximplant-websdk-tests.ts index ea06007a8b..76b15f789d 100644 --- a/voximplant-websdk/voximplant-websdk-tests.ts +++ b/voximplant-websdk/voximplant-websdk-tests.ts @@ -1,3 +1,4 @@ +import VoxImplant = require("voximplant-websdk"); var vox: VoxImplant.Client = VoxImplant.getInstance(), call: VoxImplant.Call, room: string; diff --git a/wake_on_lan/index.d.ts b/wake_on_lan/index.d.ts index d0f4aaeb1c..22358c02b1 100644 --- a/wake_on_lan/index.d.ts +++ b/wake_on_lan/index.d.ts @@ -5,6 +5,9 @@ /// +declare var wol: wol.Wol; +export = wol; + declare namespace wol { export interface WakeOptions { @@ -66,8 +69,3 @@ declare namespace wol { createMagicPacket(macAddress:string):Buffer; } } - -declare module 'wake_on_lan' { - var wol: wol.Wol; - export = wol; -} diff --git a/webfontloader/index.d.ts b/webfontloader/index.d.ts index 1d67516d4b..44e43a0811 100644 --- a/webfontloader/index.d.ts +++ b/webfontloader/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: doskallemaskin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = WebFont; +export as namespace WebFont; + declare namespace WebFont { export function load(config:WebFont.Config):void; export interface Config { @@ -55,6 +58,3 @@ declare namespace WebFont { } } -declare module "webfontloader" { - export = WebFont; -} diff --git a/webtorrent/index.d.ts b/webtorrent/index.d.ts index 32bf1911ab..b6e55823f5 100644 --- a/webtorrent/index.d.ts +++ b/webtorrent/index.d.ts @@ -6,6 +6,10 @@ /// /// +declare var webTorrentStatic:WebTorrent.ClientConstructor; +export = webTorrentStatic; +export as namespace WebTorrent; + declare namespace WebTorrent { export interface ClientOptions { dht?: boolean|Object, // Enable DHT (default=true), or options object for DHT @@ -333,8 +337,3 @@ declare namespace WebTorrent { on(event: 'done', callback:()=>void): this; } } - -declare module "webtorrent" { - const webTorrentStatic:WebTorrent.ClientConstructor; - export = webTorrentStatic; -} diff --git a/windows-1251/index.d.ts b/windows-1251/index.d.ts index 48883637bd..0a90439090 100644 --- a/windows-1251/index.d.ts +++ b/windows-1251/index.d.ts @@ -2,6 +2,17 @@ // Project: https://github.com/mathiasbynens/windows-1251 // Definitions by: RomanGolovanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var windows1251: { + encode(input:string, options?:{ mode?: windows1251.EncoderMode }):string; + decode(text: string, options?:{ mode?: windows1251.DecoderMode }): string; + version: string; + labels: string[]; +} + +export = windows1251; +export as namespace windows1251; + declare namespace windows1251 { type EncoderMode = 'fatal' | 'html'; @@ -13,14 +24,3 @@ declare namespace windows1251 { } } - -declare module 'windows-1251' { - var windows1251: { - encode(input:string, options?:{ mode?: windows1251.EncoderMode }):string; - decode(text: string, options?:{ mode?: windows1251.DecoderMode }): string; - version: string; - labels: string[]; - } - - export = windows1251; -} diff --git a/wolfy87-eventemitter/index.d.ts b/wolfy87-eventemitter/index.d.ts index 45c4e54e5d..8e5b8a6ace 100644 --- a/wolfy87-eventemitter/index.d.ts +++ b/wolfy87-eventemitter/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: ryiwamoto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare class EventEmitter extends Wolfy87EventEmitter.EventEmitter {} +export = EventEmitter; +export as namespace EventEmitter; + declare namespace Wolfy87EventEmitter { /** @@ -504,10 +508,5 @@ declare namespace Wolfy87EventEmitter { } } -declare module "wolfy87-eventemitter" { - class EventEmitter extends Wolfy87EventEmitter.EventEmitter {} - export = EventEmitter; -} - //declare var EventEmitter: typeof Wolfy87EventEmitter.EventEmitter; diff --git a/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts b/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts index 15fb0e2a57..a2e75ed746 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts @@ -21,39 +21,39 @@ function testGetListenersAsObject() { } function testAddListener() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .addListener("foo", listener) .addListener(/^foo/, listener); } function testOn() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .on("foo", listener) .on(/^foo/, listener); } function testAddOnceListener() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .addOnceListener("foo", listener) .addOnceListener(/^foo/, listener); } function testOnce() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .once("foo", listener) .once(/^foo/, listener); } function testDefineEvent() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.defineEvent("foo"); + var e = emitter.defineEvent("foo"); } function testDefineEvents() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.defineEvents(["foo", "bar"]); + var e = emitter.defineEvents(["foo", "bar"]); } function testAddListeners() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .addListeners("foo", [listener]) .addListeners({ "foo": listener, @@ -62,7 +62,7 @@ function testAddListeners() { } function testRemoveListeners() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .removeListeners("foo", [listener]) .removeListeners({ "foo": listener, @@ -71,11 +71,11 @@ function testRemoveListeners() { } function testRemoveListener() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.removeListener("foo", listener); + var e = emitter.removeListener("foo", listener); } function testManipulateListeners() { - var e: Wolfy87EventEmitter.EventEmitter = emitter + var e = emitter .manipulateListeners(true, "foo", [listener]) .manipulateListeners(true, { "foo": listener @@ -83,27 +83,27 @@ function testManipulateListeners() { } function testRemoveEvent() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.removeEvent("foo").removeEvent(); + var e = emitter.removeEvent("foo").removeEvent(); } function testEmitEvent() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.emitEvent("foo", ["arg1", "arg2"]).emitEvent("foo"); + var e = emitter.emitEvent("foo", ["arg1", "arg2"]).emitEvent("foo"); } function testTrigger() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.trigger("foo", ["arg1", "arg2"]).trigger("foo"); + var e = emitter.trigger("foo", ["arg1", "arg2"]).trigger("foo"); } function testEmit() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.emit("foo", ["arg1", "arg2"]).emit("foo"); + var e = emitter.emit("foo", ["arg1", "arg2"]).emit("foo"); } function testSetOnceReturnValue() { - var e: Wolfy87EventEmitter.EventEmitter = emitter.setOnceReturnValue(false); + var e = emitter.setOnceReturnValue(false); } function testNoConflict() { var NoConflictEventEmitter = EventEmitter.noConflict(); - var e: Wolfy87EventEmitter.EventEmitter = new NoConflictEventEmitter(); + var e = new NoConflictEventEmitter(); } diff --git a/wrap-ansi/index.d.ts b/wrap-ansi/index.d.ts index 79a63abc78..fcbdd756e2 100644 --- a/wrap-ansi/index.d.ts +++ b/wrap-ansi/index.d.ts @@ -3,18 +3,18 @@ // Definitions by: Klaus Reimer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "wrap-ansi" { - /** - * Wrap words to the specified column width. - * - * @param input String with ANSI escape codes. Like one styled by chalk. - * @param columns Number of columns to wrap the text to. - * @param options By default the wrap is soft, meaning long words may extend past the column width. Setting - * this to true will make it hard wrap at the column width. - */ - function wrapAnsi(input: string, columns: number, options?: { hard?: boolean }): string; - namespace wrapAnsi {} +/** + * Wrap words to the specified column width. + * + * @param input String with ANSI escape codes. Like one styled by chalk. + * @param columns Number of columns to wrap the text to. + * @param options By default the wrap is soft, meaning long words may extend past the column width. Setting + * this to true will make it hard wrap at the column width. + */ +declare function wrapAnsi(input: string, columns: number, options?: { hard?: boolean }): string; + +declare namespace wrapAnsi {} + +export = wrapAnsi; - export = wrapAnsi; -} diff --git a/yeoman-generator/index.d.ts b/yeoman-generator/index.d.ts index 4ab6f14d0b..a42e08be46 100644 --- a/yeoman-generator/index.d.ts +++ b/yeoman-generator/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export = yo; + declare namespace yo { export interface IYeomanGenerator { argument(name: string, config: IArgumentConfig): void; @@ -244,7 +246,3 @@ declare namespace yo { static extend(protoProps: IQueueProps, staticProps?: any): IYeomanGenerator; } } - -declare module "yeoman-generator" { - export = yo; -} diff --git a/z-schema/index.d.ts b/z-schema/index.d.ts index 83f43bc064..1514949351 100644 --- a/z-schema/index.d.ts +++ b/z-schema/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Adam Meadows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = ZSchema.Validator; +export as namespace ZSchema; + declare namespace ZSchema { export interface Options { @@ -55,8 +58,4 @@ declare namespace ZSchema { getLastError(): SchemaError; getLastErrors(): SchemaError[]; } -} - -declare module "z-schema" { - export = ZSchema.Validator; -} +} \ No newline at end of file diff --git a/z-schema/z-schema-tests.ts b/z-schema/z-schema-tests.ts index 4caee35252..c82d19c5f7 100644 --- a/z-schema/z-schema-tests.ts +++ b/z-schema/z-schema-tests.ts @@ -2,12 +2,12 @@ import ZSchema = require('z-schema'); -var options: ZSchema.Options = { +var options = { noTypeless: true, forceItems: true, }; -var validator: ZSchema.Validator = new ZSchema(options); +var validator = new ZSchema(options); var json: any = { foo: 'bar', }; @@ -30,5 +30,5 @@ validator.validate(json, schema, function (err: any, valid: boolean) { } }); -var error: ZSchema.SchemaError = validator.getLastError(); -var errors: ZSchema.SchemaError[] = validator.getLastErrors(); +var error = validator.getLastError(); +var errors = validator.getLastErrors(); diff --git a/zmq/index.d.ts b/zmq/index.d.ts index c977864ada..d39fa76146 100644 --- a/zmq/index.d.ts +++ b/zmq/index.d.ts @@ -7,212 +7,208 @@ interface EventEmitter {} -declare module 'zmq' { +interface SocketTypes { + pub: number; + xpub: number; + sub: number; + xsub: number; + req: number; + xreq: number; + rep: number; + xrep: number; + push: number; + pull: number; + dealer: number; + router: number; + pair: number; +} - interface SocketTypes { - pub: number; - xpub: number; - sub: number; - xsub: number; - req: number; - xreq: number; - rep: number; - xrep: number; - push: number; - pull: number; - dealer: number; - router: number; - pair: number; - } +interface SocketOptions { + _fd: number; + _ioevents: number; + _receiveMore: number; + _subscribe: number; + _unsubscribe: number; + affinity: number; + backlog: number; + hwm: number; + identity: number; + linger: number; + mcast_loop: number; + rate: number; + rcvbuf: number; + last_endpoint: number; + reconnect_ivl: number; + recovery_ivl: number; + sndbuf: number; + swap: number; +} - interface SocketOptions { - _fd: number; - _ioevents: number; - _receiveMore: number; - _subscribe: number; - _unsubscribe: number; - affinity: number; - backlog: number; - hwm: number; - identity: number; - linger: number; - mcast_loop: number; - rate: number; - rcvbuf: number; - last_endpoint: number; - reconnect_ivl: number; - recovery_ivl: number; - sndbuf: number; - swap: number; - } +interface Socket extends EventEmitter { + /** + * Set `opt` to `val`. + * + * @param opt Option + * @param val Value + */ + setsocketopt(opt: number, val: any): Socket; - interface Socket extends EventEmitter { - /** - * Set `opt` to `val`. - * - * @param opt Option - * @param val Value - */ - setsocketopt(opt: number, val: any): Socket; + /** + * Set `opt` to `val`. + * + * @param opt Option + * @param val Value + */ + setsocketopt(opt: string, val: any): Socket; - /** - * Set `opt` to `val`. - * - * @param opt Option - * @param val Value - */ - setsocketopt(opt: string, val: any): Socket; + /** + * Get socket `opt`. + * + * @param opt Option number + */ + getsocketopt(opt: number): any; - /** - * Get socket `opt`. - * - * @param opt Option number - */ - getsocketopt(opt: number): any; + /** + * Get socket `opt`. + * + * @param opt Option string + */ + getsocketopt(opt: string): any; - /** - * Get socket `opt`. - * - * @param opt Option string - */ - getsocketopt(opt: string): any; + /** + * Async bind. + * + * Emits the "bind" event. + * + * @param addr Socket address + * @param cb Bind callback + */ + bind(addr: string, callback?: (error: string) => void ): Socket; - /** - * Async bind. - * - * Emits the "bind" event. - * - * @param addr Socket address - * @param cb Bind callback - */ - bind(addr: string, callback?: (error: string) => void ): Socket; + /** + * Sync bind. + * + * @param addr Socket address + */ + bindSync(addr: string): Socket; - /** - * Sync bind. - * - * @param addr Socket address - */ - bindSync(addr: string): Socket; + /** + * Async unbind. + * + * Emits the "unbind" event. + * + * @param addr Socket address + * @param cb Unind callback + */ + unbind(addr: string, callback?: (error: string) => void ): Socket; - /** - * Async unbind. - * - * Emits the "unbind" event. - * - * @param addr Socket address - * @param cb Unind callback - */ - unbind(addr: string, callback?: (error: string) => void ): Socket; + /** + * Sync unbind. + * + * @param addr Socket address + */ + unbindSync(addr: string): Socket; - /** - * Sync unbind. - * - * @param addr Socket address - */ - unbindSync(addr: string): Socket; + /** + * Connect to `addr`. + * + * @param addr Connection address + */ + connect(addr: string): Socket; - /** - * Connect to `addr`. - * - * @param addr Connection address - */ - connect(addr: string): Socket; + /** + * Disconnect from `addr`. + * + * @param addr The address + */ + disconnect(addr: string): Socket; - /** - * Disconnect from `addr`. - * - * @param addr The address - */ - disconnect(addr: string): Socket; + /** + * Subscribe with the given `filter`. + * + * @param filter The filter + */ + subscribe(filter: string): Socket; - /** - * Subscribe with the given `filter`. - * - * @param filter The filter - */ - subscribe(filter: string): Socket; + /** + * Unsubscribe with the given `filter`. + * + * @param filter The filter + */ + unsubscribe(filter: string): Socket; - /** - * Unsubscribe with the given `filter`. - * - * @param filter The filter - */ - unsubscribe(filter: string): Socket; + /** + * Send the given `msg`. + * + * @param msg The message + * @param flags Message flags + */ + send(msg: string, flags?: number): Socket; - /** - * Send the given `msg`. - * - * @param msg The message - * @param flags Message flags - */ - send(msg: string, flags?: number): Socket; + /** + * Send the given `msg`. + * + * @param msg {Buffer} The message + * @param flags {number} Optional message flags + */ + send(msg: Buffer, flags?: number): Socket; - /** - * Send the given `msg`. - * - * @param msg {Buffer} The message - * @param flags {number} Optional message flags - */ - send(msg: Buffer, flags?: number): Socket; + /** + * Send the given `msg`. + * + * @param msg The message + * @param flags Message flags + */ + send(msg: any[], flags?: number): Socket; - /** - * Send the given `msg`. - * - * @param msg The message - * @param flags Message flags - */ - send(msg: any[], flags?: number): Socket; + /** + * Enable monitoring of a Socket + * + * @param {Number} timer interval in ms > 0 or Undefined for default + * @return {Socket} for chaining + */ + monitor(interval?: number): Socket; - /** - * Enable monitoring of a Socket - * - * @param {Number} timer interval in ms > 0 or Undefined for default - * @return {Socket} for chaining - */ - monitor(interval?: number): Socket; + /** + * Close the socket. + * + */ + close(): Socket; - /** - * Close the socket. - * - */ - close(): Socket; + /** + * Socket event + * @param eventName {string} + * @param callback {Function} + */ + on(eventName: string, callback: (...buffer: Buffer[]) => void): void; - /** - * Socket event - * @param eventName {string} - * @param callback {Function} - */ - on(eventName: string, callback: (...buffer: Buffer[]) => void): void; + // Socket Options + _fd: any; + _ioevents: any; + _receiveMore: any; + _subscribe: any; + _unsubscribe: any; + affinity: any; + backlog(): any; + hwm: any; + identity: any; + linger: any; + mcast_loop: any; + rate: any; + rcvbuf: any; + last_endpoint: any; + reconnect_ivl: any; + recovery_ivl: any; + sndbuf: any; + swap: any; - // Socket Options - _fd: any; - _ioevents: any; - _receiveMore: any; - _subscribe: any; - _unsubscribe: any; - affinity: any; - backlog(): any; - hwm: any; - identity: any; - linger: any; - mcast_loop: any; - rate: any; - rcvbuf: any; - last_endpoint: any; - reconnect_ivl: any; - recovery_ivl: any; - sndbuf: any; - swap: any; - - - } - - export var version: string; - export var types: SocketTypes; - export var options: SocketOptions; - - function socket(type: string, options?: any): Socket; - function socket(type: number, options?: any): Socket; - function createSocket(type: string, options?: any): Socket; } + +export var version: string; +export var types: SocketTypes; +export var options: SocketOptions; + +declare function socket(type: string, options?: any): Socket; +declare function socket(type: number, options?: any): Socket; +declare function createSocket(type: string, options?: any): Socket;