diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index 7f66f26114..3a6b7d6bf1 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -3,14 +3,14 @@ var app = angular.module("angular-jwt-tests", ["angular-jwt"]); -var $jwtHelper: angular.jwt.IJwtHelper; +var $jwtHelper: ng.jwt.IJwtHelper; var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8'; var tokenPayload = $jwtHelper.decodeToken(expToken); var date = $jwtHelper.getTokenExpirationDate(expToken); var bool = $jwtHelper.isTokenExpired(expToken); -var $jwtInterceptor: angular.jwt.IJwtInterceptor; +var $jwtInterceptor: ng.jwt.IJwtInterceptor; $jwtInterceptor.tokenGetter = () => { return expToken; diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts index d8c719e2ef..eb02cf24df 100644 --- a/angular-jwt/angular-jwt.d.ts +++ b/angular-jwt/angular-jwt.d.ts @@ -8,14 +8,14 @@ declare namespace angular.jwt { interface JwtToken { - iss: string; - sub: string; - aud: string; - exp: number; - nbf: number; - iat: number; - jti: string; - unique_name: string; + iss?: string; + sub?: string; + aud?: string; + exp?: number; + nbf?: number; + iat?: number; + jti?: string; + unique_name?: string; } interface IJwtHelper { diff --git a/angular-permission/angular-permission-2.3.1-tests.ts b/angular-permission/angular-permission-2.3.1-tests.ts new file mode 100644 index 0000000000..3753ba9d51 --- /dev/null +++ b/angular-permission/angular-permission-2.3.1-tests.ts @@ -0,0 +1,92 @@ +/// + +import permission = angular.permission; + +angular + .module('fooModule', ['permission', 'user']) + .run(function (PermissionStore: permission.PermissionStore, User: any) { + // Define anonymous permission + PermissionStore + .definePermission('anonymous', function (stateParams) { + // If the returned value is *truthy* then the user has the permission, otherwise they don't + if (!User) { + return true; // Is anonymous + } + return false; + }); + }); + + interface BackendUserService { + checkSession(): angular.IPromise; + getAccessLevel(): angular.IPromise<{accessLevel: string}>; + hasPermissionDefinition(permission: string) : angular.IPromise; + } + + angular.module('barModule', ['permission', 'user']) + .run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) { + PermissionStore + // Define user permission calling back-end + .definePermission('user', function (stateParams) { + // This time we will return a promise + // If the promise *resolves* then the user has the permission, if it *rejects* (you guessed it) + + // Let's assume this returns a promise that resolves or rejects if session is active + return User.checkSession(); + }); + + PermissionStore + // A different example for admin + .definePermission('admin', function (stateParams) { + var deferred = $q.defer(); + + User.getAccessLevel() + .then(function (data) { + if (data.accessLevel === 'admin') { + deferred.resolve(); + } else { + deferred.reject(); + } + }) + .catch(function () { + // Error with request + deferred.reject(); + }); + + return deferred.promise; + }); + + let arrayOfPermissionNames = ['p1', 'p2']; + PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) { + return User.hasPermissionDefinition(permissionName); + }); + + PermissionStore.clearStore(); + + PermissionStore.removePermissionDefinition('user'); + + let permissions: Array = PermissionStore.getStore(); + + + }); + +angular + .module('fooModule', ['permission', 'user']) + .run(function (RoleStore: permission.RoleStore, User: any) { + RoleStore + // Permission array validated role + // Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid + .defineRole('admin', ['user', 'editor']); + + RoleStore + // Server side validated role + .defineRole('accountant', [], function (stateParams) { + // Let's assume that we are making a request to server here and return response as promise + return User.hasRole('accountant'); + }); + + RoleStore.clearStore(); + + RoleStore.removeRoleDefinition('user'); + + let roles: Array = RoleStore.getStore(); + }); diff --git a/angular-permission/angular-permission-2.3.1.d.ts b/angular-permission/angular-permission-2.3.1.d.ts new file mode 100644 index 0000000000..afe32ce875 --- /dev/null +++ b/angular-permission/angular-permission-2.3.1.d.ts @@ -0,0 +1,165 @@ +// Type definitions for angular-permission 2.3.1 +// Project: https://github.com/Narzerus/angular-permission +// Definitions by: Voislav Mishevski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.permission { + + export interface PermissionStore { + /** + * Allows to define permission on application configuration + * @method + * + * @param permissionName {String} Name of defined permission + * @param validationFunction {Function} Function used to validate if permission is valid + */ + definePermission( + name: string, + validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + ): void; + + /** + * Allows to define set of permissionNames with shared validation function on application configuration + * @method + * @throws {TypeError} + * + * @param permissionNames {Array} Set of permission names + * @param validationFunction {Function} Function used to validate if permission is valid + */ + defineManyPermissions( + permissions: string[], + validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + ): void; + + clearStore(): void; + + /** + * Deletes permission + * @method + * + * @param permissionName {String} Name of defined permission + */ + removePermissionDefinition(permission: string): void; + + /** + * Checks if permission exists + * @method + * + * @param permissionName {String} Name of defined permission + * @returns {Boolean} + */ + hasPermissionDefinition(permissionName: string): boolean; + + /** + * Returns all permissions + * @method + * + * @returns {Object} Permissions collection + */ + getStore(): Permission[]; + } + + export interface RoleStore { + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + * @param [validationFunction] {Function} Function used to validate if permissions in role are valid + */ + defineRole( + role: string, + permissions: Array, + validationFunction: RoleValidationFunction + ): void; + + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + */ + defineRole(role: string, permissions: Array): void; + + /** + * Checks if role is defined in store + * @method + * + * @param roleName {String} Name of role + * @returns {Boolean} + */ + hasRoleDefinition(role: string): boolean; + + /** + * Returns role definition object by it's name + * @method + * + * @returns {permission.Role} Role definition object + */ + getRoleDefinition(roleName: string): Role; + + /** + * Removes all role definitions + * @method + */ + clearStore(): void; + + /** + * Deletes role from store + * @method + * + * @param roleName {String} Name of defined permission + */ + removeRoleDefinition(roleName: string): void; + + /** + * Returns all role definitions + * @method + * + * @returns {Object} Defined roles collection + */ + getStore(): Role[]; + } + + export interface Role { + roleName: string; + permissionNames: string[]; + validationFunction?: RoleValidationFunction; + } + + export interface Permission { + permissionName: string; + validationFunction?: PermissionValidationFunction; + } + + interface RoleValidationFunction { + (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + } + + interface PermissionValidationFunction { + (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + } + + export interface IPermissionState extends angular.ui.IState { + data?: any | DataWithPermissions; + } + + export interface DataWithPermissions { + permissions?: { + only?: (() => void) | Array | angular.IPromise; + except?: (() => void) | Array | angular.IPromise; + redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | {[index: string]: PermissionRedirectConfigation} + }; + } + + export interface PermissionRedirectConfigation { + state: string; + params?: {}; + options?: angular.ui.IStateOptions; + } +} diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index 206850ad70..cc9cd7c367 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -36,7 +36,7 @@ angular PermissionStore // A different example for admin - .definePermission('admin', function (stateParams) { + .definePermission('admin', function (permission: string, stateParams: angular.permission.TransitionProperties) { var deferred = $q.defer(); User.getAccessLevel() @@ -56,7 +56,7 @@ angular }); let arrayOfPermissionNames = ['p1', 'p2']; - PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) { + PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (permissionName: string, stateParams: angular.permission.TransitionProperties) { return User.hasPermissionDefinition(permissionName); }); @@ -79,7 +79,7 @@ angular RoleStore // Server side validated role - .defineRole('accountant', [], function (stateParams) { + .defineRole('accountant', [], function (permission, stateParams) { // Let's assume that we are making a request to server here and return response as promise return User.hasRole('accountant'); }); diff --git a/angular-permission/angular-permission.d.ts b/angular-permission/angular-permission.d.ts index afe32ce875..fecbafb29b 100644 --- a/angular-permission/angular-permission.d.ts +++ b/angular-permission/angular-permission.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-permission 2.3.1 +// Type definitions for angular-permission 2.3.6 // Project: https://github.com/Narzerus/angular-permission // Definitions by: Voislav Mishevski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,16 @@ /// declare namespace angular.permission { + /** + * Used as optional parameter provided on definitions of permissions and roles + */ + export interface TransitionProperties { + fromState?: angular.ui.IState; + fromParams?: angular.ui.IStateParamsService; + toState?: angular.ui.IState; + toParams?: angular.ui.IStateParamsService; + options?: angular.ui.IStateOptions; + } export interface PermissionStore { /** @@ -18,7 +28,7 @@ declare namespace angular.permission { */ definePermission( name: string, - validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise ): void; /** @@ -31,7 +41,7 @@ declare namespace angular.permission { */ defineManyPermissions( permissions: string[], - validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise ): void; clearStore(): void; @@ -138,11 +148,11 @@ declare namespace angular.permission { } interface RoleValidationFunction { - (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; } interface PermissionValidationFunction { - (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; } export interface IPermissionState extends angular.ui.IState { diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index fa2928c136..d33eeddace 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1683,7 +1683,7 @@ declare namespace protractor { * @return {!webdriver.promise.Promise} A promise that will resolve to the * scripts return value. */ - waitForAngular(): webdriver.promise.Promise; + waitForAngular(): webdriver.promise.Promise; /** * Add a module to load before Angular whenever Protractor.get is called. diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index 8ef1ab2e39..4aac8b4b34 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -35,7 +35,11 @@ interface Scope extends ng.IScope { app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateService) => { $scope['changeLanguage'] = function (key: any) { - $translate.use(key); + $translate.onReady().then(() => { + if($translate.isReady()) { + $translate.use(key); + } + }); }; }).run(($filter: ng.IFilterService) => { var x: string; diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 9d9eeb98a1..c4eca39a95 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -66,6 +66,8 @@ declare namespace angular.translate { useFallbackLanguage(langKey?: string): void; versionInfo(): string; loaderCache(): any; + isReady(): boolean; + onReady(): angular.IPromise; } interface ITranslateProvider extends angular.IServiceProvider { diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 7851d2da37..d92c90bc60 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -181,6 +181,10 @@ testApp.controller('TestCtrl', ( $log.log('modal rendered'); }); + modalInstance.closed.then(()=> { + $log.log('modal closed'); + }); + modalInstance.result.then((closeResult:any)=> { $log.log('modal closed', closeResult); }, (dismissResult:any)=> { diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 29ad03485b..0a7b54775e 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -270,6 +270,11 @@ declare namespace angular.ui.bootstrap { * A promise that is resolved when a modal is rendered. */ rendered: angular.IPromise; + + /** + * A promise that is resolved when a modal is closed and the animation completes. + */ + closed: angular.IPromise; } interface IModalScope extends angular.IScope { diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index 294bcf8982..8790e68cf3 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -36,6 +36,7 @@ mock.module( function () { return 2; } ); mock.module({ module1: function () { return 1; } }); +mock.module.sharedInjector(); date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); date = mock.TzDate(-8, 12345678); diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index c97471e5bf..9031cc56d1 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -47,7 +47,10 @@ declare namespace angular { inject: IInjectStatic // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module - module(...modules: any[]): any; + module: { + (...modules: any[]): any; + sharedInjector(): void; + } // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; diff --git a/array-find-index/array-find-index-tests.ts b/array-find-index/array-find-index-tests.ts new file mode 100644 index 0000000000..8c69a531e2 --- /dev/null +++ b/array-find-index/array-find-index-tests.ts @@ -0,0 +1,10 @@ +/// + +import * as arrayFindIndex from 'array-find-index'; + +arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn'); + +const ctx = {foo: 'rainbow'}; +arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) { + return x === this.foo; +}, ctx); diff --git a/array-find-index/array-find-index.d.ts b/array-find-index/array-find-index.d.ts new file mode 100644 index 0000000000..650cac2a16 --- /dev/null +++ b/array-find-index/array-find-index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for array-find-index +// Project: https://github.com/sindresorhus/array-find-index +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "array-find-index" { + type Predicate = (element: any, index: number, array: any[]) => boolean; + + function arrayFindIndex(arr: any[], predicate: Predicate): number; + function arrayFindIndex(arr: any[], predicate: Predicate, ctx: any): number; + namespace arrayFindIndex {} + export = arrayFindIndex; +} diff --git a/async/async.d.ts b/async/async.d.ts index 066685e3c7..c3d218fabc 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -15,7 +15,7 @@ interface AsyncIterator { (item: T, callback: ErrorCallback): void; } interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } -interface AsyncBooleanIterator { (item: T, callback: (truthValue: boolean) => void): void; } +interface AsyncBooleanIterator { (item: T, callback: (err: string, truthValue: boolean) => void): void; } interface AsyncWorker { (task: T, callback: ErrorCallback): void; } interface AsyncVoidFunction { (callback: ErrorCallback): void; } @@ -85,23 +85,23 @@ interface Async { map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - filter(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - select(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - reject(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + select(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + reject(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; + rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; - detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; - detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index eb54a5991d..879ebce832 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -1072,7 +1072,7 @@ declare module "aws-sdk" { GrantReadACP?: string; GrantWriteACP?: string; Key: string; - Metadata?: string[]; + Metadata?: { [key: string]:string; }; ServerSideEncryption?: string; StorageClass?: string; WebsiteRedirectLocation?: string; diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index f93ca868c7..b9749002c9 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -100,7 +100,7 @@ declare namespace Microsoft.WindowsAzure { } } -declare module "WindowsAzure" { +declare module "azure-mobile-apps-client" { export = WindowsAzure; } diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 42faf0909e..92758e143a 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -15,6 +15,9 @@ var knex = Knex({ var bookshelf = Bookshelf(knex); +bookshelf.plugin('registry'); +bookshelf.plugin(['virtuals']); + class User extends bookshelf.Model { get tableName() { return 'users'; } messages() : Bookshelf.Collection { diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 74f5e83d4a..cf70220840 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -18,7 +18,7 @@ declare module 'bookshelf' { Model : typeof Bookshelf.Model; Collection : typeof Bookshelf.Collection; - plugin(name: string) : Bookshelf; + plugin(name: string | string[] | Function, options?: any) : Bookshelf; transaction(callback : (transaction : knex.Transaction) => T) : Promise; } diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 9cdf8c3a5d..cdb48b2767 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -6211,6 +6211,11 @@ declare namespace chrome.tabs { * @since Chrome 27. */ faviconUrl?: string; + /** + * The tab's new title. + * @since Chrome 48. + */ + title?: string; } interface TabMoveInfo { diff --git a/colors/colors.d.ts b/colors/colors.d.ts index cc6b307c03..7a78240287 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -41,6 +41,7 @@ declare module "colors" { america: Color; trap: Color; random: Color; + zalgo: Color; } namespace e { @@ -80,6 +81,7 @@ declare module "colors" { export var america: Color; export var trap: Color; export var random: Color; + export var zalgo: Color; } export = e; @@ -120,4 +122,5 @@ interface String { america: string; trap: string; random: string; + zalgo: string; } diff --git a/compression/compression.d.ts b/compression/compression.d.ts index 6a444e3f49..84fa211bd0 100644 --- a/compression/compression.d.ts +++ b/compression/compression.d.ts @@ -10,8 +10,50 @@ declare module "compression" { namespace e { interface CompressionOptions { - threshold?: number; + /** + * See https://github.com/expressjs/compression#chunksize regarding the usage. + */ + chunkSize?: number; + + /** + * See https://github.com/expressjs/compression#level regarding the usage. + */ + level?: number; + + /** + * See https://github.com/expressjs/compression#memlevel regarding the usage. + */ + memLevel?: number; + + /** + * See https://github.com/expressjs/compression#strategy regarding the usage. + */ + strategy?: number; + + /** + * See https://github.com/expressjs/compression#threshold regarding the usage. + */ + threshold?: number|string; + + /** + * See https://github.com/expressjs/compression#windowbits regarding the usage. + */ + windowBits?: number; + + /** + * See https://github.com/expressjs/compression#filter regarding the usage. + */ filter?: Function; + + /** + * See https://nodejs.org/api/zlib.html#zlib_class_options regarding the usage. + */ + flush?: number; + + /** + * See https://nodejs.org/api/zlib.html#zlib_class_options regarding the usage. + */ + finishFlush?: number; } } diff --git a/fixed-data-table/fixed-data-table.d.ts b/fixed-data-table/fixed-data-table.d.ts index e4bc79ff51..dcc188e5ba 100644 --- a/fixed-data-table/fixed-data-table.d.ts +++ b/fixed-data-table/fixed-data-table.d.ts @@ -398,7 +398,7 @@ declare namespace FixedDataTable { /** * Component that defines the attributes of a table column group. */ - export interface ColumnGroupProps { + export interface ColumnGroupProps extends __React.Props { /** * The horizontal alignment of the table cell content. * 'left', 'center', 'right' diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index 1366a82022..a2c40c1d68 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -19,6 +19,7 @@ import { screen, shell, session, + systemPreferences, hideInternalModules } from 'electron'; @@ -65,7 +66,7 @@ app.on('ready', () => { mainWindow.webContents.openDevTools(); mainWindow.webContents.toggleDevTools(); - mainWindow.webContents.openDevTools({detach: true}); + mainWindow.webContents.openDevTools({mode: 'detach'}); mainWindow.webContents.closeDevTools(); mainWindow.webContents.addWorkSpace('/path/to/workspace'); mainWindow.webContents.removeWorkSpace('/path/to/workspace'); @@ -260,8 +261,8 @@ app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); app.commandLine.appendSwitch('v', -1); app.commandLine.appendSwitch('vmodule', 'console=0'); -// app -// https://github.com/atom/electron/blob/master/docs/api/app.md +// systemPreferences +// https://github.com/electron/electron/blob/master/docs/api/system-preferences.md var browserOptions = { width: 1000, @@ -271,7 +272,7 @@ var browserOptions = { }; // Make the window transparent only if the platform supports it. -if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { +if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true; browserOptions.frame = false; } @@ -288,9 +289,12 @@ if (browserOptions.transparent) { } app.on('platform-theme-changed', () => { - console.log(app.isDarkMode()); + console.log(systemPreferences.isDarkMode()); }); +// app +// https://github.com/atom/electron/blob/master/docs/api/app.md + app.on('certificate-error', function(event, webContents, url, error, certificate, callback) { if (url == "https://github.com") { // Verification logic. @@ -337,6 +341,9 @@ win.on('closed', () => { win.loadURL('https://github.com'); win.show(); +var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); +win.setSheetOffset(toolbarRect.height); + // content-tracing // https://github.com/atom/electron/blob/master/docs/api/content-tracing.md @@ -517,12 +524,20 @@ var template = [ { label: 'Reload', accelerator: 'Command+R', - click: () => { BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache(); } + click: (item, focusedWindow) => { + if (focusedWindow) { + focusedWindow.webContents.reloadIgnoringCache(); + } + } }, { label: 'Toggle DevTools', accelerator: 'Alt+Command+I', - click: () => { BrowserWindow.getFocusedWindow().webContents.toggleDevTools(); } + click: (item, focusedWindow) => { + if (focusedWindow) { + focusedWindow.webContents.toggleDevTools(); + } + } } ] }, @@ -703,6 +718,18 @@ var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); +// process +// https://github.com/electron/electron/blob/master/docs/api/process.md + +console.log(process.type); +console.log(process.resourcesPath); +console.log(process.mas); +console.log(process.windowsStore); +process.noAsar = true; +process.crash(); +process.hang(); +process.setFdLimit(8192); + // screen // https://github.com/atom/electron/blob/master/docs/api/screen.md diff --git a/github-electron/github-electron-renderer-tests.ts b/github-electron/github-electron-renderer-tests.ts index 37faae9dbb..42d034c5c7 100644 --- a/github-electron/github-electron-renderer-tests.ts +++ b/github-electron/github-electron-renderer-tests.ts @@ -171,6 +171,16 @@ var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); +// https://github.com/electron/electron/blob/master/docs/api/process.md + +// preload.js +var _setImmediate = setImmediate; +var _clearImmediate = clearImmediate; +process.once('loaded', function() { + global.setImmediate = _setImmediate; + global.clearImmediate = _clearImmediate; +}); + // screen // https://github.com/atom/electron/blob/master/docs/api/screen.md diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index ec53909d50..131a0a425a 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v0.37.6 +// Type definitions for Electron v0.37.7 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -149,11 +149,6 @@ declare namespace Electron { * Emitted when the gpu process crashes. */ on(event: 'gpu-process-crashed', listener: Function): this; - /** - * Emitted when the system’s Dark Mode theme is toggled. - * Note: This is only implemented on OS X. - */ - on(event: 'platform-theme-changed', listener: Function): this; on(event: string, listener: Function): this; /** * Try to close all windows. The before-quit event will first be emitted. @@ -256,10 +251,16 @@ declare namespace Electron { /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * - * Note: This API is only available on Windows. + * Note: This is only implemented on Windows. * On OS X, removing the app will automatically remove the app as the default protocol handler. */ removeAsDefaultProtocolClient(protocol: string): void; + /** + * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). + * + * Note: This is only implemented on OS X and Windows. + */ + isDefaultProtocolClient(protocol: string): boolean; /** * Adds tasks to the Tasks category of JumpList on Windows. * @@ -285,18 +286,13 @@ declare namespace Electron { */ setAppUserModelId(id: string): void; /** - * This method returns true if DWM composition (Aero Glass) is enabled, - * and false otherwise. You can use it to determine if you should create - * a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled). + * Imports the certificate in pkcs12 format into the platform certificate store. + * @param callback Called with the result of import operation, a value of 0 indicates success + * while any other value indicates failure according to chromium net_error_list. * - * Note: This is only implemented on Windows. + * Note: This API is only available on Linux. */ - isAeroGlassEnabled(): boolean; - /** - * @returns If the system is in Dark Mode. - * Note: This is only implemented on OS X. - */ - isDarkMode(): boolean; + importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void; commandLine: CommandLine; /** * Note: This API is only available on Mac. @@ -306,6 +302,17 @@ declare namespace Electron { type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'; + interface ImportCertificateOptions { + /** + * Path for the pkcs12 file. + */ + certificate: string; + /** + * Passphrase for the certificate. + */ + password: string; + } + interface CommandLine { /** * Append a switch [with optional value] to Chromium's command line. @@ -814,6 +821,11 @@ declare namespace Electron { * @returns The title of the native window. */ getTitle(): string; + /** + * Changes the attachment point for sheets on Mac OS X. + * Note: This API is available only on OS X. + */ + setSheetOffset(offset: number): void; /** * Starts or stops flashing the window to attract user's attention. */ @@ -2244,19 +2256,19 @@ declare namespace Electron { /** * Registers a protocol of scheme that will send the file as a response. */ - registerFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: FileProtocolCallback) => void, completion?: (error: Error) => void): void; + registerFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; /** * Registers a protocol of scheme that will send a Buffer as a response. */ - registerBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: BufferProtocolCallback) => void, completion?: (error: Error) => void): void; + registerBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; /** * Registers a protocol of scheme that will send a String as a response. */ - registerStringProtocol(scheme: string, handler: (request: ProtocolRequest, callback: StringProtocolCallback) => void, completion?: (error: Error) => void): void; + registerStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; /** * Registers a protocol of scheme that will send an HTTP request as a response. */ - registerHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: HttpProtocolCallback) => void, completion?: (error: Error) => void): void; + registerHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; /** * Unregisters the custom protocol of scheme. */ @@ -2268,25 +2280,30 @@ declare namespace Electron { /** * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response. */ - interceptFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: FileProtocolCallback) => void, completion?: (error: Error) => void): void; - /** - * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response. - */ - interceptStringProtocol(scheme: string, handler: (request: ProtocolRequest, callback: BufferProtocolCallback) => void, completion?: (error: Error) => void): void; + interceptFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; /** * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response. */ - interceptBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: StringProtocolCallback) => void, completion?: (error: Error) => void): void; + interceptBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; + /** + * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response. + */ + interceptStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; /** * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response. */ - interceptHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: HttpProtocolCallback) => void, completion?: (error: Error) => void): void; + interceptHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; /** * Remove the interceptor installed for scheme and restore its original handler. */ uninterceptProtocol(scheme: string, completion?: (error: Error) => void): void; } + type FileProtocolHandler = (request: ProtocolRequest, callback: FileProtocolCallback) => void; + type BufferProtocolHandler = (request: ProtocolRequest, callback: BufferProtocolCallback) => void; + type StringProtocolHandler = (request: ProtocolRequest, callback: StringProtocolCallback) => void; + type HttpProtocolHandler = (request: ProtocolRequest, callback: HttpProtocolCallback) => void; + interface ProtocolRequest { url: string; referrer: string; @@ -2392,7 +2409,7 @@ declare namespace Electron { */ scaleFactor: number; /** - * Can be 0, 1, 2, 3, each represents screen rotation in clock-wise degrees of 0, 90, 180, 270. + * Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees. */ rotation: number; touchSupport: 'available' | 'unavailable' | 'unknown'; @@ -2419,7 +2436,7 @@ declare namespace Electron { /** * The screen module retrieves information about screen size, displays, cursor position, etc. - * You should not use this module until the ready event of the app module is emitted. + * You can not use this module until the ready event of the app module is emitted. */ interface Screen extends NodeJS.EventEmitter { /** @@ -2547,7 +2564,7 @@ declare namespace Electron { webRequest: WebRequest; } - type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen'; + type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; interface ClearStorageDataOptions { /** @@ -2926,6 +2943,47 @@ declare namespace Electron { beep(): void; } + // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md + + /** + * Get system preferences. + */ + interface SystemPreferences { + /** + * @returns If the system is in Dark Mode. + * + * Note: This is only implemented on OS X. + */ + isDarkMode(): boolean; + /** + * Subscribes to native notifications of OS X, callback will be called when the corresponding event happens. + * The id of the subscriber is returned, which can be used to unsubscribe the event. + * + * Note: This is only implemented on OS X. + */ + subscribeNotification(event: string, callback: Function): number; + /** + * Removes the subscriber with id. + * + * Note: This is only implemented on OS X. + */ + unsubscribeNotification(id: number): void; + /** + * Get the value of key in system preferences. + * + * Note: This is only implemented on OS X. + */ + getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url'): any; + /** + * This method returns true if DWM composition (Aero Glass) is enabled, + * and false otherwise. You can use it to determine if you should create + * a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled). + * + * Note: This is only implemented on Windows. + */ + isAeroGlassEnabled(): boolean; + } + // https://github.com/electron/electron/blob/master/docs/api/tray.md /** @@ -3253,6 +3311,10 @@ declare namespace Electron { * @returns Whether web page is still loading resources. */ isLoading(): boolean; + /** + * @returns Whether the main frame (and not just iframes or frames within it) is still loading. + */ + isLoadingMainFrame(): boolean; /** * @returns Whether web page is waiting for a first-response for the main * resource of the page. @@ -3420,9 +3482,9 @@ declare namespace Electron { */ openDevTools(options?: { /** - * Opens devtools in a new window. + * Opens the devtools with specified dock state. Defaults to last used dock state. */ - detach?: boolean; + mode?: 'right' | 'bottom' | 'undocked' | 'detach' }): void; /** * Closes the developer tools. @@ -4234,7 +4296,7 @@ declare namespace Electron { * Emitted when a page's theme color changes. This is usually due to encountering a meta tag: * */ - addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.DidChangeThemeColorEvent) => void, useCapture?: boolean): void; /** * Emitted when DevTools is opened. */ @@ -4330,6 +4392,10 @@ declare namespace Electron { name: string; version: string; } + + interface DidChangeThemeColorEvent extends Event { + themeColor: string; + } } /** @@ -4386,6 +4452,7 @@ declare namespace Electron { protocol: Electron.Protocol; screen: Electron.Screen; session: typeof Electron.Session; + systemPreferences: Electron.SystemPreferences; Tray: Electron.Tray; hideInternalModules(): void; } @@ -4424,6 +4491,54 @@ interface File { path: string; } +// https://github.com/electron/electron/blob/master/docs/api/process.md + +declare namespace NodeJS { + interface Process { + /** + * Process's type + */ + type: 'browser' | 'renderer'; + /** + * Path to JavaScript source code. + */ + resourcesPath: string; + /** + * For Mac App Store build, this value is true, for other builds it is undefined. + */ + mas?: boolean; + /** + * If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined. + */ + windowsStore?: boolean; + /** + * Emitted when Electron has loaded its internal initialization script + * and is beginning to load the web page or the main script. + */ + on(event: 'loaded', listener: Function): this; + on(event: string, listener: Function): this; + /** + * Setting this to true can disable the support for asar archives in Node's built-in modules. + */ + noAsar?: boolean; + /** + * Causes the main thread of the current process crash; + */ + crash(): void; + /** + * Causes the main thread of the current process hang. + */ + hang(): void; + /** + * Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, + * whichever is lower for the current process. + * + * Note: This API is only available on Mac and Linux. + */ + setFdLimit(maxDescriptors: number): void; + } +} + declare module 'electron' { var electron: Electron.ElectronMainAndRenderer; export = electron; diff --git a/handsontable/handsontable-tests.ts b/handsontable/handsontable-tests.ts index 88cbe587af..25ec4dee0f 100644 --- a/handsontable/handsontable-tests.ts +++ b/handsontable/handsontable-tests.ts @@ -14,14 +14,17 @@ function test_HandsontableInit() { autoRowSize: true, autoWrapCol: true, autoWrapRow: true, + bindRowsWithHeaders: 'foo', cell: [], cells: function() {}, checkedTemplate: true, className: [], colHeaders: true, + collapsibleColumns: true, columnHeaderHeight: 123, columns: [], columnSorting: {}, + columnSummary: {}, colWidths: 123, commentedCellClassName: 'foo', comments: [], @@ -41,15 +44,24 @@ function test_HandsontableInit() { debug: true, defaultDate: 'foo', disableVisualSelection: true, + dropdownMenu: [], editor: true, enterBeginsEditing: true, enterMoves: {}, fillHandle: true, + filter: true, + filteringCaseSensitive: true, + filters: false, fixedColumnsLeft: 123, + fixedRowsBottom: 123, fixedRowsTop: 123, format: 'foo', fragmentSelection: true, + ganttChart: {}, + headerTooltips: true, height: 123, + hiddenColumns: true, + hiddenRows: {}, invalidCellClassName: 'foo', label: {}, language: 'foo', @@ -66,6 +78,7 @@ function test_HandsontableInit() { minSpareCols: 123, minSpareRows: 123, multiSelect: true, + nestedHeaders: [], noWordWrapClassName: 'foo', observeChanges: true, observeDOMVisibility: true, @@ -85,6 +98,7 @@ function test_HandsontableInit() { search: true, selectOptions: [], skipColumnOnPaste: true, + sortByRelevance: true, sortFunction: function() {}, sortIndicator: true, source: [], diff --git a/handsontable/handsontable.d.ts b/handsontable/handsontable.d.ts index 1af41e0125..9c7f87aaa3 100644 --- a/handsontable/handsontable.d.ts +++ b/handsontable/handsontable.d.ts @@ -16,14 +16,17 @@ declare namespace ht { autoRowSize?: Object|boolean; autoWrapCol?: boolean; autoWrapRow?: boolean; + bindRowsWithHeaders?: boolean|string; cell?: any[]; cells?: Function; checkedTemplate?: boolean|string; className?: string|any[]; colHeaders?: boolean|any[]|Function; + collapsibleColumns?: boolean|any[]; columnHeaderHeight?: number|any[]; columns?: any[]; columnSorting?: boolean|Object; + columnSummary?: Object; colWidths?: any[]|Function|number|string; commentedCellClassName?: string; comments?: boolean|any[]; @@ -43,15 +46,24 @@ declare namespace ht { debug?: boolean; defaultDate?: string; disableVisualSelection?: boolean|string|any[]; + dropdownMenu?: boolean|Object|any[]; editor?: string|Function|boolean; enterBeginsEditing?: boolean; enterMoves?: Object|Function; fillHandle?: boolean|string|Object; + filter?: boolean; + filteringCaseSensitive?: boolean; + filters?: boolean; fixedColumnsLeft?: number; + fixedRowsBottom?: number; fixedRowsTop?: number; format?: string; fragmentSelection?: boolean|string; + ganttChart?: Object; + headerTooltips?: boolean|Object; height?: number|Function; + hiddenColumns?: boolean|Object; + hiddenRows?: boolean|Object; invalidCellClassName?: string; label?: Object; language?: string; @@ -68,6 +80,7 @@ declare namespace ht { minSpareCols?: number; minSpareRows?: number; multiSelect?: boolean; + nestedHeaders?: any[]; noWordWrapClassName?: string; observeChanges?: boolean; observeDOMVisibility?: boolean; @@ -87,6 +100,7 @@ declare namespace ht { search?: boolean; selectOptions?: any[]; skipColumnOnPaste?: boolean; + sortByRelevance?: boolean; sortFunction?: Function; sortIndicator?: boolean; source?: any[]|Function; diff --git a/helmet/helmet-tests.ts b/helmet/helmet-tests.ts index 0223244cc0..5d8a7515cd 100644 --- a/helmet/helmet-tests.ts +++ b/helmet/helmet-tests.ts @@ -10,22 +10,19 @@ var app = express(); */ function helmetTest() { app.use(helmet()); + app.use(helmet({})); + app.use(helmet({ frameguard: false })); + app.use(helmet({ frameguard: true })); + app.use(helmet({ + frameguard: { + action: 'deny' + } + })); } /** - * @summary Test for {@see helmet#xssFilter} function. + * @summary Test for {@see helmet#contentSecurityPolicy} function. */ -function xssFilterTest() { - app.use(helmet.xssFilter()); - app.use(helmet.xssFilter({})); - app.use(helmet.xssFilter({ setOnOldIE: false })); - app.use(helmet.xssFilter({ setOnOldIE: true })); -} - -/** - * @summary Test for {@see helmet#csp} function. - */ - function contentSecurityPolicyTest() { const emptyArray: string[] = []; const config = { @@ -63,86 +60,6 @@ function contentSecurityPolicyTest() { }, setAllHeaders: true })); - - app.use(helmet.csp()); - app.use(helmet.csp({})); - app.use(helmet.csp(config)); - app.use(helmet.csp({ - directives: { - defaultSrc: ["'self'"] - }, - setAllHeaders: true - })); -} - -/** - * @summary Test for {@see helmet#frameguard} function. - */ -function frameguardTest() { - app.use(helmet.frameguard()); - app.use(helmet.frameguard("sameorigin")); -} - -/** - * @summary Test for {@see helmet#hsts} function. - */ -function hstsTest() { - app.use(helmet.hsts()); - app.use(helmet.hsts({ maxAge: 7776000000 })); -} - -/** - * @summary Test for {@see helmet#ieNoOpen} function. - */ -function ieNoOpenTest() { - app.use(helmet.ieNoOpen()); -} - -/** - * @summary Test for {@see helmet#noSniff} function. - */ -function noSniffTest() { - app.use(helmet.noSniff()); -} - -/** - * @summary Test for {@see helmet#publicKeyPins} function. - */ -function publicKeyPinsTest() { - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - })); - - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - includeSubdomains: false - })); - - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - includeSubdomains: true - })); - - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - reportUri: "http://example.com" - })); - - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - reportOnly: true - })); - - app.use(helmet.publicKeyPins({ - maxAge: 7776000000, - sha256s: ["AbCdEf123=", "ZyXwVu456="], - setIf: function (req, res) { return true; } - })); } /** @@ -153,3 +70,132 @@ function dnsPrefetchControlTest() { app.use(helmet.dnsPrefetchControl({ allow: false })); app.use(helmet.dnsPrefetchControl({ allow: true })); } + +/** + * @summary Test for {@see helmet#frameguard} function. + */ +function frameguardTest() { + app.use(helmet.frameguard()); + app.use(helmet.frameguard({})); + app.use(helmet.frameguard({ action: 'deny' })); + app.use(helmet.frameguard({ action: 'sameorigin' })); + app.use(helmet.frameguard({ + action: 'allow-from', + domain: 'http://example.com' + })); +} + +/** + * @summary Test for {@see helmet#hidePoweredBy} function. + */ +function hidePoweredBy() { + app.use(helmet.hidePoweredBy()); + app.use(helmet.hidePoweredBy({})); + app.use(helmet.hidePoweredBy({ setTo: 'PHP 4.2.0' })); +} + +/** + * @summary Test for {@see helmet#hpkp} function. + */ +function hpkpTest() { + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: false + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportUri: 'http://example.com' + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportOnly: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + setIf: function (req, res) { return true; } + })); +} + +/** + * @summary Test for {@see helmet#hsts} function. + */ +function hstsTest() { + app.use(helmet.hsts()); + + app.use(helmet.hsts({ maxAge: 7776000000 })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + includeSubdomains: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + preload: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + force: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + setIf: function (req, res) { return true; } + })); +} + +/** + * @summary Test for {@see helmet#ieNoOpen} function. + */ +function ieNoOpenTest() { + app.use(helmet.ieNoOpen()); +} + +/** + * @summary Test for {@see helmet#noCache} function. + */ +function noCacheTest() { + app.use(helmet.noCache()); + app.use(helmet.noCache({})); + app.use(helmet.noCache({ noEtag: true })); +} + +/** + * @summary Test for {@see helmet#noSniff} function. + */ +function noSniffTest() { + app.use(helmet.noSniff()); +} + +/** + * @summary Test for {@see helmet#xssFilter} function. + */ +function xssFilterTest() { + app.use(helmet.xssFilter()); + app.use(helmet.xssFilter({})); + app.use(helmet.xssFilter({ setOnOldIE: false })); + app.use(helmet.xssFilter({ setOnOldIE: true })); +} diff --git a/helmet/helmet.d.ts b/helmet/helmet.d.ts index f32ba0a2d9..7154d0b739 100644 --- a/helmet/helmet.d.ts +++ b/helmet/helmet.d.ts @@ -5,15 +5,28 @@ /// -declare module "helmet" { - import express = require("express"); - - interface IHelmetCspDirectiveFunction { +declare module 'helmet' { + import express = require('express'); + + interface IHelmetConfiguration { + contentSecurityPolicy? : boolean | IHelmetContentSecurityPolicyConfiguration, + dnsPrefetchControl?: boolean | IHelmetDnsPrefetchControlConfiguration, + frameguard?: boolean | IHelmetFrameguardConfiguration, + hidePoweredBy?: boolean | IHelmetHidePoweredByConfiguration, + hpkp?: boolean | IHelmetHpkpConfiguration, + hsts?: boolean | IHelmetHstsConfiguration, + ieNoOpen?: boolean, + noCache?: boolean, + noSniff?: boolean, + xssFilter?: boolean | IHelmetXssFilterConfiguration + } + + interface IHelmetContentSecurityPolicyDirectiveFunction { (req: express.Request, res: express.Response): string; } - type HelmetCspDirectiveValue = string | IHelmetCspDirectiveFunction; + type HelmetCspDirectiveValue = string | IHelmetContentSecurityPolicyDirectiveFunction; - interface IHelmetCspDirectives { + interface IHelmetContentSecurityPolicyDirectives { baseUri? : HelmetCspDirectiveValue[], childSrc? : HelmetCspDirectiveValue[], connectSrc? : HelmetCspDirectiveValue[], @@ -31,36 +44,53 @@ declare module "helmet" { scriptSrc? : HelmetCspDirectiveValue[], styleSrc? : HelmetCspDirectiveValue[] } - - interface IHelmetCspConfiguration { + + interface IHelmetContentSecurityPolicyConfiguration { reportOnly? : boolean; setAllHeaders? : boolean; disableAndroid? : boolean; browserSniff?: boolean; - directives? : IHelmetCspDirectives + directives? : IHelmetContentSecurityPolicyDirectives } - interface IHelmetPublicKeyPinsSetIfFunction { + interface IHelmetDnsPrefetchControlConfiguration { + allow? : boolean; + } + + interface IHelmetFrameguardConfiguration { + action? : string, + domain? : string + } + + interface IHelmetHidePoweredByConfiguration { + setTo? : string + } + + interface IHelmetSetIfFunction { (req: express.Request, res: express.Response): boolean; } - interface IHelmetPublicKeyPinsConfiguration { + interface IHelmetHpkpConfiguration { maxAge : number; sha256s : string[]; includeSubdomains? : boolean; reportUri? : string; reportOnly? : boolean; - setIf?: IHelmetPublicKeyPinsSetIfFunction + setIf?: IHelmetSetIfFunction + } + + interface IHelmetHstsConfiguration { + maxAge: number; + includeSubdomains? : boolean; + preload? : boolean; + setIf? : IHelmetSetIfFunction, + force? : boolean; } interface IHelmetXssFilterConfiguration { setOnOldIE? : boolean; } - interface IHelmetDnsPrefetchControlConfiguration { - allow? : boolean; - } - /** * @summary Interface for helmet class. * @interface @@ -70,77 +100,74 @@ declare module "helmet" { * @summary Constructor. * @return {RequestHandler} The Request handler. */ - ():express.RequestHandler; + (options ?: IHelmetConfiguration): express.RequestHandler; + + /** + * @summary Set policy around third-party content via headers + * @param {IHelmetContentSecurityPolicyConfiguration} options The options + * @return {RequestHandler} The Request handler + */ + contentSecurityPolicy(options ?: IHelmetContentSecurityPolicyConfiguration): express.RequestHandler; /** * @summary Stop browsers from doing DNS prefetching. + * @param {IHelmetDnsPrefetchControlConfiguration} options The options + * @return {RequestHandler} The Request handler */ - dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration):express.RequestHandler; + dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration): express.RequestHandler; /** * @summary Prevent clickjacking. - * @param {string} header The header. - * @return {RequestHandler} The Request handler. + * @param {IHelmetFrameguardConfiguration} options The options + * @return {RequestHandler} The Request handler */ - frameguard(header ?: string):express.RequestHandler; + frameguard(options ?: IHelmetFrameguardConfiguration): express.RequestHandler; /** * @summary Hide "X-Powered-By" header. - * @param {Object} options The options. + * @param {IHelmetHidePoweredByConfiguration} options The options * @return {RequestHandler} The Request handler. */ - hidePoweredBy(options ?: Object):express.RequestHandler; + hidePoweredBy(options ?: IHelmetHidePoweredByConfiguration): express.RequestHandler; + + /** + * @summary Adds the "Public-Key-Pins" header. + * @param {IHelmetHpkpConfiguration} options The options + * @return {RequestHandler} The Request handler. + */ + hpkp(options ?: IHelmetHpkpConfiguration): express.RequestHandler; /** * @summary Adds the "Strict-Transport-Security" header. - * @param {Object} options The options. + * @param {IHelmetHstsConfiguration} options The options * @return {RequestHandler} The Request handler. */ - hsts(options ?: Object):express.RequestHandler; + hsts(options ?: IHelmetHstsConfiguration): express.RequestHandler; /** * @summary Add the "X-Download-Options" header. * @return {RequestHandler} The Request handler. */ - ieNoOpen():express.RequestHandler; + ieNoOpen(): express.RequestHandler; /** * @summary Add the "Cache-Control" and "Pragma" headers to stop caching. * @return {RequestHandler} The Request handler. */ - noCache(options ?: Object):express.RequestHandler; + noCache(options ?: Object): 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; + noSniff(): express.RequestHandler; /** * @summary Mitigate cross-site scripting attacks with the "X-XSS-Protection" header. + * @param {IHelmetXssFilterConfiguration} options The options * @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; - - /** - * @see csp - */ - contentSecurityPolicy(options ?: IHelmetCspConfiguration): express.RequestHandler; - + xssFilter(options ?: IHelmetXssFilterConfiguration): express.RequestHandler; } var helmet: Helmet; diff --git a/highland/highland-tests.ts b/highland/highland-tests.ts index c7e213aa17..7a67670edd 100644 --- a/highland/highland-tests.ts +++ b/highland/highland-tests.ts @@ -137,7 +137,9 @@ fooStream = _(readable); fooStream = _(emitter); fooStream = _(fooStreamThen); -fooStream = _(fooArrThen); +fooStream = _(fooThen); + +fooArrStream = _(fooArrThen); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/highland/highland.d.ts b/highland/highland.d.ts index 8becaf2762..f3617ccd14 100644 --- a/highland/highland.d.ts +++ b/highland/highland.d.ts @@ -67,7 +67,7 @@ interface HighlandStatic { // moar (promise for everything?) (xs: Highland.Thenable>): Highland.Stream; - (xs: Highland.Thenable): Highland.Stream; + (xs: Highland.Thenable): Highland.Stream; /** * The end of stream marker. This is sent along the data channel of a Stream diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index d8627c4462..9f976fd751 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -100,7 +100,7 @@ declare namespace I18next { getFixedT(lng?:string, ns?:string|string[]):TranslationFunction; - t(key:string, options?:TranslationOptions):string; + t(key:string, options?:TranslationOptions):string|any|Array; exists():boolean; diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index 1790e542f1..d8c98ae25f 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -9,6 +9,8 @@ testIonic.config(['$ionicConfigProvider', ($ionicConfigProvider: ionic.utility.I $ionicConfigProvider.views.maxCache(10); var forwardCache: boolean = $ionicConfigProvider.views.forwardCache(); $ionicConfigProvider.views.forwardCache(true); + var swipeBackEnabled: boolean = $ionicConfigProvider.views.swipeBackEnabled(); + $ionicConfigProvider.views.swipeBackEnabled(true); var jsScrolling: boolean = $ionicConfigProvider.scrolling.jsScrolling(); $ionicConfigProvider.scrolling.jsScrolling(true); diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index e2cbc195b7..fae9cdbf63 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -358,6 +358,7 @@ declare namespace ionic { transition(transition?: string): string; maxCache(maxNumber?: number): number; forwardCache(value?: boolean): boolean; + swipeBackEnabled(value?: boolean): boolean; }; scrolling: { jsScrolling(value?: boolean): boolean; diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 033dd23faa..451b9abc88 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -29,7 +29,7 @@ declare namespace jest { function fn(implementation?: Function): Mock; function dontMock(moduleName: string): void; function genMockFromModule(moduleName: string): Mock; - function mock(moduleName: string): void; + function mock(moduleName: string, factory?: Function): void; function runAllTicks(): void; function runAllTimers(): void; function runOnlyPendingTimers(): void; diff --git a/jquery-mousewheel/jquery-mousewheel-tests.ts b/jquery-mousewheel/jquery-mousewheel-tests.ts new file mode 100644 index 0000000000..7f8807d7bb --- /dev/null +++ b/jquery-mousewheel/jquery-mousewheel-tests.ts @@ -0,0 +1,11 @@ +/// + +$('#my_elem').on('mousewheel', (event: JQueryMousewheel.JQueryMousewheelEventObject) => { + console.log(event.deltaX, event.deltaY, event.deltaFactor, event.deltaMode, event.absDelta); +}); + +$('#my_elem').mousewheel(event => { + console.log(event.deltaX, event.deltaY, event.deltaFactor, event.deltaMode, event.absDelta); +}); + +$('#my_elem').unmousewheel(); diff --git a/jquery-mousewheel/jquery-mousewheel.d.ts b/jquery-mousewheel/jquery-mousewheel.d.ts new file mode 100644 index 0000000000..1061e49f28 --- /dev/null +++ b/jquery-mousewheel/jquery-mousewheel.d.ts @@ -0,0 +1,21 @@ +// Type definitions for jquery-mousewheel v3.1.13 +// Project: https://github.com/jquery/jquery-mousewheel +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JQueryMousewheel { + interface JQueryMousewheelEventObject extends JQueryEventObject { + deltaX: number; + deltaY: number; + deltaFactor: number; + deltaMode: number; + absDelta: number; + } +} + +interface JQuery { + mousewheel(handler: (eventObject: JQueryMousewheel.JQueryMousewheelEventObject, ...args: any[]) => any): JQuery + unmousewheel(): JQuery; +} diff --git a/karma/karma-tests.ts b/karma/karma-tests.ts index 7dbd533b59..31a3948275 100644 --- a/karma/karma-tests.ts +++ b/karma/karma-tests.ts @@ -43,6 +43,14 @@ server.on('browser_register', function (browser: any) { console.log('A new browser was registered'); }); +server.on('run_complete', (browsers, results) => { + results.disconnected = false; + results.error = false; + results.exitCode = 0; + results.failed = 9; + results.success = 10; +}); + //var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any karma.runner.run({port: 9876}, function(exitCode: number) { console.log('Karma has exited with ' + exitCode); diff --git a/karma/karma.d.ts b/karma/karma.d.ts index 455d1df911..e0fcfba7b9 100644 --- a/karma/karma.d.ts +++ b/karma/karma.d.ts @@ -34,7 +34,7 @@ declare module 'karma' { interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` - new(emitter: NodeJS.EventEmitter, injector: any): Launcher; + new (emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { @@ -53,11 +53,19 @@ declare module 'karma' { } interface Runner { - run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; + run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void; + } + + interface TestResults { + disconnected: boolean; + error: boolean; + exitCode: number; + failed: number; + success: number; } interface Server extends NodeJS.EventEmitter { - new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; + new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ @@ -72,6 +80,13 @@ declare module 'karma' { */ refreshFiles(): Promise; + on(event: string, listener: Function): this; + + /** + * Listen to the 'run_complete' event. + */ + on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this; + ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 @@ -191,7 +206,7 @@ declare module 'karma' { * @default [] * @description List of files/patterns to load in the browser. */ - files?: (FilePattern|string)[]; + files?: (FilePattern | string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... @@ -257,7 +272,7 @@ declare module 'karma' { * but your interactive debugging does not. * */ - preprocessors?: { [name: string]: string|string[] } + preprocessors?: { [name: string]: string | string[] } /** * @default 'http:' * Possible Values: diff --git a/kik-browser/kik-browser-tests.ts b/kik-browser/kik-browser-tests.ts new file mode 100644 index 0000000000..ebd7bed113 --- /dev/null +++ b/kik-browser/kik-browser-tests.ts @@ -0,0 +1,310 @@ +/// + +if (kik.enabled) { + // running in kik +} + +if (kik.send) { + // can send messages +} + +kik.getUser(function (user) { + if (!user) { + // user denied access to their information + } else { + typeof user.username; // "string" + typeof user.fullName; // "string" + typeof user.firstName; // "string" + typeof user.lastName; // "string" + typeof user.pic; // "string" + typeof user.thumbnail; // "string" + } +}); + +if (kik.hasPermission()) { + // your webpage has permission +} + +kik.getAnonymousUser(function (token) { + typeof token; // "string" +}); + +kik.sign("my data", function (signedData, username, host) { + if (!signedData) { + // failed to sign + // perhaps user denied permissions + } else { + // successfully signed + typeof signedData; // "string", signed data + typeof username; // "string", user who signed + typeof host; // "string", host of your webpage + // all of these fields must be passed to the + // verification service to be successful + } +}); + +kik.anonymousSign("my data", function (signedData, anonToken, host) { + if (!signedData) { + // failed to sign + } else { + // successfully signed + typeof signedData; // "string", signed data + typeof anonToken; // "string", anonymous user who signed + typeof host; // "string", host of your webpage + } +}); + +kik.send({ + title : "Message title" , + text : "Message body" , + pic : "http://mysite.com/pic" , // optional + big : true , // optional + noForward : true , // optional + data : { some : "json" } // optional +}); + +kik.send("myFriend", { + title : "Message title" , + text : "Message body" , +}); + +if (kik.message) { + // your webpage was launched from a message + // kik.message is exactly what was provided in kik.send + // in this case: { some "json" } +} + +kik.openConversation("kikteam"); + +kik.metrics.enableGoogleAnalytics("id", "mydomain.com"); +kik.metrics.enableGoogleAnalytics(); +kik.showProfile("kikteam"); + +kik.pickUsers(function (users) { + if (!users) { + // action was cancelled by user + } else { + users.forEach(function (user) { + typeof user.username; // "string" + typeof user.fullName; // "string" + typeof user.firstName; // "string" + typeof user.lastName; // "string" + typeof user.pic; // "string" + typeof user.thumbnail; // "string" + }); + } +}); + +kik.pickUsers({ + minResults : 2 , // number >= 0 + maxResults : 4 // number > 0 +}, function (users) { + // do something with data +}); + +kik.pickUsers({ + preselected : [ + { username : "foo" /*, etc */ }, + // any user object obtained from previous call to pickUsers + ] +}, function (users) { + // do something with data +}); + +kik.pickUsers({ + filterSelf: false +}, function (users) { + // do something with data +}); + +kik.photo.get(function (photos) { + if (!photos) { + // action cancelled by user + } else { + // photos is a list of data URLs + } +}); + +kik.photo.get({ + quality : 0.7 , // number between 0-1 + minResults : 2 , // number between 1-25 + maxResults : 25 , // number between 1-25 + maxHeight : 1280 , // number in pixels between 0-1280 + maxWidth : 1280 , // number in pixels between 0-1280 +}, function (photos) { + // do something with the photos +}); + +kik.photo.getFromCamera({ + onSelect : function (numPhotos) { + // called immediately after the user has selected photos + // "numPhotos" is the number of photos selected by the user + // that many "onPhoto" events will be fired after this + // "onComplete" will fire after all "onPhoto" events are done + }, + onPhoto : function (photo, index) { + // "photo" is a data URL representing a single image + // "photo" may be null if there was an error in processing + // this will be called once for each image when it is ready + // "index" is an integer relating to the order of selection + // event may not come in order so use index if you care + }, + onComplete : function (photos) { + // "photos" is list of all photos from all photo events + // this event is identical to normal callback + }, + onCancel : function () { + // the action was cancelled by the user + // no other events will be called + } +}); + +kik.photo.get({ + quality : 0.7 , // number between 0-1 + minResults : 2 , // number between 1-25 + maxResults : 25 , // number between 1-25 + maxHeight : 1280 , // number in pixels between 0-1280 + maxWidth : 1280 , // number in pixels between 0-1280 +}, function (photos) { + // do something with the photos +}); + +kik.photo.getFromCamera({ + onSelect : function (numPhotos) { + // called immediately after the user has selected photos + // 'numPhotos' is the number of photos selected by the user + // that many 'onPhoto' events will be fired after this + // 'onComplete' will fire after all 'onPhoto' events are done + }, + onPhoto : function (photo, index) { + // 'photo' is a data URL representing a single image + // 'photo' may be null if there was an error in processing + // this will be called once for each image when it is ready + // 'index' is an integer relating to the order of selection + // event may not come in order so use index if you care + }, + onComplete : function (photos) { + // 'photos' is list of all photos from all photo events + // this event is identical to normal callback + }, + onCancel : function () { + // the action was cancelled by the user + // no other events will be called + } +}); + +kik.photo.getFromGallery(function (photos) { + // do something with the photos +}); + +kik.photo.saveToGallery("url", function (status) { + if (status) { + // save succeeded + } else { + // save failed + } +}); + +kik.picker( + "http://othersite.com/", + { arbitrary : "request data" }, + function (response) { + // do something with the picked data! + } +); + +if (kik.picker.reply) { + // webpage was launched in "picker mode" + // kik.picker.url === the url of the calling webpage + // kik.picker.data === { arbitrary : "request data" } + kik.picker.reply({ arbitrary : "response data" }); +} + +kik.ready(function () { + // expensive task that should not block loading +}); + +function handleBackButton () { + // called when back button is pressed + return false; // optionally cancel default behavior +} + +kik.browser.back(handleBackButton); // handle back button +kik.browser.unbindBack(handleBackButton); // unbind from handling back button + +kik.open("http://www.google.com/"); +kik.open("https://pop.kik.com/"); +kik.open("twitter://post"); + +kik.open("http://mysite.com/", true); // opens in popup mode + +kik.open("https://thirdparty.com/auth/page/path", true); + +kik.open("http://mysite.com/#response-data"); + +kik.linkData; // "response-data" + +kik.on("linkData", function () { + kik.linkData; // "response-data" +}); + +if (kik.browser.background) { + // the webpage is in the background +} + +kik.browser.on("background", function () { + // the webpage is now in the background +}); +kik.browser.on("foreground", function () { + // the webpage has returned to the foreground +}); + +// lock the orientation in landscape mode +kik.browser.setOrientationLock("landscape"); + +// unlock the orientation +kik.browser.setOrientationLock("free"); + +kik.browser.statusBar(false); // hide status bar +kik.browser.statusBar(true); // show status bar + +kik.formHelpers.show(); // show helpers +kik.formHelpers.hide(); // hide helpers +kik.formHelpers.isEnabled(); // check if enabled + +// backlight will not turn off as long +// as your webpage is visible to the user +kik.browser.backlightTimeout(false); + +// backlight will timeout as per OS rules +kik.browser.backlightTimeout(true); + +function eventHandler () { + // do something when event occurs +} + +// bind to event +kik.on("message", eventHandler); + +// unbind from event +kik.off("message", eventHandler); + +// bind to an event once (ignoring subsequent occurrences) +kik.once("message", eventHandler); + +kik.trigger("message", { + title : "Fake message" , + // object will be passed to all event listeners +}); + +let os = kik.utils.platform.os; +typeof os.name === "string"; // "ios", "android", "osx", "windows", etc +typeof os.version === "number"; // numeric version number + +let browser = kik.utils.platform.browser; +typeof browser.name === "string"; // "chrome", "safari", "opera", etc +typeof browser.version === "number"; // numeric version number + +let version = kik.utils.platform.version; +typeof browser.name === "string"; +typeof browser.version === "number"; // numeric version number \ No newline at end of file diff --git a/kik-browser/kik-browser.d.ts b/kik-browser/kik-browser.d.ts new file mode 100644 index 0000000000..3e183b0e21 --- /dev/null +++ b/kik-browser/kik-browser.d.ts @@ -0,0 +1,135 @@ +// Type definitions for Kik Cards v2.3.6 +// Project: https://dev.kik.com +// Definitions by: Joel Day +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Kik { + enabled: boolean; + message: KikMessage; + + send(user: string, message: KikMessage): void; + send(message: KikMessage): void; + ready(callback: () => void): void; + hasPermission(): boolean; + open(url: string, popupMode?: boolean): void; + on(property: string, eventHandler: () => void): void; + off(property: string, eventHandler: () => void): void; + once(property: string, eventHandler: () => void): void; + trigger(property: string, data?: any): void; + linkData: string; + getUser(callback: (user: KikUser) => void): void; + getAnonymousUser(callback: (token: string) => void): void; + sign(data: string, callback: (signedData: string, username: string, host: string) => void): void; + anonymousSign(data: string, callback: (signedData: string, anonToken: string, host: string) => void): void; + openConversation(username: string): void; + showProfile(username: string): void; + pickUsers(options: KikPickUsersOptions, callback: (users: KikUser[]) => void): void; + pickUsers(callback: (users: KikUser[]) => void): void; + + formHelpers: { + show(): void; + hide(): void; + isEnabled(): boolean; + }; + + metrics: { + enableGoogleAnalytics(): void; + enableGoogleAnalytics(trackingId: string, domain: string, oldApi?: boolean): void; + }; + + photo: { + get(options: KikGetOptions, callback: (photos: string[]) => void): void; + getFromCamera(callbacks: KikGetFromCameraCallbacks): void; + getFromCamera(options: KikGetFromCameraOptions, callbacks: KikGetFromCameraCallbacks): void; + getFromGallery(callback: (photos: string[]) => void): void; + getFromGallery(options: KikGetOptions, callback: (photos: string[]) => void): void; + saveToGallery(url: string, callback: (status: boolean) => void): void; + get(callback: (photos: string[]) => void): void; + }; + + picker: { + (url: string, data: any, callback: (response: any) => void): void; + reply: (data: any) => void; + }; + + browser: { + background: boolean; + back(callback: () => boolean | void): void; + unbindBack(callback: () => boolean | void): void; + on(property: string, callback: () => void): void; + off(property: string, callback: () => void): void; + once(property: string, callback: () => void): void; + trigger(property: string, data?: any): void; + getOrientationLock(): string; + setOrientationLock(lock: "free" | "landscape" | "portrait"): void; + setOrientationLock(lock: string): void; + statusBar(show: boolean): void; + backlightTimeout(timeout: boolean): void; + }; + + utils: { + platform: { + os: { + name: string; + version: string; + }; + browser: { + name: string; + version: string; + }; + version: { + name: string; + version: string; + }; + }; + }; +} + +interface KikUser { + username: string; + fullName: string; + firstName: string; + lastName: string; + pic: string; + thumbnail: string; +} + +interface KikMessage { + title: string; + text: string; + pic?: string; + big?: boolean; + noForward?: boolean; + data?: any; +} + +interface KikPickUsersOptions { + minResults?: number; + maxResults?: number; + preselected?: { username: string }[]; + filtered?: string[]; + filterSelf?: boolean; +} + +interface KikGetOptions { + quality?: number; + minResults?: number; + maxResults?: number; + maxHeight?: number; + maxWidth?: number; +} + +interface KikGetFromCameraOptions { + quality?: number; + maxHeight?: number; + maxWidth?: number; +} + +interface KikGetFromCameraCallbacks { + onSelect: (numPhotos: number) => void; + onPhoto: (photo: string, index: number) => void; + onComplete: (photos: string[]) => void; + onCancel: () => void; +} + +declare const kik: Kik; \ No newline at end of file diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 52740662c8..5aa1a46d18 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -3,11 +3,11 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +/// /// declare module "knex" { - // import Promise = require("bluebird"); + import Promise = require("bluebird"); import * as events from "events"; type Callback = Function; @@ -299,8 +299,8 @@ declare module "knex" { // Schema builder // - interface SchemaBuilder { - createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; + interface SchemaBuilder extends Promise { + createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; dropTable(tableName: string): Promise; hasTable(tableName: string): Promise; @@ -339,6 +339,7 @@ declare module "knex" { unique(columnNames: string[], indexName?: string) : TableBuilder; foreign(column: string): ForeignConstraintBuilder; foreign(columns: string[]): MultikeyForeignConstraintBuilder; + dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; } interface CreateTableBuilder extends TableBuilder { diff --git a/knockout.deferred.updates/knockout.deferred.updates-tests.ts b/knockout.deferred.updates/knockout.deferred.updates-tests.ts deleted file mode 100644 index 060ff3984a..0000000000 --- a/knockout.deferred.updates/knockout.deferred.updates-tests.ts +++ /dev/null @@ -1,252 +0,0 @@ -/// - -// Turn *off* deferred updates for computed observables and subscriptions -ko.computed.deferUpdates = false; - -var myComputed = ko.computed(() => { /* ... */ }); -// Turn *on* deferred updates for this computed observable -myComputed.deferUpdates = true; - -var myObservable = ko.observable(); -var mySubscription = myObservable.subscribe((value) => { /* ... */ }); -// Turn *on* deferred updates for this subscription -mySubscription.deferUpdates = true; - -// Turn *off* deferred updates for this computed observable -myComputed.extend({ deferred: false }); - - -// -// Examples -// - -function nestedComputedNoPlugin() { - var vm: any = { - a: ko.observable(0), - b: ko.observable(0), - c: ko.observable(0), - d: ko.observable(0), - e: ko.observable(0), - f: ko.observable(0) - }; - - var startTime = new Date().getTime(); - var updateArray = []; - - function firstUpdate() { - var updateList = document.getElementById('updates'); - while (updateList.firstChild) updateList.removeChild(updateList.firstChild); - } - - function pushUpdate(name, value, color) { - var li = document.createElement('li'); - li.appendChild(document.createTextNode(name + ' ' + value + '; ' + (new Date().getTime() - startTime) + ' ms')); - li.style.color = color; - document.getElementById('updates').appendChild(li); - } - - function lastUpdate() { - } - - var updateCounter = 0, plusminus = 1; - - vm.doUpdate = function () { - var u = updateCounter += plusminus; - startTime = new Date().getTime(); - vm.a(u); - vm.b(u); - vm.c(u); - vm.d(u); - vm.e(u); - vm.f(u); - plusminus = !u ? 1 : (u == 9) ? -1 : plusminus; - }; - - vm.setThrottle = function (value) { - vm.A.throttleEvaluation = value; - vm._B.throttleEvaluation = value; - vm.C.throttleEvaluation = value; - vm.D.throttleEvaluation = value; - vm.E.throttleEvaluation = value; - vm.F.throttleEvaluation = value; - }; - - vm.runNormal = function () { - ko.computed.deferUpdates = false; - vm.setThrottle(undefined); - vm.doUpdate(); - }; - - vm.runThrottle = function () { - ko.computed.deferUpdates = false; - vm.setThrottle(1); - vm.doUpdate(); - }; - - vm.A = ko.computed(function () { - var result = '' + vm.a(); - firstUpdate(); - pushUpdate('A', result, 'green'); - return result; - }, null, { deferEvaluation: true }); - - vm._B = ko.computed(function () { - var result = '' + vm.A() + vm.b(); - pushUpdate('B', result, 'darkturquoise'); - return result; - }, null, { deferEvaluation: true }); - - vm.C = ko.computed(function () { - var result = '' + vm._B() + vm.c(); - pushUpdate('C', result, 'royalblue'); - return result; - }, null, { deferEvaluation: true }); - - vm.D = ko.computed(function () { - var result = '' + vm.C() + vm.d(); - pushUpdate('D', result, 'indigo'); - return result; - }, null, { deferEvaluation: true }); - - vm.E = ko.computed(function () { - var result = '' + vm.D() + vm.e(); - pushUpdate('E', result, 'firebrick'); - return result; - }, null, { deferEvaluation: true }); - - vm.F = ko.computed(function () { - var f = vm.f(), result = '' + vm.E() + f; - pushUpdate('F', result, 'orangered'); - if (result === '' + f + f + f + f + f + f) lastUpdate(); - return result; - }, null, { deferEvaluation: true }); - - vm.A(); - vm._B(); - vm.C(); - vm.D(); - vm.E(); - vm.F(); - - ko.applyBindings(vm); -}; - -function nestedComputedPlugin() { - var vm: any = { - a: ko.observable(0), - b: ko.observable(0), - c: ko.observable(0), - d: ko.observable(0), - e: ko.observable(0), - f: ko.observable(0) - }; - - var startTime = new Date().getTime(); - var updateArray = []; - - function firstUpdate() { - var updateList = document.getElementById('updates'); - while (updateList.firstChild) - updateList.removeChild(updateList.firstChild); - } - - function pushUpdate(name, value, color) { - var li = document.createElement('li'); - li.appendChild(document.createTextNode(name + ' ' + value + '; ' + (new Date().getTime() - startTime) + ' ms')); - li.style.color = color; - document.getElementById('updates').appendChild(li); - } - - function lastUpdate() { - } - - var updateCounter = 0, plusminus = 1; - - vm.doUpdate = function () { - var u = updateCounter += plusminus; - startTime = new Date().getTime(); - vm.a(u); - vm.b(u); - vm.c(u); - vm.d(u); - vm.e(u); - vm.f(u); - plusminus = !u ? 1 : (u == 9) ? -1 : plusminus; - }; - - vm.setThrottle = function (value) { - vm.A.throttleEvaluation = value; - vm._B.throttleEvaluation = value; - vm.C.throttleEvaluation = value; - vm.D.throttleEvaluation = value; - vm.E.throttleEvaluation = value; - vm.F.throttleEvaluation = value; - }; - - vm.runNormal = function () { - ko.computed.deferUpdates = false; - vm.setThrottle(undefined); - vm.doUpdate(); - }; - - vm.runThrottle = function () { - ko.computed.deferUpdates = false; - vm.setThrottle(1); - vm.doUpdate(); - }; - - vm.runDefer = function () { - ko.computed.deferUpdates = true; - vm.setThrottle(undefined); - vm.doUpdate(); - }; - - vm.runWrappedDefer = ko.tasks.makeProcessedCallback(vm.runDefer); - - vm.A = ko.computed(function () { - var result = '' + vm.a(); - firstUpdate(); - pushUpdate('A', result, 'green'); - return result; - }, null, { deferEvaluation: true }); - - vm._B = ko.computed(function () { - var result = '' + vm.A() + vm.b(); - pushUpdate('B', result, 'darkturquoise'); - return result; - }, null, { deferEvaluation: true }); - - vm.C = ko.computed(function () { - var result = '' + vm._B() + vm.c(); - pushUpdate('C', result, 'royalblue'); - return result; - }, null, { deferEvaluation: true }); - - vm.D = ko.computed(function () { - var result = '' + vm.C() + vm.d(); - pushUpdate('D', result, 'indigo'); - return result; - }, null, { deferEvaluation: true }); - - vm.E = ko.computed(function () { - var result = '' + vm.D() + vm.e(); - pushUpdate('E', result, 'firebrick'); - return result; - }, null, { deferEvaluation: true }); - - vm.F = ko.computed(function () { - var f = vm.f(), result = '' + vm.E() + f; - pushUpdate('F', result, 'orangered'); - if (result === '' + f + f + f + f + f + f) lastUpdate(); - return result; - }, null, { deferEvaluation: true }); - - vm.A(); - vm._B(); - vm.C(); - vm.D(); - vm.E(); - vm.F(); - - ko.applyBindings(vm); -} diff --git a/knockout.deferred.updates/knockout.deferred.updates-tests.ts.tscparams b/knockout.deferred.updates/knockout.deferred.updates-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/knockout.deferred.updates/knockout.deferred.updates-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/knockout.deferred.updates/knockout.deferred.updates.d.ts b/knockout.deferred.updates/knockout.deferred.updates.d.ts deleted file mode 100644 index d3c5d7b40d..0000000000 --- a/knockout.deferred.updates/knockout.deferred.updates.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Type definitions for Knockout Deferred Updates -// Project: https://github.com/mbest/knockout-deferred-updates -// Definitions by: Sebastián Galiano -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface KnockoutDeferredTasks { - processImmediate(evaluator: Function, object?: any, args?: any[]): any; - processDelayed(evaluator: Function, distinct?: boolean, options?: any[]): boolean; - makeProcessedCallback(evaluator: Function): void; -} - -// Knockout global -interface KnockoutStatic { - tasks: KnockoutDeferredTasks; - processAllDeferredBindingUpdates(): void; - processAllDeferredUpdates(): void; - evaluateAsynchronously(evaluator: Function, timeout?: any): number; - ignoreDependencies(callback: Function, callbackTarget: any, callbackArgs?: any[]); -} - -// Observables -interface KnockoutSubscribableFunctions { - deferUpdates: boolean; -} - -// Computed -interface KnockoutComputedStatic { - deferUpdates: boolean; -} - -interface KnockoutSubscription { - deferUpdates: boolean; -} - -// Utils -interface KnockoutUtils { - objectForEach(obj: any, action: Function): void; - objectMap(source: any, mapping: Function): any; -} - -// Deferred extender -interface KnockoutExtenders { - deferred(target: any, value: boolean): any; -} \ No newline at end of file diff --git a/knockout.deferred.updates/knockout.deferred.updates.d.ts.tscparams b/knockout.deferred.updates/knockout.deferred.updates.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/knockout.deferred.updates/knockout.deferred.updates.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/knockout.validation/knockout.validation.d.ts b/knockout.validation/knockout.validation.d.ts index 40a8a83d4f..df4cdade1c 100644 --- a/knockout.validation/knockout.validation.d.ts +++ b/knockout.validation/knockout.validation.d.ts @@ -6,22 +6,95 @@ /// interface KnockoutValidationGroupingOptions { + /** + * indicates whether to walk the ViewModel (or object) + * recursively, or only walk first-level properties. + */ deep?: boolean; + /** + * indicates whether the returned errors object + * is a ko.computed or a simple function + */ observable?: boolean; + /** + * indicates whether changes to observableArrays inside + * the model should cause the validator to re-run + */ + live?: boolean; +} + +interface KnockoutValidationValidateOptions { + throttle?: number; } interface KnockoutValidationConfiguration { - registerExtenders?: boolean; - messagesOnModified?: boolean; - messageTemplate?: string; - insertMessages?: boolean; - parseInputAttributes?: boolean; - writeInputAttributes?: boolean; + /** + * Allows HTML in validation messages + */ + allowHtmlMessages?: boolean; + /** + * Indicates whether css error classes are added only + * when properties are modified or at all times + * @type {[type]} + */ + decorateElementOnModified?: boolean; + /** + * Indicates whether to assign an error class to the tag + * when your property is invalid + */ decorateInputElement?: boolean; + /** + * If defined, the CSS class assigned to both and validation message elements + */ errorClass?: string; + /** + * The CSS class assigned to validation error elements, must have decorateInputElement set to true + */ errorElementClass?: string; + /** + * The CSS class assigned to validation error messages + */ errorMessageClass?: string; + /** + * Shows tooltips using input 'title' attribute. False hides them + */ + errorsAsTitle?: boolean; + /** + * Shows the error when hovering the input field (decorateElement must be true) + */ + errorsAsTitleOnModified?: boolean; grouping?: KnockoutValidationGroupingOptions; + /** + * If true validation will insert either a element or the template + * specified by messageTemplate after any element (e.g. ) + * that uses a KO value binding with a validated field + */ + insertMessages?: boolean; + /** + * Indicates whether validation messages are triggered only + * when properties are modified or at all times + */ + messagesOnModified?: boolean; + /** + * The id of the + * that you want to use for all your validation messages + */ + messageTemplate?: string; + /** + * Indicates whether to assign validation rules to your ViewModel + * using HTML5 validation attributes + */ + parseInputAttributes?: boolean; + /** + * Register custom validation rules defined via ko.validation.rules + */ + registerExtenders?: boolean; + validate?: KnockoutValidationValidateOptions; + /** + * Add HTML5 input validation attributes to form elements + * that ko observable's are bound to + */ + writeInputAttributes?: boolean; } interface KnockoutValidationUtils { @@ -154,7 +227,7 @@ interface KnockoutSubscribableFunctions { } declare module "knockout.validation" { - export = validation; + export = validation; } -declare var validation: KnockoutValidationStatic +declare var validation: KnockoutValidationStatic diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 962a776333..6e53ac2e25 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Knockout v3.2.0 +// Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov , Igor Oleinikov , Clément Bourgeois +// Definitions by: Boris Yankov , Igor Oleinikov , Clément Bourgeois , Matt Brooks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -387,6 +387,17 @@ interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { rewriteTemplate(template: any, rewriterCallback: Function, templateDocument: Document): void; } +////////////////////////////////// +// tasks.js +////////////////////////////////// + +interface KnockoutTasks { + scheduler: (callback: Function) => any; + schedule(task: Function): number; + cancel(handle: number): void; + runEarly(): void; +} + ///////////////////////////////// interface KnockoutStatic { @@ -544,7 +555,13 @@ interface KnockoutStatic { deferUpdates: boolean, useOnlyNativeEvents: boolean - } + }; + + ///////////////////////////////// + // tasks.js + ///////////////////////////////// + + tasks: KnockoutTasks; } interface KnockoutBindingProvider { diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index e9334a7534..8da6c12950 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -570,8 +570,8 @@ function test_misc() { $(element).datepicker("destroy"); }); - this.observableFactory = function(): KnockoutObservable{ - if (true) { + this.observableFactory = function(flag = true): KnockoutObservable{ + if (flag) { return ko.computed({ read:function(){ return 3; @@ -655,3 +655,28 @@ function testUnwrapUnion() { var num = ko.unwrap(possibleObs); } + +function test_tasks() { + // Schedule an empty task + ko.tasks.schedule(function() { + }); + + // Schedule a task with arguments and return type + let logSomethingTask = (message: string) => { + console.log("Log message"); + return true; + }; + + let taskHandle = ko.tasks.schedule(logSomethingTask); + + // Cancel a task + ko.tasks.cancel(taskHandle); + + // Process the current microtask queue on demand + ko.tasks.runEarly(); + + // Redefine or augment how Knockout schedules the event to process and flush the queue + ko.tasks.scheduler = function (callback) { + setTimeout(callback, 0); + }; +} diff --git a/kolite/knockout.activity.d.ts b/kolite/knockout.activity.d.ts index c5d876f630..02d7e75f37 100644 --- a/kolite/knockout.activity.d.ts +++ b/kolite/knockout.activity.d.ts @@ -28,8 +28,18 @@ interface KoLiteActivity { getOpacity(options: { steps?: number; segments?: number; opacity?: number; }, i: number): number; } +interface KoLiteActivityDefaultOptions { + activityClass?: string, + container?: string, + inactiveClass?: string +} + +interface KoLiteActivityBindingHandler extends KnockoutBindingHandler { + defaultOptions: KoLiteActivityDefaultOptions +} + interface KnockoutBindingHandlers { - activity: KnockoutBindingHandler; + activity: KoLiteActivityBindingHandler; } interface JQuery { diff --git a/kolite/kolite-tests.ts b/kolite/kolite-tests.ts index a7b6d08f01..8cafcf6946 100644 --- a/kolite/kolite-tests.ts +++ b/kolite/kolite-tests.ts @@ -2,6 +2,20 @@ /// /// +function test_activityDefaults() { + ko.bindingHandlers.activity.defaultOptions = { + activityClass: 'fa fa-spinner fa-spin', + container: 'i', + inactiveClass: '' + }; + + ko.bindingHandlers.activity.defaultOptions = { + activityClass: 'some Value' + }; + + ko.bindingHandlers.activity.defaultOptions = { + }; +} function test_asyncCommand() { var saveCmd = ko.asyncCommand({ execute: function (complete) { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 0e506e9597..1e39d223f0 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1,6 +1,6 @@ // Type definitions for Lo-Dash // Project: http://lodash.com/ -// Definitions by: Brian Zengel , Ilya Mochalov +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18961,6 +18961,1842 @@ declare module _ { } } +// Named exports + +declare module "lodash/after" { + const after: typeof _.after; + export = after; +} + + +declare module "lodash/ary" { + const ary: typeof _.ary; + export = ary; +} + + +declare module "lodash/assign" { + const assign: typeof _.assign; + export = assign; +} + + +declare module "lodash/assignIn" { + const assignIn: typeof _.assignIn; + export = assignIn; +} + + +declare module "lodash/assignInWith" { + const assignInWith: typeof _.assignInWith; + export = assignInWith; +} + + +declare module "lodash/assignWith" { + const assignWith: typeof _.assignWith; + export = assignWith; +} + + +declare module "lodash/at" { + const at: typeof _.at; + export = at; +} + + +declare module "lodash/before" { + const before: typeof _.before; + export = before; +} + + +declare module "lodash/bind" { + const bind: typeof _.bind; + export = bind; +} + + +declare module "lodash/bindAll" { + const bindAll: typeof _.bindAll; + export = bindAll; +} + + +declare module "lodash/bindKey" { + const bindKey: typeof _.bindKey; + export = bindKey; +} + + +declare module "lodash/castArray" { + const castArray: typeof _.castArray; + export = castArray; +} + + +declare module "lodash/chain" { + const chain: typeof _.chain; + export = chain; +} + + +declare module "lodash/chunk" { + const chunk: typeof _.chunk; + export = chunk; +} + + +declare module "lodash/compact" { + const compact: typeof _.compact; + export = compact; +} + + +declare module "lodash/concat" { + const concat: typeof _.concat; + export = concat; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/cond" { + const cond: typeof _.cond; + export = cond; +} +*/ + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/conforms" { + const conforms: typeof _.conforms; + export = conforms; +} +*/ + +declare module "lodash/constant" { + const constant: typeof _.constant; + export = constant; +} + + +declare module "lodash/countBy" { + const countBy: typeof _.countBy; + export = countBy; +} + + +declare module "lodash/create" { + const create: typeof _.create; + export = create; +} + + +declare module "lodash/curry" { + const curry: typeof _.curry; + export = curry; +} + + +declare module "lodash/curryRight" { + const curryRight: typeof _.curryRight; + export = curryRight; +} + + +declare module "lodash/debounce" { + const debounce: typeof _.debounce; + export = debounce; +} + + +declare module "lodash/defaults" { + const defaults: typeof _.defaults; + export = defaults; +} + + +declare module "lodash/defaultsDeep" { + const defaultsDeep: typeof _.defaultsDeep; + export = defaultsDeep; +} + + +declare module "lodash/defer" { + const defer: typeof _.defer; + export = defer; +} + + +declare module "lodash/delay" { + const delay: typeof _.delay; + export = delay; +} + + +declare module "lodash/difference" { + const difference: typeof _.difference; + export = difference; +} + + +declare module "lodash/differenceBy" { + const differenceBy: typeof _.differenceBy; + export = differenceBy; +} + + +declare module "lodash/differenceWith" { + const differenceWith: typeof _.differenceWith; + export = differenceWith; +} + + +declare module "lodash/drop" { + const drop: typeof _.drop; + export = drop; +} + + +declare module "lodash/dropRight" { + const dropRight: typeof _.dropRight; + export = dropRight; +} + + +declare module "lodash/dropRightWhile" { + const dropRightWhile: typeof _.dropRightWhile; + export = dropRightWhile; +} + + +declare module "lodash/dropWhile" { + const dropWhile: typeof _.dropWhile; + export = dropWhile; +} + + +declare module "lodash/fill" { + const fill: typeof _.fill; + export = fill; +} + + +declare module "lodash/filter" { + const filter: typeof _.filter; + export = filter; +} + + +declare module "lodash/flatMap" { + const flatMap: typeof _.flatMap; + export = flatMap; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/flatMapDeep" { + const flatMapDeep: typeof _.flatMapDeep; + export = flatMapDeep; +} +*/ +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/flatMapDepth" { + const flatMapDepth: typeof _.flatMapDepth; + export = flatMapDepth; +} +*/ + +declare module "lodash/flatten" { + const flatten: typeof _.flatten; + export = flatten; +} + + +declare module "lodash/flattenDeep" { + const flattenDeep: typeof _.flattenDeep; + export = flattenDeep; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/flattenDepth" { + const flattenDepth: typeof _.flattenDepth; + export = flattenDepth; +} +*/ + +declare module "lodash/flip" { + const flip: typeof _.flip; + export = flip; +} + + +declare module "lodash/flow" { + const flow: typeof _.flow; + export = flow; +} + + +declare module "lodash/flowRight" { + const flowRight: typeof _.flowRight; + export = flowRight; +} + + +declare module "lodash/fromPairs" { + const fromPairs: typeof _.fromPairs; + export = fromPairs; +} + + +declare module "lodash/functions" { + const functions: typeof _.functions; + export = functions; +} + + +declare module "lodash/functionsIn" { + const functionsIn: typeof _.functionsIn; + export = functionsIn; +} + + +declare module "lodash/groupBy" { + const groupBy: typeof _.groupBy; + export = groupBy; +} + + +declare module "lodash/initial" { + const initial: typeof _.initial; + export = initial; +} + + +declare module "lodash/intersection" { + const intersection: typeof _.intersection; + export = intersection; +} + + +declare module "lodash/intersectionBy" { + const intersectionBy: typeof _.intersectionBy; + export = intersectionBy; +} + + +declare module "lodash/intersectionWith" { + const intersectionWith: typeof _.intersectionWith; + export = intersectionWith; +} + + +declare module "lodash/invert" { + const invert: typeof _.invert; + export = invert; +} + + +declare module "lodash/invertBy" { + const invertBy: typeof _.invertBy; + export = invertBy; +} + + +declare module "lodash/invokeMap" { + const invokeMap: typeof _.invokeMap; + export = invokeMap; +} + + +declare module "lodash/iteratee" { + const iteratee: typeof _.iteratee; + export = iteratee; +} + + +declare module "lodash/keyBy" { + const keyBy: typeof _.keyBy; + export = keyBy; +} + + +declare module "lodash/keys" { + const keys: typeof _.keys; + export = keys; +} + + +declare module "lodash/keysIn" { + const keysIn: typeof _.keysIn; + export = keysIn; +} + + +declare module "lodash/map" { + const map: typeof _.map; + export = map; +} + + +declare module "lodash/mapKeys" { + const mapKeys: typeof _.mapKeys; + export = mapKeys; +} + + +declare module "lodash/mapValues" { + const mapValues: typeof _.mapValues; + export = mapValues; +} + + +declare module "lodash/matches" { + const matches: typeof _.matches; + export = matches; +} + + +declare module "lodash/matchesProperty" { + const matchesProperty: typeof _.matchesProperty; + export = matchesProperty; +} + + +declare module "lodash/memoize" { + const memoize: typeof _.memoize; + export = memoize; +} + + +declare module "lodash/merge" { + const merge: typeof _.merge; + export = merge; +} + + +declare module "lodash/mergeWith" { + const mergeWith: typeof _.mergeWith; + export = mergeWith; +} + + +declare module "lodash/method" { + const method: typeof _.method; + export = method; +} + + +declare module "lodash/methodOf" { + const methodOf: typeof _.methodOf; + export = methodOf; +} + + +declare module "lodash/mixin" { + const mixin: typeof _.mixin; + export = mixin; +} + + +declare module "lodash/negate" { + const negate: typeof _.negate; + export = negate; +} + + +declare module "lodash/nthArg" { + const nthArg: typeof _.nthArg; + export = nthArg; +} + + +declare module "lodash/omit" { + const omit: typeof _.omit; + export = omit; +} + + +declare module "lodash/omitBy" { + const omitBy: typeof _.omitBy; + export = omitBy; +} + + +declare module "lodash/once" { + const once: typeof _.once; + export = once; +} + + +declare module "lodash/orderBy" { + const orderBy: typeof _.orderBy; + export = orderBy; +} + + +declare module "lodash/over" { + const over: typeof _.over; + export = over; +} + + +declare module "lodash/overArgs" { + const overArgs: typeof _.overArgs; + export = overArgs; +} + + +declare module "lodash/overEvery" { + const overEvery: typeof _.overEvery; + export = overEvery; +} + + +declare module "lodash/overSome" { + const overSome: typeof _.overSome; + export = overSome; +} + + +declare module "lodash/partial" { + const partial: typeof _.partial; + export = partial; +} + + +declare module "lodash/partialRight" { + const partialRight: typeof _.partialRight; + export = partialRight; +} + + +declare module "lodash/partition" { + const partition: typeof _.partition; + export = partition; +} + + +declare module "lodash/pick" { + const pick: typeof _.pick; + export = pick; +} + + +declare module "lodash/pickBy" { + const pickBy: typeof _.pickBy; + export = pickBy; +} + + +declare module "lodash/property" { + const property: typeof _.property; + export = property; +} + + +declare module "lodash/propertyOf" { + const propertyOf: typeof _.propertyOf; + export = propertyOf; +} + + +declare module "lodash/pull" { + const pull: typeof _.pull; + export = pull; +} + + +declare module "lodash/pullAll" { + const pullAll: typeof _.pullAll; + export = pullAll; +} + + +declare module "lodash/pullAllBy" { + const pullAllBy: typeof _.pullAllBy; + export = pullAllBy; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/pullAllWith" { + const pullAllWith: typeof _.pullAllWith; + export = pullAllWith; +} +*/ + +declare module "lodash/pullAt" { + const pullAt: typeof _.pullAt; + export = pullAt; +} + + +declare module "lodash/range" { + const range: typeof _.range; + export = range; +} + + +declare module "lodash/rangeRight" { + const rangeRight: typeof _.rangeRight; + export = rangeRight; +} + + +declare module "lodash/rearg" { + const rearg: typeof _.rearg; + export = rearg; +} + + +declare module "lodash/reject" { + const reject: typeof _.reject; + export = reject; +} + + +declare module "lodash/remove" { + const remove: typeof _.remove; + export = remove; +} + + +declare module "lodash/rest" { + const rest: typeof _.rest; + export = rest; +} + + +declare module "lodash/reverse" { + const reverse: typeof _.reverse; + export = reverse; +} + + +declare module "lodash/sampleSize" { + const sampleSize: typeof _.sampleSize; + export = sampleSize; +} + + +declare module "lodash/set" { + const set: typeof _.set; + export = set; +} + + +declare module "lodash/setWith" { + const setWith: typeof _.setWith; + export = setWith; +} + + +declare module "lodash/shuffle" { + const shuffle: typeof _.shuffle; + export = shuffle; +} + + +declare module "lodash/slice" { + const slice: typeof _.slice; + export = slice; +} + + +declare module "lodash/sortBy" { + const sortBy: typeof _.sortBy; + export = sortBy; +} + + +declare module "lodash/sortedUniq" { + const sortedUniq: typeof _.sortedUniq; + export = sortedUniq; +} + + +declare module "lodash/sortedUniqBy" { + const sortedUniqBy: typeof _.sortedUniqBy; + export = sortedUniqBy; +} + + +declare module "lodash/split" { + const split: typeof _.split; + export = split; +} + + +declare module "lodash/spread" { + const spread: typeof _.spread; + export = spread; +} + + +declare module "lodash/tail" { + const tail: typeof _.tail; + export = tail; +} + + +declare module "lodash/take" { + const take: typeof _.take; + export = take; +} + + +declare module "lodash/takeRight" { + const takeRight: typeof _.takeRight; + export = takeRight; +} + + +declare module "lodash/takeRightWhile" { + const takeRightWhile: typeof _.takeRightWhile; + export = takeRightWhile; +} + + +declare module "lodash/takeWhile" { + const takeWhile: typeof _.takeWhile; + export = takeWhile; +} + + +declare module "lodash/tap" { + const tap: typeof _.tap; + export = tap; +} + + +declare module "lodash/throttle" { + const throttle: typeof _.throttle; + export = throttle; +} + + +declare module "lodash/thru" { + const thru: typeof _.thru; + export = thru; +} + + +declare module "lodash/toArray" { + const toArray: typeof _.toArray; + export = toArray; +} + + +declare module "lodash/toPairs" { + const toPairs: typeof _.toPairs; + export = toPairs; +} + + +declare module "lodash/toPairsIn" { + const toPairsIn: typeof _.toPairsIn; + export = toPairsIn; +} + + +declare module "lodash/toPath" { + const toPath: typeof _.toPath; + export = toPath; +} + + +declare module "lodash/toPlainObject" { + const toPlainObject: typeof _.toPlainObject; + export = toPlainObject; +} + + +declare module "lodash/transform" { + const transform: typeof _.transform; + export = transform; +} + + +declare module "lodash/unary" { + const unary: typeof _.unary; + export = unary; +} + + +declare module "lodash/union" { + const union: typeof _.union; + export = union; +} + + +declare module "lodash/unionBy" { + const unionBy: typeof _.unionBy; + export = unionBy; +} + + +declare module "lodash/unionWith" { + const unionWith: typeof _.unionWith; + export = unionWith; +} + + +declare module "lodash/uniq" { + const uniq: typeof _.uniq; + export = uniq; +} + + +declare module "lodash/uniqBy" { + const uniqBy: typeof _.uniqBy; + export = uniqBy; +} + + +declare module "lodash/uniqWith" { + const uniqWith: typeof _.uniqWith; + export = uniqWith; +} + + +declare module "lodash/unset" { + const unset: typeof _.unset; + export = unset; +} + + +declare module "lodash/unzip" { + const unzip: typeof _.unzip; + export = unzip; +} + + +declare module "lodash/unzipWith" { + const unzipWith: typeof _.unzipWith; + export = unzipWith; +} + + +declare module "lodash/update" { + const update: typeof _.update; + export = update; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/updateWith" { + const updateWith: typeof _.updateWith; + export = updateWith; +} +*/ + +declare module "lodash/values" { + const values: typeof _.values; + export = values; +} + + +declare module "lodash/valuesIn" { + const valuesIn: typeof _.valuesIn; + export = valuesIn; +} + + +declare module "lodash/without" { + const without: typeof _.without; + export = without; +} + + +declare module "lodash/words" { + const words: typeof _.words; + export = words; +} + + +declare module "lodash/wrap" { + const wrap: typeof _.wrap; + export = wrap; +} + + +declare module "lodash/xor" { + const xor: typeof _.xor; + export = xor; +} + + +declare module "lodash/xorBy" { + const xorBy: typeof _.xorBy; + export = xorBy; +} + + +declare module "lodash/xorWith" { + const xorWith: typeof _.xorWith; + export = xorWith; +} + + +declare module "lodash/zip" { + const zip: typeof _.zip; + export = zip; +} + + +declare module "lodash/zipObject" { + const zipObject: typeof _.zipObject; + export = zipObject; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/zipObjectDeep" { + const zipObjectDeep: typeof _.zipObjectDeep; + export = zipObjectDeep; +} +*/ + + +declare module "lodash/zipWith" { + const zipWith: typeof _.zipWith; + export = zipWith; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/entries" { + const entries: typeof _.entries; + export = entries; +} +*/ +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/entriesIn" { + const entriesIn: typeof _.entriesIn; + export = entriesIn; +} +*/ + + +declare module "lodash/extend" { + const extend: typeof _.extend; + export = extend; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/extendWith" { + const extendWith: typeof _.extendWith; + export = extendWith; +} +*/ + +declare module "lodash/add" { + const add: typeof _.add; + export = add; +} + + +declare module "lodash/attempt" { + const attempt: typeof _.attempt; + export = attempt; +} + + +declare module "lodash/camelCase" { + const camelCase: typeof _.camelCase; + export = camelCase; +} + + +declare module "lodash/capitalize" { + const capitalize: typeof _.capitalize; + export = capitalize; +} + + +declare module "lodash/ceil" { + const ceil: typeof _.ceil; + export = ceil; +} + + +declare module "lodash/clamp" { + const clamp: typeof _.clamp; + export = clamp; +} + + +declare module "lodash/clone" { + const clone: typeof _.clone; + export = clone; +} + + +declare module "lodash/cloneDeep" { + const cloneDeep: typeof _.cloneDeep; + export = cloneDeep; +} + + +declare module "lodash/cloneDeepWith" { + const cloneDeepWith: typeof _.cloneDeepWith; + export = cloneDeepWith; +} + + +declare module "lodash/cloneWith" { + const cloneWith: typeof _.cloneWith; + export = cloneWith; +} + + +declare module "lodash/deburr" { + const deburr: typeof _.deburr; + export = deburr; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/divide" { + const divide: typeof _.divide; + export = divide; +} +*/ + +declare module "lodash/endsWith" { + const endsWith: typeof _.endsWith; + export = endsWith; +} + + +declare module "lodash/eq" { + const eq: typeof _.eq; + export = eq; +} + + +declare module "lodash/escape" { + const escape: typeof _.escape; + export = escape; +} + + +declare module "lodash/escapeRegExp" { + const escapeRegExp: typeof _.escapeRegExp; + export = escapeRegExp; +} + + +declare module "lodash/every" { + const every: typeof _.every; + export = every; +} + + +declare module "lodash/find" { + const find: typeof _.find; + export = find; +} + + +declare module "lodash/findIndex" { + const findIndex: typeof _.findIndex; + export = findIndex; +} + + +declare module "lodash/findKey" { + const findKey: typeof _.findKey; + export = findKey; +} + + +declare module "lodash/findLast" { + const findLast: typeof _.findLast; + export = findLast; +} + + +declare module "lodash/findLastIndex" { + const findLastIndex: typeof _.findLastIndex; + export = findLastIndex; +} + + +declare module "lodash/findLastKey" { + const findLastKey: typeof _.findLastKey; + export = findLastKey; +} + + +declare module "lodash/floor" { + const floor: typeof _.floor; + export = floor; +} + + +declare module "lodash/forEach" { + const forEach: typeof _.forEach; + export = forEach; +} + + +declare module "lodash/forEachRight" { + const forEachRight: typeof _.forEachRight; + export = forEachRight; +} + + +declare module "lodash/forIn" { + const forIn: typeof _.forIn; + export = forIn; +} + + +declare module "lodash/forInRight" { + const forInRight: typeof _.forInRight; + export = forInRight; +} + + +declare module "lodash/forOwn" { + const forOwn: typeof _.forOwn; + export = forOwn; +} + + +declare module "lodash/forOwnRight" { + const forOwnRight: typeof _.forOwnRight; + export = forOwnRight; +} + + +declare module "lodash/get" { + const get: typeof _.get; + export = get; +} + + +declare module "lodash/gt" { + const gt: typeof _.gt; + export = gt; +} + + +declare module "lodash/gte" { + const gte: typeof _.gte; + export = gte; +} + + +declare module "lodash/has" { + const has: typeof _.has; + export = has; +} + + +declare module "lodash/hasIn" { + const hasIn: typeof _.hasIn; + export = hasIn; +} + + +declare module "lodash/head" { + const head: typeof _.head; + export = head; +} + + +declare module "lodash/identity" { + const identity: typeof _.identity; + export = identity; +} + + +declare module "lodash/includes" { + const includes: typeof _.includes; + export = includes; +} + + +declare module "lodash/indexOf" { + const indexOf: typeof _.indexOf; + export = indexOf; +} + + +declare module "lodash/inRange" { + const inRange: typeof _.inRange; + export = inRange; +} + + +declare module "lodash/invoke" { + const invoke: typeof _.invoke; + export = invoke; +} + + +declare module "lodash/isArguments" { + const isArguments: typeof _.isArguments; + export = isArguments; +} + + +declare module "lodash/isArray" { + const isArray: typeof _.isArray; + export = isArray; +} + + +declare module "lodash/isArrayBuffer" { + const isArrayBuffer: typeof _.isArrayBuffer; + export = isArrayBuffer; +} + + +declare module "lodash/isArrayLike" { + const isArrayLike: typeof _.isArrayLike; + export = isArrayLike; +} + + +declare module "lodash/isArrayLikeObject" { + const isArrayLikeObject: typeof _.isArrayLikeObject; + export = isArrayLikeObject; +} + + +declare module "lodash/isBoolean" { + const isBoolean: typeof _.isBoolean; + export = isBoolean; +} + + +declare module "lodash/isBuffer" { + const isBuffer: typeof _.isBuffer; + export = isBuffer; +} + + +declare module "lodash/isDate" { + const isDate: typeof _.isDate; + export = isDate; +} + + +declare module "lodash/isElement" { + const isElement: typeof _.isElement; + export = isElement; +} + + +declare module "lodash/isEmpty" { + const isEmpty: typeof _.isEmpty; + export = isEmpty; +} + + +declare module "lodash/isEqual" { + const isEqual: typeof _.isEqual; + export = isEqual; +} + + +declare module "lodash/isEqualWith" { + const isEqualWith: typeof _.isEqualWith; + export = isEqualWith; +} + + +declare module "lodash/isError" { + const isError: typeof _.isError; + export = isError; +} + + +declare module "lodash/isFinite" { + const isFinite: typeof _.isFinite; + export = isFinite; +} + + +declare module "lodash/isFunction" { + const isFunction: typeof _.isFunction; + export = isFunction; +} + + +declare module "lodash/isInteger" { + const isInteger: typeof _.isInteger; + export = isInteger; +} + + +declare module "lodash/isLength" { + const isLength: typeof _.isLength; + export = isLength; +} + + +declare module "lodash/isMap" { + const isMap: typeof _.isMap; + export = isMap; +} + + +declare module "lodash/isMatch" { + const isMatch: typeof _.isMatch; + export = isMatch; +} + + +declare module "lodash/isMatchWith" { + const isMatchWith: typeof _.isMatchWith; + export = isMatchWith; +} + + +declare module "lodash/isNaN" { + const isNaN: typeof _.isNaN; + export = isNaN; +} + + +declare module "lodash/isNative" { + const isNative: typeof _.isNative; + export = isNative; +} + + +declare module "lodash/isNil" { + const isNil: typeof _.isNil; + export = isNil; +} + + +declare module "lodash/isNull" { + const isNull: typeof _.isNull; + export = isNull; +} + + +declare module "lodash/isNumber" { + const isNumber: typeof _.isNumber; + export = isNumber; +} + + +declare module "lodash/isObject" { + const isObject: typeof _.isObject; + export = isObject; +} + + +declare module "lodash/isObjectLike" { + const isObjectLike: typeof _.isObjectLike; + export = isObjectLike; +} + + +declare module "lodash/isPlainObject" { + const isPlainObject: typeof _.isPlainObject; + export = isPlainObject; +} + + +declare module "lodash/isRegExp" { + const isRegExp: typeof _.isRegExp; + export = isRegExp; +} + + +declare module "lodash/isSafeInteger" { + const isSafeInteger: typeof _.isSafeInteger; + export = isSafeInteger; +} + + +declare module "lodash/isSet" { + const isSet: typeof _.isSet; + export = isSet; +} + + +declare module "lodash/isString" { + const isString: typeof _.isString; + export = isString; +} + + +declare module "lodash/isSymbol" { + const isSymbol: typeof _.isSymbol; + export = isSymbol; +} + + +declare module "lodash/isTypedArray" { + const isTypedArray: typeof _.isTypedArray; + export = isTypedArray; +} + + +declare module "lodash/isUndefined" { + const isUndefined: typeof _.isUndefined; + export = isUndefined; +} + + +declare module "lodash/isWeakMap" { + const isWeakMap: typeof _.isWeakMap; + export = isWeakMap; +} + + +declare module "lodash/isWeakSet" { + const isWeakSet: typeof _.isWeakSet; + export = isWeakSet; +} + + +declare module "lodash/join" { + const join: typeof _.join; + export = join; +} + + +declare module "lodash/kebabCase" { + const kebabCase: typeof _.kebabCase; + export = kebabCase; +} + + +declare module "lodash/last" { + const last: typeof _.last; + export = last; +} + + +declare module "lodash/lastIndexOf" { + const lastIndexOf: typeof _.lastIndexOf; + export = lastIndexOf; +} + + +declare module "lodash/lowerCase" { + const lowerCase: typeof _.lowerCase; + export = lowerCase; +} + + +declare module "lodash/lowerFirst" { + const lowerFirst: typeof _.lowerFirst; + export = lowerFirst; +} + + +declare module "lodash/lt" { + const lt: typeof _.lt; + export = lt; +} + + +declare module "lodash/lte" { + const lte: typeof _.lte; + export = lte; +} + + +declare module "lodash/max" { + const max: typeof _.max; + export = max; +} + + +declare module "lodash/maxBy" { + const maxBy: typeof _.maxBy; + export = maxBy; +} + + +declare module "lodash/mean" { + const mean: typeof _.mean; + export = mean; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/meanBy" { + const meanBy: typeof _.meanBy; + export = meanBy; +} +*/ + +declare module "lodash/min" { + const min: typeof _.min; + export = min; +} + + +declare module "lodash/minBy" { + const minBy: typeof _.minBy; + export = minBy; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/multiply" { + const multiply: typeof _.multiply; + export = multiply; +} +*/ + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash/nth" { + const nth: typeof _.nth; + export = nth; +} +*/ + +declare module "lodash/noConflict" { + const noConflict: typeof _.noConflict; + export = noConflict; +} + + +declare module "lodash/noop" { + const noop: typeof _.noop; + export = noop; +} + + +declare module "lodash/now" { + const now: typeof _.now; + export = now; +} + + +declare module "lodash/pad" { + const pad: typeof _.pad; + export = pad; +} + + +declare module "lodash/padEnd" { + const padEnd: typeof _.padEnd; + export = padEnd; +} + + +declare module "lodash/padStart" { + const padStart: typeof _.padStart; + export = padStart; +} + + +declare module "lodash/parseInt" { + const parseInt: typeof _.parseInt; + export = parseInt; +} + + +declare module "lodash/random" { + const random: typeof _.random; + export = random; +} + + +declare module "lodash/reduce" { + const reduce: typeof _.reduce; + export = reduce; +} + + +declare module "lodash/reduceRight" { + const reduceRight: typeof _.reduceRight; + export = reduceRight; +} + + +declare module "lodash/repeat" { + const repeat: typeof _.repeat; + export = repeat; +} + + +declare module "lodash/replace" { + const replace: typeof _.replace; + export = replace; +} + + +declare module "lodash/result" { + const result: typeof _.result; + export = result; +} + + +declare module "lodash/round" { + const round: typeof _.round; + export = round; +} + + +declare module "lodash/runInContext" { + const runInContext: typeof _.runInContext; + export = runInContext; +} + + +declare module "lodash/sample" { + const sample: typeof _.sample; + export = sample; +} + + +declare module "lodash/size" { + const size: typeof _.size; + export = size; +} + + +declare module "lodash/snakeCase" { + const snakeCase: typeof _.snakeCase; + export = snakeCase; +} + + +declare module "lodash/some" { + const some: typeof _.some; + export = some; +} + + +declare module "lodash/sortedIndex" { + const sortedIndex: typeof _.sortedIndex; + export = sortedIndex; +} + + +declare module "lodash/sortedIndexBy" { + const sortedIndexBy: typeof _.sortedIndexBy; + export = sortedIndexBy; +} + + +declare module "lodash/sortedIndexOf" { + const sortedIndexOf: typeof _.sortedIndexOf; + export = sortedIndexOf; +} + + +declare module "lodash/sortedLastIndex" { + const sortedLastIndex: typeof _.sortedLastIndex; + export = sortedLastIndex; +} + + +declare module "lodash/sortedLastIndexBy" { + const sortedLastIndexBy: typeof _.sortedLastIndexBy; + export = sortedLastIndexBy; +} + + +declare module "lodash/sortedLastIndexOf" { + const sortedLastIndexOf: typeof _.sortedLastIndexOf; + export = sortedLastIndexOf; +} + + +declare module "lodash/startCase" { + const startCase: typeof _.startCase; + export = startCase; +} + + +declare module "lodash/startsWith" { + const startsWith: typeof _.startsWith; + export = startsWith; +} + + +declare module "lodash/subtract" { + const subtract: typeof _.subtract; + export = subtract; +} + + +declare module "lodash/sum" { + const sum: typeof _.sum; + export = sum; +} + + +declare module "lodash/sumBy" { + const sumBy: typeof _.sumBy; + export = sumBy; +} + + +declare module "lodash/template" { + const template: typeof _.template; + export = template; +} + + +declare module "lodash/times" { + const times: typeof _.times; + export = times; +} + + +declare module "lodash/toInteger" { + const toInteger: typeof _.toInteger; + export = toInteger; +} + + +declare module "lodash/toLength" { + const toLength: typeof _.toLength; + export = toLength; +} + + +declare module "lodash/toLower" { + const toLower: typeof _.toLower; + export = toLower; +} + + +declare module "lodash/toNumber" { + const toNumber: typeof _.toNumber; + export = toNumber; +} + + +declare module "lodash/toSafeInteger" { + const toSafeInteger: typeof _.toSafeInteger; + export = toSafeInteger; +} + + +declare module "lodash/toString" { + const toString: typeof _.toString; + export = toString; +} + + +declare module "lodash/toUpper" { + const toUpper: typeof _.toUpper; + export = toUpper; +} + + +declare module "lodash/trim" { + const trim: typeof _.trim; + export = trim; +} + + +declare module "lodash/trimEnd" { + const trimEnd: typeof _.trimEnd; + export = trimEnd; +} + + +declare module "lodash/trimStart" { + const trimStart: typeof _.trimStart; + export = trimStart; +} + + +declare module "lodash/truncate" { + const truncate: typeof _.truncate; + export = truncate; +} + + +declare module "lodash/unescape" { + const unescape: typeof _.unescape; + export = unescape; +} + + +declare module "lodash/uniqueId" { + const uniqueId: typeof _.uniqueId; + export = uniqueId; +} + + +declare module "lodash/upperCase" { + const upperCase: typeof _.upperCase; + export = upperCase; +} + + +declare module "lodash/upperFirst" { + const upperFirst: typeof _.upperFirst; + export = upperFirst; +} + + +declare module "lodash/each" { + const each: typeof _.each; + export = each; +} + + +declare module "lodash/eachRight" { + const eachRight: typeof _.eachRight; + export = eachRight; +} + + +declare module "lodash/first" { + const first: typeof _.first; + export = first; +} + +declare module "lodash/fp" { + export = _; +} + declare module "lodash" { export = _; } diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index bdb7093265..177cac59e1 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -1434,7 +1434,7 @@ declare namespace __MaterialUI { autoHideDuration?: number; bodyStyle?: React.CSSProperties; className?: string; - message: string; + message: string | JSX.Element; onActionTouchTap?: React.TouchEventHandler; /** @deprecated Use the open property to control the component instead */ onDismiss?: () => void; // DEPRECATED diff --git a/mithril/mithril-tests.ts b/mithril/mithril-tests.ts index be5832a40d..a7d065f144 100644 --- a/mithril/mithril-tests.ts +++ b/mithril/mithril-tests.ts @@ -52,4 +52,4 @@ var todo = { }; //initialize the application -m.module(document, todo); +m.mount(document, todo); diff --git a/mithril/mithril.d.ts b/mithril/mithril.d.ts index b4e9dd5a54..d1c2ba78a6 100644 --- a/mithril/mithril.d.ts +++ b/mithril/mithril.d.ts @@ -3,175 +3,860 @@ // Definitions by: Leo Horie , Chris Bowdon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -//Mithril type definitions for Typescript +// Mithril type definitions for Typescript -declare module _mithril { - interface MithrilStatic { +/** +* This is the module containing all the types/declarations/etc. for Mithril +*/ +declare namespace Mithril { + interface ChildArray extends Array {} + type Children = Child | ChildArray; + type Child = string | VirtualElement | Component; - (selector: string, attributes: MithrilAttributes, ...children: Array>): MithrilVirtualElement; - (selector: string, ...children: Array>): MithrilVirtualElement; + interface Static { + /** + * Creates a virtual element for use with m.render, m.mount, etc. + * + * @param selector A simple CSS selector. May include SVG tags. Nested + * selectors are not supported. + * @param attributes Attributes to add. Any DOM attribute may be used + * as an attribute, although innerHTML and the like may be overwritten + * silently. + * @param children Child elements, components, and text to add. + * @return A virtual element. + * + * @see m.render + * @see m.mount + * @see m.component + */ + ( + selector: string, + ...children: Children[] + ): VirtualElement; - prop(promise: MithrilPromise) : MithrilPromiseProperty; - prop(value: T): MithrilProperty; - prop(): MithrilProperty; // might be that this should be Property + /** + * Creates a virtual element for use with m.render, m.mount, etc. + * + * @param selector A simple CSS selector. May include SVG tags. Nested + * selectors are not supported. + * @param attributes Attributes to add. Any DOM attribute may be used + * as an attribute, although innerHTML and the like may be overwritten + * silently. + * @param children Child elements, components, and text to add. + * @return A virtual element. + * + * @see m.render + * @see m.mount + * @see m.component + */ + ( + selector: string, + attributes: Attributes, + ...children: Children[] + ): VirtualElement; - withAttr(property: string, callback: (value: any) => void): (e: MithrilEvent) => any; + /** + * Initializes a component for use with m.render, m.mount, etc. + * + * @param component A component. + * @param args Arguments to optionally pass to the component. + * @return A component. + * + * @see m.render + * @see m.mount + * @see m + */ + ( + component: Component, + ...args: any[] + ): Component; - module(rootElement: Node, component: MithrilComponent): T; - module(rootElement: Node): T; - mount(rootElement: Node, component: MithrilComponent): T; - mount(rootElement: Node): T; + /** + * Creates a getter-setter function that wraps a Mithril promise. Useful + * for uniform data access, m.withAttr, etc. + * + * @param promise A thennable to initialize the property with. It may + * optionally be a Mithril promise. + * @return A getter-setter function wrapping the promise. + * + * @see m.withAttr + */ + prop(promise: Thennable) : Promise; - component(component: MithrilComponent, ...args: Array): MithrilComponent - - trust(html: string): string; + /** + * Creates a getter-setter function that wraps a simple value. Useful + * for uniform data access, m.withAttr, etc. + * + * @param value A value to initialize the property with + * @return A getter-setter function wrapping the value. + * + * @see m.withAttr + */ + prop(value: T): BasicProperty; - render(rootElement: Element|HTMLDocument): void; - render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement, forceRecreation?: boolean): void; - render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement[], forceRecreation?: boolean): void; + /** + * Creates a getter-setter function that wraps a simple value. Useful + * for uniform data access, m.withAttr, etc. + * + * @return A getter-setter function wrapping the value. + * + * @see m.withAttr + */ + prop(): BasicProperty; + + /** + * Returns a event handler that can be bound to an element, firing with + * the specified property. + * + * @param property The property to get from the event. + * @param callback The handler to use the value from the event. + * @return A function suitable for listening to an event. + */ + withAttr( + property: string, + callback: (value: any) => any, + callbackThis?: any + ): (e: Event) => void; + + /** + * @deprecated Use m.mount instead + */ + module( + rootElement: Node, + component: Component + ): T; + + /** + * Mounts a component to a base DOM node. + * + * @param rootElement The base node. + * @param component The component to mount. + * @return An instance of the top-level component's controller + */ + mount( + rootElement: Node, + component: Component + ): T; + + /** + * Initializes a component for use with m.render, m.mount, etc. + * + * @param selector A component. + * @param args Arguments to optionally pass to the component. + * @return A component. + * + * @see m.render + * @see m.mount + * @see m + */ + component( + component: Component, + ...args: any[] + ): Component; + + /** + * Trust this string of HTML. + * + * @param html The HTML to trust + * @return A String object instance with an added internal flag to mark + * it as trusted. + */ + trust(html: string): TrustedString; + + /** + * Render a virtual DOM tree. + * + * @param rootElement The base element/node to render the tree from. + * @param children One or more child nodes to add to the tree. + * @param forceRecreation If true, overwrite the entire tree without + * diffing against it. + */ + render( + rootElement: Element, + children: VirtualElement|VirtualElement[], + forceRecreation?: boolean + ): void; redraw: { + /** + * Force a redraw the active component. It redraws asynchronously by + * default to allow for simultaneous events to run before redrawing, + * such as the event combination keypress + input frequently used for + * input. + * + * @param force If true, redraw synchronously. + */ (force?: boolean): void; - strategy: MithrilProperty; + + /** + * Gets/sets the current redraw strategy, which returns one of the + * following: + * + * "all" - recreates the DOM tree from scratch + * "diff" - recreates the DOM tree from scratch + * "none" - leaves the DOM tree intact + * + * This is useful for event handlers, which may want to cancel + * the next redraw if the event doesn't update the UI. + * + * @return The current strategy + */ + strategy: BasicProperty<"all" | "diff" | "none">; } route: { - (rootElement: HTMLDocument, defaultRoute: string, routes: MithrilRoutes): void; - (rootElement: Element, defaultRoute: string, routes: MithrilRoutes): void; + /** + * Enable routing, mounting a controller based on the route. It + * automatically mounts the components for you, starting with the one + * specified by the default route. + * + * @param rootElement The element to mount the active controller to. + * @param defaultRoute The route to start with. + * @param routes A key-value mapping of pathname to controller. + */ + ( + rootElement: Element, + defaultRoute: string, + routes: Routes + ): void; - (element: Element, isInitialized: boolean, context: Object, vdom: Object): void; + /** + * This allows m.route to be used as the `config` attribute for a + * virtual element, particularly useful for cases like this: + * + * ```ts + * // Note that the '#' is not required in `href`, thanks to the + * `config` setting. + * m("a[href='/dashboard/alicesmith']", {config: m.route}); + * ``` + */ + ( + element: Element, + isInitialized: boolean, + context?: Context, + vdom?: VirtualElement + ): void; + + /** + * Programmatically redirect to another route. + * + * @param path The route to go to. + * @param params Parameters to pass as a query string. + * @param shouldReplaceHistory Whether to replace the current history + * instead of adding a new one. + */ (path: string, params?: any, shouldReplaceHistory?: boolean): void; + + /** + * Gets the current route. + * + * @return The current route. + */ (): string; + /** + * Gets a route parameter. + * + * @param key The key to get. + * @return The value associated with the parameter key. + */ param(key: string): string; - mode: string; - buildQueryString(data: Object): String - parseQueryString(data: String): Object + + /** + * The current routing mode. This may be changed before calling + * m.route to change the part of the URL used to perform the routing. + * + * The value can be set to one of the following, defaulting to + * "hash": + * + * "search" - Uses the query string. This allows for named anchors to + * work on the page, but changes cause IE8 and lower to refresh the + * page. + * + * "hash" - Uses the hash. This is the only routing mode that does + * not cause page refreshes on any browser, but it does not support + * named anchors. + * + * "pathname" - Uses the URL pathname. This requires server-side + * setup to support bookmarking and page refreshes. It always causes + * page refreshes on IE8 and lower. Note that this requires that the + * application to be run from the root of the URL. + */ + mode: "search" | "hash" | "pathname"; + + /** + * Serialize an object into a query string. + * + * @param data The data to serialize. + * @return The serialized string. + */ + buildQueryString(data: Object): string; + + /** + * Parse a query string into an object. + * + * @param data The data to parse. + * @return The parsed object data. + */ + parseQueryString(data: string): Object; } - request(options: MithrilXHROptions): MithrilPromise; + /** + * Send an XHR request to a server. Note that the `url` option is + * required. + * + * @param options The options to use for the request. + * @return A promise to the returned data, or void if not applicable. + * + * @see XHROptions for the available options. + */ + request(options: XHROptions): Promise + + /** + * Send a JSONP request to a server. Note that the `url` option is + * required. + * + * @param options The options to use + * @return A promise to the returned data. + * + * @see JSONPOptions for the available options. + */ + request(options: JSONPOptions): Promise; deferred: { + /** + * Create a Mithril deferred object. It behaves synchronously if + * possible, an intentional deviation from Promises/A+. Note that + * deferreds are completely separate from the redrawing system, and + * never trigger a redraw on their own. + * + * @return A new Mithril deferred instance. + * + * @see m.deferred.onerror for the error callback called for Error + * subclasses + */ + (): Deferred; + + /** + * A callback for all uncaught native Error subclasses in deferreds. + * This defaults to synchronously rethrowing all errors, a deviation + * from Promises/A+, but the behavior is configurable. To restore + * Promises/A+-compatible behavior. simply set this to a no-op. + */ onerror(e: Error): void; - (): MithrilDeferred; } - sync(promises: MithrilPromise[]): MithrilPromise; + /** + * Takes a list of promises or thennables and returns a Mithril promise + * that resolves once all in the list are resolved, or rejects if any of + * them reject. + * + * @param promises A list of promises to try to resolve. + * @return A promise that resolves to all the promises if all resolve, or + * rejects with the error contained in the first rejection. + */ + sync(promises: Thennable[]): Promise; + /** + * Use this and endComputation if your views aren't redrawing after + * calls to third-party libraries. For integrating asynchronous code, + * this should be called before any asynchronous work is done. For + * synchronous code, this should be called at the beginning of the + * problematic segment. Note that these calls must be balanced, much like + * braces and parentheses. This is mostly used internally. Prefer + * m.redraw where possible, especially when making repeated calls. + * + * @see endComputation + * @see m.render + */ startComputation(): void; + + /** + * Use startComputation and this if your views aren't redrawing after + * calls to third-party libraries. For integrating asynchronous code, + * this should be called after all asynchronous work completes. For + * synchronous code, this should be called at the end of the problematic + * segment. Note that these calls must be balanced, much like braces and + * parentheses. This is mostly used internally. Prefer m.redraw where + * possible, especially when making repeated calls. + * + * @see startComputation + * @see m.render + */ endComputation(): void; - // For test suite - deps: { - (mockWindow: Window): Window; - factory: Object; - } - + /** + * This overwrites the internal version of window used by Mithril. + * It's mostly useful for testing, and is also used internally by + * Mithril to test itself. By default Mithril uses `window` for the + * dependency. + * + * @param mockWindow The mock to use for the window. + * @return The mock that was passed in. + */ + deps(mockWindow: Window): Window; } - export interface MithrilVirtualElement { - key?: number; - tag?: string; - attrs?: MithrilAttributes; - children?: any[]; + interface TrustedString extends String { + /** @private Implementation detail. Don't depend on it. */ + $trusted: boolean; } - // Configuration function for an element - interface MithrilElementConfig { - (element: Element, isInitialized: boolean, context?: any, vdom?: MithrilVirtualElement): void; + /** + * The interface for a virtual element. It's best to consider this immutable + * for most use cases. + * + * @see m + */ + interface VirtualElement { + /** + * The tag name of this element. + */ + tag: string; + + /** + * The attributes of this element. + */ + attrs: Attributes; + + /** + * The children of this element. + */ + children: Children[]; } - // Attributes on a virtual element - interface MithrilAttributes { - title?: string; + /** + * An event passed by Mithril to unload event handlers. + */ + interface Event { + /** + * Prevent the default behavior of scrolling the page and updating the + * URL on next route change. + */ + preventDefault(): void; + } + + /** + * A context object for configuration functions. + * + * @see ElementConfig + */ + interface Context { + /** + * A function to call when the node is unloaded. Useful for cleanup. + */ + onunload?(): any; + + /** + * Set true if the backing DOM node needs to be retained between route + * changes if possible. Set false if this node needs to be recreated + * every single time, regardless of how "different" it is. + */ + retain?: boolean; + } + + /** + * This represents a callback function for a virtual element's config + * attribute. It's a low-level function useful for extra cleanup after + * removal from the tree, storing instances of third-party classes that + * need to be associated with the DOM, etc. + * + * @see Attributes + * @see Context + */ + interface ElementConfig { + /** + * A callback function for a virtual element's config attribute. + * + * @param element The associated DOM element. + * @param isInitialized Whether this is the first call for the virtual + * element or not. + * @param context The associated context for this element. + * @param vdom The associated virtual element. + */ + ( + element: Element, + isInitialized: boolean, + context: Context, + vdom: VirtualElement + ): void; + } + + /** + * This represents the attributes available for configuring virtual elements, + * beyond the applicable DOM attributes. + * + * @see m + */ + interface Attributes { + /** + * The class name(s) for this virtual element, as a space-separated list. + */ className?: string; + + /** + * The class name(s) for this virtual element, as a space-separated list. + */ class?: string; - config?: MithrilElementConfig; + + /** + * A custom, low-level configuration in case this element needs special + * cleanup after removal from the tree. + * + * @see ElementConfig + */ + config?: ElementConfig; + + /** + * A key to optionally associate with this element. + */ + key?: string | number; + + /** + * Any other virtual element properties, including attributes and event + * handlers. + */ + [property: string]: any; } - // Defines the subset of Event that Mithril needs - interface MithrilEvent { - currentTarget: Element; - } - - interface MithrilController { + /** + * The basis of a Mithril controller instance. + */ + interface Controller { + /** + * An optional handler to call when the associated virtual element is + * destroyed. + * + * @param evt An associated event. + */ onunload?(evt: Event): any; } - interface MithrilControllerFunction extends MithrilController { - (): any; + /** + * This represents a controller function. + * + * @see ControllerConstructor + */ + interface ControllerFunction { + (...args: any[]): T; } - interface MithrilView { - (ctrl: T): string|MithrilVirtualElement; + /** + * This represents a controller constructor. + * + * @see ControllerFunction + */ + interface ControllerConstructor { + new (...args: any[]): T; } - interface MithrilComponent { - controller: MithrilControllerFunction|{ new(): T }; - view: MithrilView; + /** + * This represents a Mithril component. + * + * @see m + * @see m.component + */ + interface Component { + /** + * The component's controller. + * + * @see m.component + */ + controller: ControllerFunction | ControllerConstructor; + + /** + * Creates a view out of virtual elements. + * + * @see m.component + */ + view(ctrl?: T, ...args: any[]): VirtualElement; } - interface MithrilProperty { + /** + * This is the base interface for property getter-setters + * + * @see m.prop + */ + interface Property { + /** + * Gets the contained value. + * + * @return The contained value. + */ (): T; + + /** + * Sets the contained value. + * + * @param value The new value to set. + * @return The newly set value. + */ (value: T): T; + } + + /** + * This represents a non-promise getter-setter functions. + * + * @see m.prop which returns objects that implement this interface. + */ + interface BasicProperty extends Property { + /** + * Makes this serializable to JSON. + */ toJSON(): T; } - interface MithrilPromiseProperty extends MithrilPromise { - (): T; - (value: T): T; - toJSON(): T; + /** + * This represents a key-value mapping linking routes to components. + */ + interface Routes { + /** + * The key represents the route. The value represents the corresponding + * component. + */ + [key: string]: Component; } - interface MithrilRoutes { - [key: string]: MithrilComponent; - } - - - interface MithrilDeferred { + /** + * This represents a Mithril deferred object. + */ + interface Deferred { + /** + * Resolve this deferred's promise with a value. + * + * @param value The value to resolve the promise with. + */ resolve(value?: T): void; - reject(value?: any): void; - promise: MithrilPromise; + + /** + * Reject this deferred with an error. + * + * @param value The reason for rejecting the promise. + */ + reject(reason?: any): void; + + /** + * The backing promise. + * + * @see Promise + */ + promise: Promise; } - interface MithrilSuccessCallback { - (value: T): U; - (value: T): MithrilPromise; + /** + * This represents a thennable success callback. + */ + interface SuccessCallback { + (value: T): U | Thennable; } - interface MithrilErrorCallback { - (value: Error): U; - (value: string): U; + /** + * This represents a thennable error callback. + */ + interface ErrorCallback { + (value: Error): T | Thennable; } - interface MithrilPromise { - (): T; - (value: T): T; - then(success: (value: T) => U): MithrilPromise; - then(success: (value: T) => MithrilPromise): MithrilPromise; - then(success: (value: T) => U, error: (value: Error) => V): MithrilPromise|MithrilPromise; - then(success: (value: T) => MithrilPromise, error: (value: Error) => V): MithrilPromise|MithrilPromise; + /** + * This represents a thennable. + */ + interface Thennable { + then(success: SuccessCallback): Thennable; + then(success: SuccessCallback, error: ErrorCallback): Thennable; + catch?(error: ErrorCallback): Thennable; + catch?(error: ErrorCallback): Thennable; } - interface MithrilXHROptions { - method?: string; - url: string; - user?: string; - password?: string; + + /** + * This represents a Mithril promise object. + */ + interface Promise extends Thennable, Property> { + /** + * Chain this promise with a simple success callback, propogating + * rejections. + * + * @param success The callback to call when the promise is resolved. + * @return The chained promise. + */ + then(success: SuccessCallback): Promise; + + /** + * Chain this promise with a success callback and error callback, without + * propogating rejections. + * + * @param success The callback to call when the promise is resolved. + * @param error The callback to call when the promise is rejected. + * @return The chained promise. + */ + then(success: SuccessCallback, error: ErrorCallback): Promise; + + /** + * Chain this promise with a single error callback, without propogating + * rejections. + * + * @param error The callback to call when the promise is rejected. + * @return The chained promise. + */ + catch(error: ErrorCallback): Promise; + } + + /** + * These are the common options shared across normal and JSONP requests. + * + * @see m.request + */ + interface RequestOptions { + /** + * The data to be sent. It's automatically serialized in the right format + * depending on the method (with exception of HTML5 FormData), and put in + * the appropriate section of the request. + */ data?: any; + + /** + * Whether to run it in the background, i.e. true if it doesn't affect + * template rendering. + */ background?: boolean; + + /** + * Set an initial value while the request is working, to populate the + * promise getter-setter. + */ + initialValue?: any; + + /** + * An optional preprocessor function to unwrap a successful response, in + * case the response contains metadata wrapping the data. + * + * @param data The data to unwrap. + * @return The unwrapped result. + */ unwrapSuccess?(data: any): any; + + /** + * An optional preprocessor function to unwrap an unsuccessful response, + * in case the response contains metadata wrapping the data. + * + * @param data The data to unwrap. + * @return The unwrapped result. + */ unwrapError?(data: any): any; + + /** + * An optional function to serialize the data. This defaults to + * `JSON.stringify`. + * + * @param dataToSerialize The data to serialize. + * @return The serialized form as a string. + */ serialize?(dataToSerialize: any): string; + + /** + * An optional function to deserialize the data. This defaults to + * `JSON.parse`. + * + * @param dataToSerialize The data to parse. + * @return The parsed form. + */ deserialize?(dataToDeserialize: string): any; - extract?(xhr: XMLHttpRequest, options: MithrilXHROptions): string; - type?(data: Object): void; - config?(xhr: XMLHttpRequest, options: MithrilXHROptions): XMLHttpRequest; - dataType?: string; + + /** + * An optional function to extract the data from a raw XMLHttpRequest, + * useful if the relevant data is in a response header or the status + * field. + * + * @param xhr The associated XMLHttpRequest. + * @param options The options passed to this request. + * @return string The serialized format. + */ + extract?(xhr: XMLHttpRequest, options: this): string; + + /** + * The parsed data, or its children if it's an array, will be passed to + * this class constructor if it's given, to parse it into classes. + * + * @param data The data to parse. + * @return The new instance for the list. + */ + type?: new (data: any) => any; + + /** + * The URL to send the request to. + */ + url: string; + } + + /** + * This represents the available options for configuring m.request for JSONP + * requests. + * + * @see m.request + */ + interface JSONPOptions extends RequestOptions { + /** + * For JSONP requests, this must be the string "jsonp". Otherwise, it's + * ignored. + */ + dataType: "jsonp"; + + /** + * The querystring key for the JSONP request callback. This is useful for + * APIs that don't use common conventions, such as + * `www.example.com/?jsonpCallback=doSomething`. It defaults to + * `callback`. + */ + callbackKey?: string; + + /** + * The data to send with the request. This is automatically serialized + * to a querystring. + */ + data?: Object; + } + + /** + * This represents the available options for configuring m.request for + * standard AJAX requests. + * + * @see m.request + */ + interface XHROptions extends RequestOptions { + /** + * This represents the HTTP method used, defaulting to "GET". + */ + method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS"; + + /** + * The username for HTTP authentication. + */ + user?: string; + + /** + * The password for HTTP authentication. + */ + password?: string; + + /** + * An optional function to run between `open` and `send`, useful for + * adding request headers or using XHR2 features such as the `upload` + * property. It is even possible to override the XHR altogether with a + * similar object, such as an XDomainRequest instance. + * + * @param xhr The associated XMLHttpRequest. + * @param options The options passed to this request. + * @return The new XMLHttpRequest, or nothing if the same one is kept. + */ + config?(xhr: XMLHttpRequest, options: this): any; + + /** + * The data to send with the request. + */ + data?: Object; } } -declare var Mithril: _mithril.MithrilStatic; -declare var m: _mithril.MithrilStatic; +declare const m: Mithril.Static; declare module "mithril" { export = m; diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 6c9f8efe7f..a08251b8ba 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -164,8 +164,8 @@ declare module "mongodb" { // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser addUser(username: string, password: string, callback: MongoCallback): void; - addUser(username: string, password: string, options?: { w?: number | string, wtimeout?: number, j?: boolean, customData?: Object, roles?: Object[] }): Promise; - addUser(username: string, password: string, options: { w?: number | string, wtimeout?: number, j?: boolean, customData?: Object, roles?: Object[] }, callback: MongoCallback): void; + addUser(username: string, password: string, options?: DbAddUserOptions): Promise; + addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#admin admin(): Admin; // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#authenticate @@ -184,7 +184,7 @@ declare module "mongodb" { collections(): Promise; collections(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#command - command(command: Object, callback?: MongoCallback): void; + command(command: Object, callback: MongoCallback): void; command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection @@ -199,8 +199,8 @@ declare module "mongodb" { db(dbName: string): Db; db(dbName: string, options: { noListener?: boolean, returnNonCachedInstance?: boolean }): Db; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropCollection - dropCollection(name: string): Promise; - dropCollection(name: string, callback: MongoCallback): void; + dropCollection(name: string): Promise; + dropCollection(name: string, callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropDatabase dropDatabase(): Promise; dropDatabase(callback: MongoCallback): void; @@ -219,7 +219,7 @@ declare module "mongodb" { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#listCollections - listCollections(filter: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter: { name?: string }, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#logout logout(callback: MongoCallback): void; logout(options?: { dbName?: string }): Promise; @@ -231,7 +231,7 @@ declare module "mongodb" { removeUser(username: string, callback: MongoCallback): void; removeUser(username: string, options?: { w?: number | string, wtimeout?: number, j?: boolean }): Promise; removeUser(username: string, options: { w?: number | string, wtimeout?: number, j?: boolean }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback): void; renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise; renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; @@ -241,6 +241,8 @@ declare module "mongodb" { stats(options: { scale?: number }, callback: MongoCallback): void; } + + // Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html export class Server extends EventEmitter { constructor(host: string, port: number, options?: ServerOptions); @@ -254,13 +256,22 @@ declare module "mongodb" { connections(): Array; } - + // Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html export class Mongos extends EventEmitter { constructor(servers: Array, options?: MongosOptions); connections(): Array; } + + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser + export interface DbAddUserOptions { + w?: string | number; + wtimeout?: number; + j?: boolean; + customData?: Object; + roles?: Object[]; + } //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection export interface CollectionCreateOptions { @@ -333,42 +344,42 @@ declare module "mongodb" { authenticate(username: string, password: string, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#buildInfo buildInfo(): Promise; - buildInfo(callback: MongoCallback): void + buildInfo(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#command command(command: Object, callback: MongoCallback): void; command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#listDatabases listDatabases(): Promise; - listDatabases(callback: MongoCallback): void + listDatabases(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#logout logout(): Promise; - logout(callback: MongoCallback): void + logout(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#ping ping(): Promise; - ping(callback: MongoCallback): void + ping(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingInfo profilingInfo(): Promise; - profilingInfo(callback: MongoCallback): void + profilingInfo(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingLevel profilingLevel(): Promise; - profilingLevel(callback: MongoCallback): void + profilingLevel(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser removeUser(username: string, callback: MongoCallback): void; removeUser(username: string, options?: FSyncOptions): Promise; removeUser(username: string, options: FSyncOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#replSetGetStatus replSetGetStatus(): Promise; - replSetGetStatus(callback: MongoCallback): void + replSetGetStatus(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverInfo serverInfo(): Promise; - serverInfo(callback: MongoCallback): void + serverInfo(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverStatus serverStatus(): Promise; - serverStatus(callback: MongoCallback): void + serverStatus(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#setProfilingLevel setProfilingLevel(level: string): Promise; - setProfilingLevel(level: string, callback: MongoCallback): void + setProfilingLevel(level: string, callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#validateCollection validateCollection(collectionNme: string, callback: MongoCallback): void; validateCollection(collectionNme: string, options?: Object): Promise; @@ -564,12 +575,12 @@ declare module "mongodb" { // Get current index hint for collection. hint: any; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - aggregate(pipeline: Object[], callback: MongoCallback): void | AggregationCursor; - aggregate(pipeline: Object[], options: CollectionAggrigationOptions, callback: MongoCallback): void | AggregationCursor; + aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite - bulkWrite(operations: Object[], callback: MongoCallback): void - bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise - bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback): void + bulkWrite(operations: Object[], callback: MongoCallback): void; + bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise; + bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count count(query: Object, callback: MongoCallback): void; count(query: Object, options?: MongoCountPreferences): Promise; @@ -590,9 +601,9 @@ declare module "mongodb" { deleteOne(filter: Object, options?: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }): Promise; deleteOne(filter: Object, options: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#distinct - distinct(key: string, query: Object, callback: MongoCallback): void + distinct(key: string, query: Object, callback: MongoCallback): void; distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string }): Promise; - distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void + distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#drop drop(): Promise; drop(callback: MongoCallback): void; @@ -604,7 +615,16 @@ declare module "mongodb" { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query: Object): Cursor; + find(query?: Object): Cursor; + /** @deprecated */ + find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, callback: MongoCallback): void; + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, options?: FindOneOptions): Promise; + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete findOneAndDelete(filter: Object, callback: MongoCallback): void; findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; @@ -640,17 +660,24 @@ declare module "mongodb" { indexInformation(options?: { full: boolean }): Promise; indexInformation(options: { full: boolean }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp - initializeOrderedBulkOp(options: CollectionOptions): OrderedBulkOperation; + initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp - initializeUnorderedBulkOp(options: CollectionOptions): UnorderedBulkOperation; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany - insertMany(docs: Object[], callback: MongoCallback): void - insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise; - insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback): void + initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne - insertOne(docs: Object, callback: MongoCallback): void + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, callback: MongoCallback): void; + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, options?: CollectionInsertOneOptions): Promise; + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany + insertMany(docs: Object[], callback: MongoCallback): void; + insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise; + insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne + insertOne(docs: Object, callback: MongoCallback): void; insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise; - insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void + insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#isCapped isCapped(): Promise; isCapped(callback: MongoCallback): void; @@ -678,10 +705,22 @@ declare module "mongodb" { replaceOne(filter: Object, doc: Object, callback: MongoCallback): void; replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise; replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#save + /** @deprecated Use insertOne, insertMany, updateOne or updateMany */ + save(doc: Object, callback: MongoCallback): void; + save(doc: Object, options?: CollectionOptions): Promise; + save(doc: Object, options: CollectionOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#stats stats(callback: MongoCallback): void; stats(options?: { scale: number }): Promise; stats(options: { scale: number }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#update + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, callback: MongoCallback): void; + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, options?: ReplaceOneOptions & { multi?: boolean }): Promise; + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, options: ReplaceOneOptions & { multi?: boolean }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateMany updateMany(filter: Object, update: Object, callback: MongoCallback): void; updateMany(filter: Object, update: Object, options?: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }): Promise; @@ -693,6 +732,7 @@ declare module "mongodb" { } // Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ + //TODO complete this export interface CollStats { // Namespace. ns: string; @@ -724,10 +764,11 @@ declare module "mongodb" { maxSize: boolean; wiredTiger: any; indexDetails: any; + ok: number; } //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - export interface CollectionAggrigationOptions { + export interface CollectionAggregationOptions { readPreference?: ReadPreference | string; // Return the query as cursor, on 2.6 > it returns as a real cursor // on pre 2.6 it returns as an emulated cursor. @@ -875,7 +916,7 @@ declare module "mongodb" { length: number; //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute execute(callback: MongoCallback): void; - execute(options: FSyncOptions): Promise; + execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find find(selector: Object): FindOperatorsOrdered; @@ -885,7 +926,7 @@ declare module "mongodb" { //http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html export interface BulkWriteResult { - ok: boolean; + ok: number; nInserted: number; nUpdated: number; nUpserted: number; @@ -936,7 +977,7 @@ declare module "mongodb" { export interface UnorderedBulkOperation { //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute execute(callback: MongoCallback): void; - execute(options: FSyncOptions): Promise; + execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find find(selector: Object): FindOperatorsUnordered; @@ -955,6 +996,30 @@ declare module "mongodb" { upsert(): FindOperatorsUnordered; } + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne + export interface FindOneOptions { + limit?: number, + sort?: Array | Object, + fields?: Object, + skip?: number, + hint?: Object, + explain?: boolean, + snapshot?: boolean, + timeout?: boolean, + tailable?: boolean, + batchSize?: number, + returnKey?: boolean, + maxScan?: number, + min?: number, + max?: number, + showDiskLoc?: boolean, + comment?: string, + raw?: boolean, + readPreference?: ReadPreference | string, + partial?: boolean, + maxTimeMs?: number + } + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertWriteOpResult export interface InsertWriteOpResult { insertedCount: number; @@ -1031,7 +1096,13 @@ declare module "mongodb" { bypassDocumentValidation?: boolean } - + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~WriteOpResult + export interface WriteOpResult { + ops: Array; + connection: any; + result: any; + } + //http://mongodb.github.io/node-mongodb-native/2.1/api/external-Readable.html export interface Readable { pause(): void; @@ -1177,7 +1248,7 @@ declare module "mongodb" { close(): Promise; close(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#each - each(callback: MongoCallback): void + each(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#explain explain(): Promise; explain(callback: MongoCallback): void; @@ -1219,8 +1290,8 @@ declare module "mongodb" { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort sort(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; + toArray(): Promise; + toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift @@ -1241,7 +1312,7 @@ declare module "mongodb" { close(): Promise; close(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#each - each(callback: MongoCallback): void + each(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#isClosed isClosed(): boolean; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#maxTimeMS @@ -1264,8 +1335,8 @@ declare module "mongodb" { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; + toArray(): Promise; + toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift diff --git a/mousetrap/mousetrap-global-bind-tests.ts b/mousetrap/mousetrap-global-bind-tests.ts index 889df1a264..d6a7826a2a 100644 --- a/mousetrap/mousetrap-global-bind-tests.ts +++ b/mousetrap/mousetrap-global-bind-tests.ts @@ -25,6 +25,11 @@ Mousetrap.bindGlobal('up up down down left right left right b a enter', function console.log('konami code'); }); +// Test that union types are accepted. +const unionTypeKeys: string | string[] = ['a', 'b', 'c']; +Mousetrap.bindGlobal(unionTypeKeys, function() { console.log('Union type test') }); + + Mousetrap.bindGlobal(['ctrl+s', 'meta+s'], (e, combo) => { if (e.preventDefault) { e.preventDefault(); diff --git a/mousetrap/mousetrap-global-bind.d.ts b/mousetrap/mousetrap-global-bind.d.ts index c27a1f58f7..36c757d18e 100644 --- a/mousetrap/mousetrap-global-bind.d.ts +++ b/mousetrap/mousetrap-global-bind.d.ts @@ -6,6 +6,5 @@ /// interface MousetrapStatic { - bindGlobal(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; - bindGlobal(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; + bindGlobal(keyArray: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; } diff --git a/mousetrap/mousetrap-tests.ts b/mousetrap/mousetrap-tests.ts index ab8b858d34..19fe27dd26 100644 --- a/mousetrap/mousetrap-tests.ts +++ b/mousetrap/mousetrap-tests.ts @@ -51,6 +51,10 @@ instance.bind('mod+s', function(){ console.log('Instance Saved'); }); // Test that the factory method works as well. Mousetrap(element).bind('mod+s', function(){ console.log('Factory Saved'); }); +// Test that union types are accepted. +const unionTypeKeys: string | string[] = ['a', 'b', 'c']; +Mousetrap(element).bind(unionTypeKeys, function() { console.log('Union type test') }); + // Test that Mousetrap can be loaded as an external module. // Assume that if the externally-loaded module can be assigned to a variable with the type of global Mousetrap, // then everything is working correctly. diff --git a/mousetrap/mousetrap.d.ts b/mousetrap/mousetrap.d.ts index 829def2939..04c8c7d403 100644 --- a/mousetrap/mousetrap.d.ts +++ b/mousetrap/mousetrap.d.ts @@ -11,20 +11,16 @@ interface MousetrapStatic { (el: Element): MousetrapInstance; new (el: Element): MousetrapInstance; stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean; - bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; - bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; - unbind(keys: string, action?: string): void; - unbind(keyArray: string[], action?: string): void; + bind(keys: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; + unbind(keys: string|string[], action?: string): void; trigger(keys: string, action?: string): void; reset(): void; } interface MousetrapInstance { stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean; - bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; - bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; - unbind(keys: string, action?: string): void; - unbind(keyArray: string[], action?: string): void; + bind(keys: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; + unbind(keys: string|string[], action?: string): void; trigger(keys: string, action?: string): void; reset(): void; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 64f7a5bb29..cc39926ca3 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -148,6 +148,35 @@ function bufferTests() { var result1 = Buffer.concat([utf8Buffer, base64Buffer]); var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); + // Class Method: Buffer.from(array) + { + const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + } + + // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + { + const arr: Uint16Array = new Uint16Array(2); + arr[0] = 5000; + arr[1] = 4000; + + let buf: Buffer; + buf = Buffer.from(arr.buffer); + buf = Buffer.from(arr.buffer, 1); + buf = Buffer.from(arr.buffer, 0, 1); + } + + // Class Method: Buffer.from(buffer) + { + const buf1: Buffer = Buffer.from('buffer'); + const buf2: Buffer = Buffer.from(buf1); + } + + // Class Method: Buffer.from(str[, encoding]) + { + const buf1: Buffer = Buffer.from('this is a tést'); + const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); + } + // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. var a: Buffer | number; diff --git a/node/node.d.ts b/node/node.d.ts index 6f115759ff..47b4b4d967 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -111,7 +111,7 @@ declare var Buffer: { /** * Produces a Buffer backed by the same allocated memory as * the given {ArrayBuffer}. - * + * * * @param arrayBuffer The ArrayBuffer with which to share memory. */ @@ -129,6 +129,37 @@ declare var Buffer: { */ new (buffer: Buffer): Buffer; prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; /** * Returns true if {obj} is a Buffer * diff --git a/normalizr/normalizr.d.ts b/normalizr/normalizr.d.ts index 77d2f86648..aff53adabb 100644 --- a/normalizr/normalizr.d.ts +++ b/normalizr/normalizr.d.ts @@ -105,7 +105,7 @@ declare namespace Normalizr { */ mergeIntoEntity?: (stored: any, normalized: any, entityKey: string) => any; }): { - entites: any; + entities: any; result: any; }; } diff --git a/phonegap-plugin-push/phonegap-plugin-push-tests.ts b/phonegap-plugin-push/phonegap-plugin-push-tests.ts index 339c7e8e14..8b885e54e0 100644 --- a/phonegap-plugin-push/phonegap-plugin-push-tests.ts +++ b/phonegap-plugin-push/phonegap-plugin-push-tests.ts @@ -9,13 +9,38 @@ function test() { sound: true, vibrate: true, clearNotifications: false, - forceShow: true + forceShow: true, + topics: ['foo', 'bar'] }, ios: { badge: true, sound: true, alert: true, - clearBadge: true + clearBadge: true, + senderID: '123456789', + gcmSandbox: true, + categories: { + "invite": { + yes: { + callback: "app.accept", title: "Accept", foreground: true, destructive: false + }, + no: { + callback: "app.reject", title: "Reject", foreground: true, destructive: false + }, + maybe: { + callback: "app.maybe", title: "Maybe", foreground: true, destructive: false + } + }, + "delete": { + yes: { + callback: "app.doDelete", title: "Delete", foreground: true, destructive: true + }, + no: { + callback: "app.cancel", title: "Cancel", foreground: true, destructive: false + } + } + }, + topics: ['foo', 'bar'] }, windows: {} }; @@ -39,7 +64,7 @@ function test() { console.log('did unregister'); }, () => { console.log('did not unregister'); - }); + }, ['foo','bar']); /*from init*/ push = PushNotification.init(options); @@ -59,12 +84,13 @@ function test() { /*the rest of the additional fields are not 'canon'*/ console.log(data.additionalData); console.log(data.additionalData.foreground); + console.log(data.additionalData.coldstart); push.finish(() => { console.log('did finish'); }, () => { console.log('did not finish'); - }); + }, 'push-1'); }; let errorHandler = (e: Error) => { diff --git a/phonegap-plugin-push/phonegap-plugin-push.d.ts b/phonegap-plugin-push/phonegap-plugin-push.d.ts index dec4f075cf..f72c8f769f 100644 --- a/phonegap-plugin-push/phonegap-plugin-push.d.ts +++ b/phonegap-plugin-push/phonegap-plugin-push.d.ts @@ -52,8 +52,9 @@ declare namespace PhonegapPluginPush { * so you will need to re-register them if you want them to function again without an application reload. * @param successHandler * @param errorHandler + * @param topics */ - unregister(successHandler: () => any, errorHandler?: () => any): void + unregister(successHandler: () => any, errorHandler?: () => any, topics?: string[]): void /*TODO according to js source code, "errorHandler" is optional, but is "count" also optional? I can't read objetive-C code (can anyone at all? I wonder...)*/ /** @@ -81,8 +82,9 @@ declare namespace PhonegapPluginPush { * successHandler gets called when background push processing is successfully completed. * @param successHandler * @param errorHandler + * @param id */ - finish(successHandler: () => any, errorHandler: () => any): void + finish(successHandler?: () => any, errorHandler?: () => any, id?: string): void } /** @@ -122,6 +124,10 @@ declare namespace PhonegapPluginPush { * If true will always show a notification, even when the app is on the foreground. Default is false. */ forceShow?: boolean + /** + * If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic. + */ + topics?: string[] } /** @@ -156,6 +162,23 @@ declare namespace PhonegapPluginPush { * If true|"true" the badge will be cleared on app startup. Default is false|"false". */ clearBadge?: boolean | string + /** + * The data required in order to enable Action Buttons for iOS. + * Action Buttons on iOS - https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#action-buttons-1 + */ + categories?: CategoryArray + /** + * Maps to the project number in the Google Developer Console. Setting this uses GCM for notifications instead of native + */ + senderID?: string + /** + * Whether to use prod or sandbox GCM setting. Defaults to false. + */ + gcmSandbox?: boolean + /** + * If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic. Note: only usable in conjunction with senderID + */ + topics?: string[] } /** @@ -166,6 +189,23 @@ declare namespace PhonegapPluginPush { } } + interface CategoryArray { + [name: string]: CategoryAction + } + + interface CategoryAction { + yes?: CategoryActionData + no?: CategoryActionData + maybe?: CategoryActionData + } + + interface CategoryActionData { + callback: string + title: string + foreground: boolean + destructive: boolean + } + interface RegistrationEventResponse { /** * The registration ID provided by the 3rd party remote push service. @@ -216,6 +256,10 @@ declare namespace PhonegapPluginPush { * Whether the notification was received while the app was in the foreground */ foreground?: boolean + /** + * Will be true if the application is started by clicking on the push notification, false if the app is already started. (Android/iOS only) + */ + coldstart?: boolean collapse_key?: string from?: string notId?: string diff --git a/pikaday/pikaday-tests.ts b/pikaday/pikaday-tests.ts index f98d4afcee..48cd8d3226 100644 --- a/pikaday/pikaday-tests.ts +++ b/pikaday/pikaday-tests.ts @@ -71,3 +71,14 @@ new Pikaday({field: $('#datepicker')[0]}); yearRange: [2000, 2020] }); })(); + +(() => { + new Pikaday( + { + field: document.getElementById('datepicker'), + firstDay: 1, + minDate: new Date('2000-01-01'), + maxDate: new Date('2020-12-31'), + showDaysInNextAndPreviousMonths: true + }); +})(); diff --git a/pikaday/pikaday.d.ts b/pikaday/pikaday.d.ts index 0025561f54..3e4f80df9a 100644 --- a/pikaday/pikaday.d.ts +++ b/pikaday/pikaday.d.ts @@ -241,6 +241,11 @@ declare namespace Pikaday { * Render the month after the year in the title. Default: false. */ showMonthAfterYear?: boolean; + + /** + * Render days of the calendar grid that fall in the next or previous months to the current month instead of rendering an empty table cell. Default: false. + */ + showDaysInNextAndPreviousMonths?: boolean; /** * Number of visible calendars. diff --git a/postal/postal.d.ts b/postal/postal.d.ts index d476c3710a..62caad6c1d 100644 --- a/postal/postal.d.ts +++ b/postal/postal.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Postal v1.0.6 +// Type definitions for Postal v1.0.8 // Project: https://github.com/postaljs/postal.js // Definitions by: Lokesh Peta , Paul Jolly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -61,19 +61,9 @@ interface IChannelDefinition { channel: string; } -interface ISourceArg { - topic: string; - channel?: string; -} - -interface IDestinationArg { - topic: string | ((topic: string) => string); - channel?: string; -} - interface IPostal { subscriptions: {}; - wiretaps: ICallback[]; + wireTaps: ICallback[]; addWireTap(callback: ICallback): () => void; @@ -83,8 +73,6 @@ interface IPostal { getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; - linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void; - publish(envelope: IEnvelope): void; reset(): void; diff --git a/pouchDB/pouch.d.ts b/pouchDB/pouch.d.ts index d3097a4099..0360e02b65 100644 --- a/pouchDB/pouch.d.ts +++ b/pouchDB/pouch.d.ts @@ -207,11 +207,13 @@ interface PouchApi { interface PouchOptions { name?: string; adapter?: string; + skip_setup?: boolean; } interface PouchDB extends PouchApi { new (name: string, opts: PouchOptions, callback: (err: PouchError, res: PouchDB) => void): PouchDB; new (name: string, callback: (err: PouchError, res: PouchDB) => void): PouchDB; + new (name: string, opts: PouchOptions): PouchDB; new (name: string): PouchDB; destroy(name: string, callback: (err: PouchError) => void): void; } diff --git a/react-native/react-native-animated-tests.tsx b/react-native/react-native-animated-tests.tsx new file mode 100644 index 0000000000..6fafd9f32f --- /dev/null +++ b/react-native/react-native-animated-tests.tsx @@ -0,0 +1,95 @@ +/// + +import * as React from 'react-native' + +import { + Animated, + View, +} from 'react-native'; + +function TestAnimatedAPI() { + // Value + const v1 = new Animated.Value(0); + const v2 = new Animated.Value(0); + + v1.setValue(0.1); + + v1.addListener(e => { + let n: number = e.value; + }); + + const v200 = v1.interpolate({ + inputRange: [0, 1], + outputRange: [0, 200], + }); + + // ValueXY + const position = new Animated.ValueXY({ x: 0, y: 0 }); + + // Animation functions + const spring1 = Animated.spring(v1, { + toValue: 0.5, + tension: 10, + }); + + const springXY = Animated.spring(position, { + toValue: { + x: 1, + y: 2, + } + }); + + spring1.start(); + spring1.stop(); + + Animated.parallel([ + Animated.spring(v1, { toValue: 1 }), + Animated.spring(v2, { toValue: 1 }), + ], { + stopTogether: true, + }); + + Animated.decay(v1, { + velocity: 2, + }); + + Animated.timing(v1, { + toValue: 1, + duration: 100, + delay: 100, + easing: v => v, + }); + + Animated.add(v1, v2); + Animated.multiply(v1, v2); + Animated.modulo(v1, 2); + + Animated.delay(100); + + Animated.sequence([ + spring1, + springXY, + ]); + + Animated.stagger(100, [ + spring1, + springXY, + ]); + + return ( + + + + + + + + ); +} \ No newline at end of file diff --git a/react-native/react-native-tests.tsx b/react-native/react-native-tests.tsx index 8bed3c8be3..6079637ce6 100644 --- a/react-native/react-native-tests.tsx +++ b/react-native/react-native-tests.tsx @@ -29,6 +29,7 @@ import { AppStateIOS, ViewPagerAndroid, Dimensions, + BackAndroid, } from 'react-native'; function testDimensions() { @@ -47,6 +48,8 @@ function testDimensions() { } = Dimensions.get("screen"); } +BackAndroid.addEventListener("hardwareBackPress", () => { +}); var styles = StyleSheet.create( { @@ -72,11 +75,19 @@ var styles = StyleSheet.create( class Welcome extends React.Component { + testNativeMethods() { + this.setNativeProps({}); + + const { rootView } = this.refs; + + rootView.measure((x, y, width, height) => { + }); + } render() { return ( - + Welcome to React Native diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index a6cab25ff0..e866c58c40 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -22,7 +22,7 @@ import React = __React; //react-native "extends" react -declare namespace __React { +declare module "react-native" { /** @@ -121,6 +121,109 @@ declare namespace __React { // @see lib.es6.d.ts export var Promise: PromiseConstructor; + module NativeMethodsMixin { + type MeasureOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, + pageX: number, + pageY: number + ) => void + + type MeasureInWindowOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number + ) => void + + type MeasureLayoutOnSuccessCallback = ( + left: number, + top: number, + width: number, + height: number + ) => void + } + + /** + * @see https://github.com/facebook/react-native/blob/master/Libraries/ReactIOS/NativeMethodsMixin.js + */ + export class Component extends React.Component { + /** + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. + */ + measure(callback: NativeMethodsMixin.MeasureOnSuccessCallback): void; + + /** + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: + * + * - x + * - y + * - width + * - height + * + * Note that these measurements are not available until after the rendering + * has been completed in native. + */ + measureInWindow(callback: NativeMethodsMixin.MeasureInWindowOnSuccessCallback): void; + + /** + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeNode`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. + * + * As always, to obtain a native node handle for a component, you can use + * `React.findNodeHandle(component)`. + */ + measureLayout( + relativeToNativeNode: number, + onSuccess: NativeMethodsMixin.MeasureLayoutOnSuccessCallback, + onFail: () => void /* currently unused */ + ): void; + + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](docs/direct-manipulation.html)). + */ + setNativeProps(nativeProps: Object): void; + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus(): void; + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur(): void; + + refs: { + [key: string]: Component + }; + } + //TODO: BGR: Replace with ComponentClass ? // node_modules/react-tools/src/classic/class/ReactClass.js export interface ReactClass { @@ -219,7 +322,6 @@ declare namespace __React { * //FIXME: need to find documentation on which compoenent is a native (i.e. non composite component) */ export interface NativeComponent { - setNativeProps: ( props: Object ) => void } /** @@ -2080,7 +2182,7 @@ declare namespace __React { } export interface Route { - component?: ComponentClass + component?: React.ComponentClass id?: string title?: string passProps?: Object; @@ -2519,7 +2621,7 @@ declare namespace __React { * @see https://facebook.github.io/react-native/docs/dimensions.html#content */ export interface Dimensions { - get( what: "window" | "screen" ): React.ScaledSize; + get( what: "window" | "screen" ): ScaledSize; } export interface InteractionManagerStatic { @@ -3351,6 +3453,312 @@ declare namespace __React { vibrate(): void } + export module Animated { + // Most (all?) functions where AnimatedValue is used any subclass of Animated can be used as well. + type AnimatedValue = Animated; + type AnimatedValueXY = ValueXY; + + type Base = Animated; + + class Animated { + // Internal class, no public API. + } + + class AnimatedWithChildren extends Animated { + // Internal class, no public API. + } + + class AnimatedInterpolation extends AnimatedWithChildren { + interpolate(config: InterpolationConfigType): AnimatedInterpolation; + } + + type ExtrapolateType = 'extend' | 'identity' | 'clamp'; + + type InterpolationConfigType = { + inputRange: number[]; + outputRange: (number[] | string[]); + easing?: ((input: number) => number); + extrapolate?: ExtrapolateType; + extrapolateLeft?: ExtrapolateType; + extrapolateRight?: ExtrapolateType; + }; + + type ValueListenerCallback = (state: {value: number}) => void; + + /** + * Standard value for driving animations. One `Animated.Value` can drive + * multiple properties in a synchronized fashion, but can only be driven by one + * mechanism at a time. Using a new mechanism (e.g. starting a new animation, + * or calling `setValue`) will stop any previous ones. + */ + export class Value extends AnimatedWithChildren { + constructor(value: number); + + setValue(value: number): void; + + /** + * Sets an offset that is applied on top of whatever value is set, whether via + * `setValue`, an animation, or `Animated.event`. Useful for compensating + * things like the start of a pan gesture. + */ + setOffset(offset: number): void; + + /** + * Merges the offset value into the base value and resets the offset to zero. + * The final output of the value is unchanged. + */ + flattenOffset(): void; + + /** + * Adds an asynchronous listener to the value so you can observe updates from + * animations. This is useful because there is no way to + * synchronously read the value because it might be driven natively. + */ + addListener(callback: ValueListenerCallback): string; + + removeListener(id: string): void; + + removeAllListeners(): void; + + /** + * Stops any running animation or tracking. `callback` is invoked with the + * final value after stopping the animation, which is useful for updating + * state to match the animation position with layout. + */ + stopAnimation(callback?: (value: number) => void): void; + + /** + * Interpolates the value before updating the property, e.g. mapping 0-1 to + * 0-10. + */ + interpolate(config: InterpolationConfigType): AnimatedInterpolation; + } + + type ValueXYListenerCallback = (value: {x: number; y: number}) => void; + + /** + * 2D Value for driving 2D animations, such as pan gestures. Almost identical + * API to normal `Animated.Value`, but multiplexed. Contains two regular + * `Animated.Value`s under the hood. + */ + export class ValueXY extends AnimatedWithChildren { + x: AnimatedValue; + y: AnimatedValue; + + constructor(valueIn?: {x: number | AnimatedValue; y: number | AnimatedValue}); + + setValue(value: {x: number; y: number}): void; + + setOffset(offset: {x: number; y: number}): void; + + flattenOffset(): void + + stopAnimation(callback?: () => number): void; + + addListener(callback: ValueXYListenerCallback): string; + + removeListener(id: string): void; + + /** + * Converts `{x, y}` into `{left, top}` for use in style, e.g. + * + *```javascript + * style={this.state.anim.getLayout()} + *``` + */ + getLayout(): { left: AnimatedValue, top: AnimatedValue }; + + /** + * Converts `{x, y}` into a useable translation transform, e.g. + * + *```javascript + * style={{ + * transform: this.state.anim.getTranslateTransform() + * }} + *``` + */ + getTranslateTransform(): {[key: string]: AnimatedValue}[]; + + } + + type EndResult = {finished: boolean}; + type EndCallback = (result: EndResult) => void; + + interface CompositeAnimation { + start: (callback?: EndCallback) => void; + stop: () => void; + } + + interface AnimationConfig { + isInteraction?: boolean; + useNativeDriver?: boolean; + } + + /** + * Animates a value from an initial velocity to zero based on a decay + * coefficient. + */ + export function decay( + value: AnimatedValue | AnimatedValueXY, + config: DecayAnimationConfig + ): CompositeAnimation; + + interface DecayAnimationConfig extends AnimationConfig { + velocity: number | {x: number, y: number}; + deceleration?: number; + } + + /** + * Animates a value along a timed easing curve. The `Easing` module has tons + * of pre-defined curves, or you can use your own function. + */ + export var timing: ( + value: AnimatedValue | AnimatedValueXY, + config: TimingAnimationConfig + ) => CompositeAnimation; + + interface TimingAnimationConfig extends AnimationConfig { + toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY; + easing?: (value: number) => number; + duration?: number; + delay?: number; + } + + interface SpringAnimationConfig extends AnimationConfig { + toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY; + overshootClamping?: boolean; + restDisplacementThreshold?: number; + restSpeedThreshold?: number; + velocity?: number | {x: number, y: number}; + bounciness?: number; + speed?: number; + tension?: number; + friction?: number; + } + + /** + * Creates a new Animated value composed from two Animated values added + * together. + */ + export function add( + a: Animated, + b: Animated + ): AnimatedAddition; + + class AnimatedAddition extends AnimatedInterpolation {} + + /** + * Creates a new Animated value composed from two Animated values multiplied + * together. + */ + export function multiply( + a: Animated, + b: Animated + ): AnimatedMultiplication; + + class AnimatedMultiplication extends AnimatedInterpolation {} + + /** + * Creates a new Animated value that is the (non-negative) modulo of the + * provided Animated value + */ + export function modulo( + a: Animated, + modulus: number + ): AnimatedModulo; + + class AnimatedModulo extends AnimatedInterpolation {} + + /** + * Starts an animation after the given delay. + */ + export function delay(time: number): CompositeAnimation; + + /** + * Starts an array of animations in order, waiting for each to complete + * before starting the next. If the current running animation is stopped, no + * following animations will be started. + */ + export function sequence( + animations: Array + ): CompositeAnimation; + + /** + * Array of animations may run in parallel (overlap), but are started in + * sequence with successive delays. Nice for doing trailing effects. + */ + + export function stagger( + time: number, + animations: Array + ): CompositeAnimation + + /** + * Spring animation based on Rebound and Origami. Tracks velocity state to + * create fluid motions as the `toValue` updates, and can be chained together. + */ + export var spring: ( + value: AnimatedValue | AnimatedValueXY, + config: SpringAnimationConfig + ) => CompositeAnimation; + + type ParallelConfig = { + stopTogether?: boolean; // If one is stopped, stop all. default: true + } + + /** + * Starts an array of animations all at the same time. By default, if one + * of the animations is stopped, they will all be stopped. You can override + * this with the `stopTogether` flag. + */ + var parallel: ( + animations: Array, + config?: ParallelConfig + ) => CompositeAnimation; + + type Mapping = {[key: string]: Mapping} | AnimatedValue; + interface EventConfig { + listener?: Function + } + + /** + * Takes an array of mappings and extracts values from each arg accordingly, + * then calls `setValue` on the mapped outputs. e.g. + * + *```javascript + * onScroll={Animated.event( + * [{nativeEvent: {contentOffset: {x: this._scrollX}}}] + * {listener}, // Optional async listener + * ) + * ... + * onPanResponderMove: Animated.event([ + * null, // raw event arg ignored + * {dx: this._panX}, // gestureState arg + * ]), + *``` + */ + var event: ( + argMapping: Mapping[], + config?: EventConfig + ) => (...args: any[]) => void; + + /** + * Animated variants of the basic native views. Accepts Animated.Value for + * props and style. + */ + export var View: any; + export var Image: any; + export var Text: any; + } + + export namespace BackAndroid { + type EVENT_NAME = "hardwareBackPress"; + + export function exitApp(): void; + export function addEventListener(event: EVENT_NAME, fn: Function): void; + export function removeEventListener(event: EVENT_NAME, fn: Function): void; + } + ////////////////////////////////////////////////////////////////////////// // // R E - E X P O R T S @@ -3489,19 +3897,6 @@ declare namespace __React { export function __spread( target: any, ...sources: any[] ): any; - - export interface GlobalStatic { - - /** - * Accepts a function as its only argument and calls that function before the next repaint. - * It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. - * In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you. - * @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe - */ - requestAnimationFrame( fn: () => void ) : void; - - } - // // Add-Ons // @@ -3518,16 +3913,19 @@ declare namespace __React { export var TestModule: TestModuleStatic export type TestModule = TestModuleStatic } - - } -declare module "react-native" { - - import ReactNative = __React - export = ReactNative +declare interface ReactNativeGlobalStatic { + /** + * Accepts a function as its only argument and calls that function before the next repaint. + * It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. + * In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you. + * @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe + */ + requestAnimationFrame( fn: () => void ) : void; } -declare var global: __React.GlobalStatic -declare function require( name: string ): any \ No newline at end of file +declare var global: ReactNativeGlobalStatic; + +declare function require( name: string ): any; \ No newline at end of file diff --git a/react-redux/react-redux.d.ts b/react-redux/react-redux.d.ts index 2e3e69dc68..6f05a17b6e 100644 --- a/react-redux/react-redux.d.ts +++ b/react-redux/react-redux.d.ts @@ -80,7 +80,12 @@ declare module "react-redux" { * Defaults to true. * @default true */ - pure: boolean; + pure?: boolean; + /** + * If true, stores a ref to the wrapped component instance and makes it available via + * getWrappedInstance() method. Defaults to false. + */ + withRef?: boolean; } export interface ProviderProps { diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 07acd52b9e..80d2e4ee6d 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -250,6 +250,7 @@ declare namespace ReactRouter { location?: H.Location | string parseQueryString?: ParseQueryString stringifyQuery?: StringifyQuery + basename?: string } interface MatchState extends RouterState { history: History diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index b5258d85ca..8e4571f472 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -5,16 +5,16 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import * as Select from "react-select"; +import Select, { Option } from "react-select"; class SelectTest extends React.Component, {}> { render() { - const options: ReactSelect.Option[] = [{ label: "Foo", value: "bar" }]; + const options: Option[] = [{ label: "Foo", value: "bar" }]; const onChange = (value: any) => console.log(value); const onOpen = () => { return; }; const onClose = () => { return; }; - const optionRenderer = (option: ReactSelect.Option) => {option.label} + const optionRenderer = (option: Option) => {option.label} return