diff --git a/README.md b/README.md index 8e582f05b4..34eae06069 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Before you share your improvement with the world, use it yourself. #### Test editing an existing package -To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html). +To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation). You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below. diff --git a/types/angular-desktop-notification/index.d.ts b/types/angular-desktop-notification/index.d.ts index a20d67cd21..6281396b66 100644 --- a/types/angular-desktop-notification/index.d.ts +++ b/types/angular-desktop-notification/index.d.ts @@ -101,7 +101,7 @@ declare module 'angular' { * Note: This property is not currently supported in any browser. * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/vibrate */ - vibrate?: boolean; + vibrate?: any; /** * The onclick property of the Notification interface specifies an event listener to receive click events. diff --git a/types/angular-gettext/index.d.ts b/types/angular-gettext/index.d.ts index 107d9e10e2..5b6eb1d90f 100644 --- a/types/angular-gettext/index.d.ts +++ b/types/angular-gettext/index.d.ts @@ -9,6 +9,7 @@ import * as angular from 'angular'; +export type gettextCatalog = angular.gettext.gettextCatalog; declare module 'angular' { export namespace gettext { diff --git a/types/angular-local-storage/index.d.ts b/types/angular-local-storage/index.d.ts index 76ab65b1b5..6e8c64416a 100644 --- a/types/angular-local-storage/index.d.ts +++ b/types/angular-local-storage/index.d.ts @@ -8,6 +8,10 @@ import * as angular from 'angular'; +export type ILocalStorageServiceProvider = angular.local.storage.ILocalStorageServiceProvider; +export type ILocalStorageService = angular.local.storage.ILocalStorageService; +export type ICookie = angular.local.storage.ICookie; + declare module 'angular' { export namespace local.storage { interface ILocalStorageServiceProvider extends angular.IServiceProvider { diff --git a/types/angular-mocks/angular-mocks-tests.ts b/types/angular-mocks/angular-mocks-tests.ts index cabbf7c578..f04c9a2a30 100644 --- a/types/angular-mocks/angular-mocks-tests.ts +++ b/types/angular-mocks/angular-mocks-tests.ts @@ -1,70 +1,91 @@ - /////////////////////////////////////// // IAngularStatic /////////////////////////////////////// -var angular: ng.IAngularStatic; -var mock: ng.IMockStatic; +let angular: ng.IAngularStatic; +let mock: ng.IMockStatic; mock = angular.mock; - /////////////////////////////////////// // IMockStatic /////////////////////////////////////// -var date: Date; +let date: Date; mock.dump({ key: 'value' }); mock.inject( - function () { return 1; }, - function () { return 2; } - ); + function() { + return 1; + }, + function() { + return 2; + } +); -mock.inject( - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]); +mock.inject([ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 1; + } +]); // This overload is not documented on the website, but flows from // how the injector works. mock.inject( - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }], - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]); + [ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 1; + } + ], + [ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 2; + } + ] +); mock.module('module1', 'module2'); mock.module( - function () { return 1; }, - function () { return 2; } - ); -mock.module({ module1: function () { return 1; } }); + function() { + return 1; + }, + function() { + return 2; + } +); +mock.module({ + module1: () => { + return 1; + } +}); mock.module.sharedInjector(); date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); date = mock.TzDate(-8, 12345678); - /////////////////////////////////////// // IExceptionHandlerProvider /////////////////////////////////////// -var exceptionHandlerProvider: ng.IExceptionHandlerProvider; +let exceptionHandlerProvider: ng.IExceptionHandlerProvider; exceptionHandlerProvider.mode('log'); - /////////////////////////////////////// // ITimeoutService /////////////////////////////////////// -var timeoutService: ng.ITimeoutService; +let timeoutService: ng.ITimeoutService; timeoutService.flush(); timeoutService.flush(1234); -timeoutService.flushNext(); -timeoutService.flushNext(1234); timeoutService.verifyNoPendingTasks(); //////////////////////////////////////// // IIntervalService //////////////////////////////////////// -var intervalService: ng.IIntervalService; -var intervalServiceTimeActuallyAdvanced: number; +let intervalService: ng.IIntervalService; +let intervalServiceTimeActuallyAdvanced: number; intervalServiceTimeActuallyAdvanced = intervalService.flush(); intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); @@ -72,9 +93,9 @@ intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); /////////////////////////////////////// // ILogService, ILogCall /////////////////////////////////////// -var logService: ng.ILogService; -var logCall: ng.ILogCall; -var logs: string[]; +let logService: ng.ILogService; +let logCall: ng.ILogCall; +let logs: string[]; logService.assertEmpty(); logService.reset(); @@ -90,29 +111,31 @@ logs = logCall.logs; /////////////////////////////////////// // ControllerService mock /////////////////////////////////////// -var $controller: ng.IControllerService; -$controller(class TestController {}, {}, {myBinding: 'works!'}); -$controller(function TestController() {}, {someLocal: 42}, {myBinding: 'works!'}); -$controller('TestController', {}, {myBinding: 'works!'}); - +let $controller: ng.IControllerService; +$controller(class TestController {}, {}, { myBinding: 'works!' }); +$controller(function TestController() {}, { someLocal: 42 }, { myBinding: 'works!' }); +$controller('TestController', {}, { myBinding: 'works!' }); /////////////////////////////////////// // IComponentControllerService /////////////////////////////////////// -var $componentController: ng.IComponentControllerService; -$componentController<{}, {}>('Test controller', { $scope: {} }); -$componentController<{}, {}>('Test controller', { $scope: {}, test: true }); -$componentController<{}, { test: boolean }>('Test controller', { $scope: {} }, { test: true}); -$componentController<{}, { test?: boolean }>('Test controller', { $scope: {} }, {}); -$componentController<{}, {}>('Test controller', { $scope: {} }, {}, 'identity'); -$componentController<{ cb: () => void }, {}>('Test controller', { $scope: {} }); -$componentController<{}, { test: {name: string} }>('Test controller', { test: {name: 'Test Local'} }); +let $componentController: ng.IComponentControllerService; +let $scope: ng.IScope; +$componentController<{}, {}>('Test controller', { $scope }); +$componentController<{}, {}>('Test controller', { $scope, test: true }); +$componentController<{}, { test: boolean }>('Test controller', { $scope }, { test: true }); +$componentController<{}, { test?: boolean }>('Test controller', { $scope }, {}); +$componentController<{}, {}>('Test controller', { $scope }, {}, 'identity'); +$componentController<{ cb: () => void }, {}>('Test controller', { $scope }); +$componentController<{}, { test: { name: string } }>('Test controller', { + test: { name: 'Test Local' } +}); /////////////////////////////////////// // IHttpBackendService /////////////////////////////////////// -var httpBackendService: ng.IHttpBackendService; -var requestHandler: ng.mock.IRequestHandler; +let httpBackendService: ng.IHttpBackendService; +let requestHandler: ng.mock.IRequestHandler; httpBackendService.flush(); httpBackendService.flush(1234); @@ -123,342 +146,1362 @@ httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data'); -requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/); -requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.expect('GET', /test.local/); requestHandler = httpBackendService.expect('GET', /test.local/, 'response data'); -requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + 'response data', + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.expect('GET', /test.local/, /response data/); -requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + /response data/, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.expect('GET', /test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.expect('GET', (url: string) => { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data' +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data', + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/ +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.expectDELETE('http://test.local'); requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectDELETE( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectGET('http://test.local'); requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectGET( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectHEAD('http://test.local'); requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectJSONP('http://test.local'); requestHandler = httpBackendService.expectJSONP(/test.local/); requestHandler = httpBackendService.expectJSONP(/test.local\/(\d+)/, ['id']); -requestHandler = httpBackendService.expectJSONP((url: string) => { return true; }); +requestHandler = httpBackendService.expectJSONP((url: string) => { + return true; +}); requestHandler = httpBackendService.expectPATCH('http://test.local'); requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/); -requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPATCH('http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expectPATCH( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPATCH(/test.local/); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPATCH(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPATCH( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH( + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST('http://test.local'); requestHandler = httpBackendService.expectPOST('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPOST('http://test.local', /response data/); -requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPOST('http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expectPOST( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST(/test.local/); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data'); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPOST(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPOST( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT('http://test.local'); requestHandler = httpBackendService.expectPUT('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPUT('http://test.local', /response data/); -requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPUT('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPUT( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT(/test.local/); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data'); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPUT(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPUT( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.when('GET', 'http://test.local'); requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data'); -requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/); -requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.when('GET', /test.local/); requestHandler = httpBackendService.when('GET', /test.local/, 'response data'); requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + 'response data', + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.when('GET', /test.local/, /response data/); requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + /response data/, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.when('GET', (url: string) => { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data' +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data', + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/ +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.whenDELETE('http://test.local'); requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenDELETE( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenGET('http://test.local'); requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenGET( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenHEAD('http://test.local'); requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenJSONP('http://test.local'); requestHandler = httpBackendService.whenJSONP(/test.local/); requestHandler = httpBackendService.whenJSONP(/test.local\/(\d+)/, ['id']); -requestHandler = httpBackendService.whenJSONP((url: string) => { return true; }); +requestHandler = httpBackendService.whenJSONP((url: string) => { + return true; +}); requestHandler = httpBackendService.whenPATCH('http://test.local'); requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/); -requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPATCH('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPATCH( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPATCH(/test.local/); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPATCH(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPATCH( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST('http://test.local'); requestHandler = httpBackendService.whenPOST('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPOST('http://test.local', /response data/); -requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPOST('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPOST( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST(/test.local/); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data'); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPOST(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPOST( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT('http://test.local'); requestHandler = httpBackendService.whenPUT('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPUT('http://test.local', /response data/); -requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPUT('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPUT( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT(/test.local/); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data'); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPUT(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPUT( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); - +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); /////////////////////////////////////// // IRequestHandler /////////////////////////////////////// -var expectedData = { key: 'value'}; +let expectedData = { key: 'value' }; requestHandler.passThrough(); requestHandler.passThrough().passThrough(); -requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); -requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({}); -requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); +requestHandler.respond((method, url, data, headers) => [ + 404, + 'data', + { header: 'value' }, + 'responseText' +]); +requestHandler + .respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']) + .respond({}); +requestHandler.respond((method, url, data, headers) => { + return [404, { key: 'value' }, { header: 'value' }, 'responseText']; +}); requestHandler.respond((method, url, data, headers, params) => { - if(params.id === 1) { - return [200, { key: 'value'}, { header: 'value'}, 'responseText']; - } else { - return [404, { key: 'value' }, { header: 'value' }, 'responseText']; - } + if (params.id === '1') { + return [200, { key: 'value' }, { header: 'value' }, 'responseText']; + } else { + return [404, { key: 'value' }, { header: 'value' }, 'responseText']; + } }); requestHandler.respond('data'); requestHandler.respond('data').respond({}); @@ -471,3 +1514,7 @@ requestHandler.respond(404, 'data').respond({}); requestHandler.respond(404, { key: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); + +browserTrigger(document.body, 'click'); +browserTrigger(angular.element(document.body), 'click'); +browserTrigger(angular.element(document.body), 'click', { which: 1, keys: ['ctrl'] }); diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index ac9e6cece3..c652443eac 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,10 +1,9 @@ -// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.5 +// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6 // Project: http://angularjs.org // Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 -/// /// import * as angular from 'angular'; @@ -13,7 +12,6 @@ import * as angular from 'angular'; // ngMock module (angular-mocks.js) /////////////////////////////////////////////////////////////////////////////// declare module 'angular' { - /////////////////////////////////////////////////////////////////////////// // AngularStatic // We reopen it to add the MockStatic definition @@ -23,27 +21,27 @@ declare module 'angular' { } // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject + // Depending on context, it might return a function, however having `void | (() => void)` + // as a return type seems to be not useful. E.g. it requires type assertions in `beforeEach(inject(...))`. interface IInjectStatic { - (...fns: Function[]): any; - (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works - strictDi(val?: boolean): void; + (...fns: Array void>>): any; // void | (() => void); + strictDi(val?: boolean): any; // void | (() => void); } interface IMockStatic { // see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump dump(obj: any): string; - inject: IInjectStatic + inject: IInjectStatic; // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module module: { (...modules: any[]): any; sharedInjector(): void; - } + }; // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate - TzDate(offset: number, timestamp: number): Date; - TzDate(offset: number, timestamp: string): Date; + TzDate(offset: number, timestamp: number | string): Date; } /////////////////////////////////////////////////////////////////////////// @@ -62,7 +60,6 @@ declare module 'angular' { /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { flush(delay?: number): void; - flushNext(expectedDelay?: number): void; verifyNoPendingTasks(): void; } @@ -96,9 +93,11 @@ declare module 'angular' { /////////////////////////////////////////////////////////////////////////// interface IControllerService { // Although the documentation doesn't state this, locals are optional - (controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T; - (controllerConstructor: Function, locals?: any, bindings?: any): T; - (controllerName: string, locals?: any, bindings?: any): T; + ( + controllerConstructor: (new (...args: any[]) => T) | ((...args: any[]) => T) | string, + locals?: any, + bindings?: any + ): T; } /////////////////////////////////////////////////////////////////////////// @@ -108,268 +107,473 @@ declare module 'angular' { interface IComponentControllerService { // TBinding is an interface exposed by a component as per John Papa's style guide // https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top - (componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; + ( + componentName: string, + locals: { $scope?: IScope; [key: string]: any }, + bindings?: TBinding, + ident?: string + ): T; } - /////////////////////////////////////////////////////////////////////////// // HttpBackendService // see https://docs.angularjs.org/api/ngMock/service/$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { /** - * Flushes pending requests using the trained responses. Requests are flushed in the order they were made, but it is also possible to skip one or more requests (for example to have them flushed later). This is useful for simulating scenarios where responses arrive from the server in any order. - * - * If there are no pending requests to flush when the method is called, an exception is thrown (as this is typically a sign of programming error). - * @param count Number of responses to flush. If undefined/null, all pending requests (starting after `skip`) will be flushed. - * @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_ - */ + * Flushes pending requests using the trained responses. Requests are flushed in the order they + * were made, but it is also possible to skip one or more requests (for example to have them + * flushed later). This is useful for simulating scenarios where responses arrive from the server + * in any order. + * + * If there are no pending requests to flush when the method is called, an exception is thrown (as + * this is typically a sign of programming error). + * + * @param count Number of responses to flush. If undefined/null, all pending requests (starting + * after `skip`) will be flushed. + * @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_ + */ flush(count?: number, skip?: number): void; /** - * Resets all request expectations, but preserves all backend definitions. - */ + * Resets all request expectations, but preserves all backend definitions. + */ resetExpectations(): void; /** - * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. - * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. - */ + * Verifies that all of the requests defined via the `expect` api were made. If any of the + * requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. + * NOTE: this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. + */ verifyNoOutstandingExpectation(digest?: boolean): void; /** - * Verifies that there are no outstanding requests that need to be flushed. - */ + * Verifies that there are no outstanding requests that need to be flushed. + */ verifyNoOutstandingRequest(): void; - /** - * Creates a new request expectation. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param method HTTP method. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expect( + method: string, + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for DELETE requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for DELETE requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectDELETE( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for GET requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for GET requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectGET( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for HEAD requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ + /** + * Creates a new request expectation for HEAD requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ - expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + expectHEAD( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for JSONP requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for JSONP requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectJSONP( + url: string | RegExp | ((url: string) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for PATCH requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for PATCH requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPATCH( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for POST requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for POST requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPOST( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for PUT requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for PUT requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPUT( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition. - * Returns an object with respond method that controls how a matched request is handled. - * @param method HTTP method. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation that compares only with the requested route. + * This method offers colon delimited matching of the url path, ignoring the query string. + * This allows declarations similar to how application routes are configured with `$routeProvider`. + * As this method converts the definition url to regex, declaration order is important. + * @param method HTTP method + * @param url HTTP url string that supports colon param matching + */ + expectRoute(method: string, url: string): mock.IRequestHandler; - /** - * Creates a new backend definition for DELETE requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + when( + method: string, + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for GET requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in request url described above - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for DELETE requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenDELETE( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for HEAD requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for GET requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in request url described above + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenGET( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for JSONP requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for HEAD requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenHEAD( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for PATCH requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for JSONP requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenJSONP( + url: string | RegExp | ((url: string) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for POST requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for PATCH requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPATCH( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for PUT requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for POST requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true + * if the url matches the current definition. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPOST( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; + + /** + * Creates a new backend definition for PUT requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true + * if the url matches the current definition. + * @param data HTTP request body or function that receives data string and returns true if the data + * is as expected. + * @param headers HTTP headers or function that receives http header object and returns true if the + * headers match the current definition. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPUT( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; + + /** + * Creates a new backend definition that compares only with the requested route. + * This method offers colon delimited matching of the url path, ignoring the query string. + * This allows declarations similar to how application routes are configured with `$routeProvider`. + * As this method converts the definition url to regex, declaration order is important. + * @param method HTTP method. + * @param url HTTP url string that supports colon param matching. + */ + whenRoute(method: string, url: string): mock.IRequestHandler; } /////////////////////////////////////////////////////////////////////////// // AnimateService // see https://docs.angularjs.org/api/ngMock/service/$animate /////////////////////////////////////////////////////////////////////////// - module animate { + namespace animate { interface IAnimateService { - /** - * This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining animation frames and/or callbacks. + * This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining + * animation frames and/or callbacks. */ closeAndFlush(): void; /** - * This method is used to flush the pending callbacks and animation frames to either start an animation or conclude an animation. Note that this will not actually close an actively running animation (see `closeAndFlush()` for that). + * This method is used to flush the pending callbacks and animation frames to either start + * an animation or conclude an animation. Note that this will not actually close an + * actively running animation (see `closeAndFlush()`} for that). */ flush(): void; } } - export module mock { - // returned interface by the the mocked HttpBackendService expect/when methods + namespace mock { + /** Object returned by the the mocked HttpBackendService expect/when methods */ interface IRequestHandler { - - /** - * Controls the response for a matched request using a function to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text. - */ - respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler; - - /** - * Controls the response for a matched request using supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param status HTTP status code to add to the response. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; - - /** - * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler; - - // Available when ngMockE2E is loaded /** - * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) - */ + * Controls the response for a matched request using a function to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys + * to regex matches in the request url and returns an array containing response status (number), data, + * headers, and status text. + */ + respond( + func: (( + method: string, + url: string, + data: string | object, + headers: IHttpHeaders, + params: { [key: string]: string } + ) => [number, string | object, IHttpHeaders, string]) + ): IRequestHandler; + + /** + * Controls the response for a matched request using supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param status HTTP status code to add to the response. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond( + status: number, + data: string | object, + headers?: IHttpHeaders, + responseText?: string + ): IRequestHandler; + + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond( + data: string | object, + headers?: IHttpHeaders, + responseText?: string + ): IRequestHandler; + + /** + * Any request matching a backend definition or expectation with passThrough handler will be + * passed through to the real backend (an XHR request will be made to the server.) + * Available when ngMockE2E is loaded + */ passThrough(): IRequestHandler; } + interface IHttpHeaders { + [headerName: string]: any; + } + + /** + * Contains additional event data used by the `browserTrigger` function when creating an event. + */ + interface IBrowserTriggerEventData { + /** + * [Event.bubbles](https://developer.mozilla.org/docs/Web/API/Event/bubbles). + * Not applicable to all events. + */ + bubbles?: boolean; + /** + * [Event.cancelable](https://developer.mozilla.org/docs/Web/API/Event/cancelable). + * Not applicable to all events. + */ + cancelable?: boolean; + /** + * [charCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/charcode) + * for keyboard events (keydown, keypress, and keyup). + */ + charcode?: number; + /** + * The elapsedTime for + * [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent) + * and [AnimationEvent](https://developer.mozilla.org/docs/Web/API/AnimationEvent). + */ + elapsedTime?: number; + /** + * [keyCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keycode) + * for keyboard events (keydown, keypress, and keyup). + */ + keycode?: number; + /** + * An array of possible modifier keys (ctrl, alt, shift, meta) for + * [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) and + * keyboard events (keydown, keypress, and keyup). + */ + keys?: Array<'ctrl' | 'alt' | 'shift' | 'meta'>; + /** + * The [relatedTarget](https://developer.mozilla.org/docs/Web/API/MouseEvent/relatedTarget) + * for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent). + */ + relatedTarget?: Node; + /** + * [which](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which) + * for keyboard events (keydown, keypress, and keyup). + */ + which?: number; + /** + * x-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) + * and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent). + */ + x?: number; + /** + * y-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) + * and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent). + */ + y?: number; + } } } /////////////////////////////////////////////////////////////////////////////// // functions attached to global object (window) /////////////////////////////////////////////////////////////////////////////// -//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. -//declare var module: (...modules: any[]) => any; +// Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. +// declare var module: (...modules: any[]) => any; declare global { - export var inject: angular.IInjectStatic; + const inject: angular.IInjectStatic; + + /** + * This is a global (window) function that is only available when the `ngMock` module is included. + * It can be used to trigger a native browser event on an element, which is useful for unit testing. + * + * @param element Either a wrapped jQuery/jqLite node or a DOM element + * @param eventType Optional event type. If none is specified, the function tries to determine + * the right event type for the element, e.g. `change` for `input[text]`. + * @param eventData An optional object which contains additional event data used when creating the event. + */ + function browserTrigger( + element: JQuery | Element, + eventType?: string, + eventData?: angular.mock.IBrowserTriggerEventData + ): void; } diff --git a/types/angular-mocks/mocks.d.ts b/types/angular-mocks/mocks.d.ts index 17c077008c..e8cc13c0a8 100644 --- a/types/angular-mocks/mocks.d.ts +++ b/types/angular-mocks/mocks.d.ts @@ -1,14 +1,14 @@ declare module "angular-mocks/ngMock" { - var _: string; + const _: string; export = _; } declare module "angular-mocks/ngMockE2E" { - var _: string; + const _: string; export = _; } declare module "angular-mocks/ngAnimateMock" { - var _: string; + const _: string; export = _; -} \ No newline at end of file +} diff --git a/types/angular-mocks/tslint.json b/types/angular-mocks/tslint.json index a41bf5d19a..e91317558b 100644 --- a/types/angular-mocks/tslint.json +++ b/types/angular-mocks/tslint.json @@ -1,79 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json", + "rules": { + "callable-types": false, + "interface-name": false, + "no-declare-current-package": false, + "no-unnecessary-generics": false, + "only-arrow-functions": false + } } diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 719fcb5d5c..f35fb57570 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) 2.15 +// Type definitions for Angular Translate (pascalprecht.translate module) 2.16 // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,8 +47,8 @@ declare module 'angular' { } interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise<{ [key: string]: string }>; + (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 6dccefc926..6b82a2bcb4 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -4,6 +4,7 @@ // Georgii Dolzhykov // Caleb St-Denis // Leonard Thieu +// Steffen Kowalski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -484,6 +485,76 @@ declare namespace angular { $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; + + /** + * Suspend watchers of this scope subtree so that they will not be invoked during digest. + * + * This can be used to optimize your application when you know that running those watchers + * is redundant. + * + * **Warning** + * + * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. + * Only use this approach if you are confident that you know what you are doing and have + * ample tests to ensure that bindings get updated as you expect. + * + * Some of the things to consider are: + * + * * Any external event on a directive/component will not trigger a digest while the hosting + * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. + * * Transcluded content exists on a scope that inherits from outside a directive but exists + * as a child of the directive's containing scope. If the containing scope is suspended the + * transcluded scope will also be suspended, even if the scope from which the transcluded + * scope inherits is not suspended. + * * Multiple directives trying to manage the suspended status of a scope can confuse each other: + * * A call to `$suspend()` on an already suspended scope is a no-op. + * * A call to `$resume()` on a non-suspended scope is a no-op. + * * If two directives suspend a scope, then one of them resumes the scope, the scope will no + * longer be suspended. This could result in the other directive believing a scope to be + * suspended when it is not. + * * If a parent scope is suspended then all its descendants will be also excluded from future + * digests whether or not they have been suspended themselves. Note that this also applies to + * isolate child scopes. + * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers + * for that scope and its descendants. When digesting we only check whether the current scope is + * locally suspended, rather than checking whether it has a suspended ancestor. + * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be + * included in future digests until all its ancestors have been resumed. + * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` + * against the `$rootScope` and so will still trigger a global digest even if the promise was + * initiated by a component that lives on a suspended scope. + */ + $suspend(): void; + + /** + * Call this method to determine if this scope has been explicitly suspended. It will not + * tell you whether an ancestor has been suspended. + * To determine if this scope will be excluded from a digest triggered at the $rootScope, + * for example, you must check all its ancestors: + * + * ``` + * function isExcludedFromDigest(scope) { + * while(scope) { + * if (scope.$isSuspended()) return true; + * scope = scope.$parent; + * } + * return false; + * ``` + * + * Be aware that a scope may not be included in digests if it has a suspended ancestor, + * even if `$isSuspended()` returns false. + * + * @returns true if the current scope has been suspended. + */ + $isSuspended(): boolean; + + /** + * Resume watchers of this scope subtree in case it was suspended. + * + * See {$rootScope.Scope#$suspend} for information about the dangers of using this approach. + */ + $resume(): void; + /** * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. * @@ -1390,10 +1461,9 @@ declare namespace angular { interface IControllerService { // Although the documentation doesn't state this, locals are optional - (controllerConstructor: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; - (controllerConstructor: Function, locals?: IControllerLocals, later?: boolean, ident?: string): T; - (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; - (controllerName: string, locals?: any, later?: boolean, ident?: string): T; + (controllerConstructor: new (...args: any[]) => T, locals?: any): T; + (controllerConstructor: (...args: any[]) => T, locals?: any): T; + (controllerName: string, locals?: any): T; } interface IControllerProvider extends IServiceProvider { diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0c64fd361b..fc070f62df 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -39,7 +39,10 @@ const showOptions : Auth0LockShowOptions = { type: "error", text: "an error has occurred" }, - rememberLastLogin: false + rememberLastLogin: false, + languageDictionary: { + title: "test" + } }; lock.show(showOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 27639834db..7dc20ae176 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -161,6 +161,7 @@ interface Auth0LockShowOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; flashMessage?: Auth0LockFlashMessageOptions; rememberLastLogin?: boolean; + languageDictionary?: any; } interface AuthResult { diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index aa82e908e5..be87ceed2c 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -350,6 +350,7 @@ export interface Identity { user_id: string; provider: string; isSocial: boolean; + access_token?: string; profileData?: { email?: string; email_verified?: boolean; @@ -882,4 +883,4 @@ export class UsersManager { impersonate(userId: string, settings: ImpersonateSettingOptions): Promise; impersonate(userId: string, settings: ImpersonateSettingOptions, cb: (err: Error, data: any) => void): void; -} \ No newline at end of file +} diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index de09b2a91f..3a6da1b49d 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; export { t as types }; diff --git a/types/babel-generator/index.d.ts b/types/babel-generator/index.d.ts index 2e34d158fc..8afeca4cd1 100644 --- a/types/babel-generator/index.d.ts +++ b/types/babel-generator/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Johnny Estilles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 467b0193e7..50b759c3f5 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { BabylonOptions } from 'babylon'; import * as t from 'babel-types'; diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index df420c17bd..5c18c3ff29 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -2,15 +2,17 @@ // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien // Marvin Hagemeister +// Ryan Petrich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as t from 'babel-types'; export type Node = t.Node; -export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; +export default function traverse(parent: Node | Node[], opts: TraverseOptions, scope: Scope, state: S, parentPath?: NodePath): void; +export default function traverse(parent: Node | Node[], opts: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; -export interface TraverseOptions extends Visitor { +export interface TraverseOptions extends Visitor { scope?: Scope; noScope?: boolean; } @@ -25,6 +27,7 @@ export class Scope { bindings: { [name: string]: Binding; }; /** Traverse node with current scope and path. */ + traverse(node: Node | Node[], opts: TraverseOptions, state: S): void; traverse(node: Node | Node[], opts?: TraverseOptions, state?: any): void; /** Generate a unique identifier and add it to the current scope. */ @@ -339,10 +342,10 @@ export class NodePath { listKey: string; inList: boolean; parentKey: string; - key: string; + key: string | number; node: T; scope: Scope; - type: string; + type: T extends undefined | null ? string | null : string; typeAnnotation: object; getScope(scope: Scope): Scope; @@ -353,7 +356,8 @@ export class NodePath { buildCodeFrameError(msg: string, Error?: new (msg: string) => TError): TError; - traverse(visitor: Visitor, state?: any): void; + traverse(visitor: Visitor, state: T): void; + traverse(visitor: Visitor): void; set(key: string, node: Node): void; @@ -372,10 +376,10 @@ export class NodePath { find(callback: (path: NodePath) => boolean): NodePath; /** Get the parent function of the current path. */ - getFunctionParent(): NodePath; + getFunctionParent(): NodePath; /** Walk up the tree until we hit a parent node path in a list. */ - getStatementParent(): NodePath; + getStatementParent(): NodePath; /** * Get the deepest common ancestor and then from it, get the earliest relationship path @@ -537,6 +541,9 @@ export class NodePath { /** Get the source code associated with this node. */ getSource(): string; + /** Check if the current path will maybe execute before another path */ + willIMaybeExecuteBefore(path: NodePath): boolean; + // ------------------------- context ------------------------- call(key: string): boolean; @@ -582,9 +589,15 @@ export class NodePath { getCompletionRecords(): NodePath[]; - getSibling(key: string): NodePath; + getSibling(key: string | number): NodePath; + getAllPrevSiblings(): NodePath[]; + getAllNextSiblings(): NodePath[]; - get(key: string, context?: boolean | TraversalContext): NodePath; + get(key: K, context?: boolean | TraversalContext): + T[K] extends Array ? Array> : + T[K] extends Node | null | undefined ? NodePath : + never; + get(key: string, context?: boolean | TraversalContext): NodePath | NodePath[]; getBindingIdentifiers(duplicates?: boolean): Node[]; diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 8c892a3ca0..c464c4bc3f 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -5,7 +5,7 @@ // Marvin Hagemeister // Boris Cherny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 export interface Comment { value: string; @@ -772,7 +772,7 @@ export interface VoidTypeAnnotation extends Node { export interface JSXAttribute extends Node { type: "JSXAttribute"; name: JSXIdentifier | JSXNamespacedName; - value: JSXElement | StringLiteral | JSXExpressionContainer; + value: JSXElement | StringLiteral | JSXExpressionContainer | null; } export interface JSXClosingElement extends Node { @@ -1424,7 +1424,7 @@ export function objectTypeProperty(key?: Expression, value?: FlowTypeAnnotation) export function qualifiedTypeIdentifier(id?: Identifier, qualification?: Identifier | QualifiedTypeIdentifier): QualifiedTypeIdentifier; export function unionTypeAnnotation(types?: FlowTypeAnnotation[]): UnionTypeAnnotation; export function voidTypeAnnotation(): VoidTypeAnnotation; -export function jSXAttribute(name?: JSXIdentifier | JSXNamespacedName, value?: JSXElement | StringLiteral | JSXExpressionContainer): JSXAttribute; +export function jSXAttribute(name?: JSXIdentifier | JSXNamespacedName, value?: JSXElement | StringLiteral | JSXExpressionContainer | null): JSXAttribute; export function jSXClosingElement(name?: JSXIdentifier | JSXMemberExpression): JSXClosingElement; export function jSXElement(openingElement?: JSXOpeningElement, closingElement?: JSXClosingElement, children?: Array, selfClosing?: boolean): JSXElement; export function jSXEmptyExpression(): JSXEmptyExpression; diff --git a/types/babel-webpack-plugin/index.d.ts b/types/babel-webpack-plugin/index.d.ts index 3f16d154ac..6f85bae2cc 100644 --- a/types/babel-webpack-plugin/index.d.ts +++ b/types/babel-webpack-plugin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/simlrh/babel-webpack-plugin // Definitions by: Jed Fox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { Plugin } from 'webpack'; import { TransformOptions } from 'babel-core'; diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index f394d2ba44..ca90ae9d4c 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: TeamworkGuy2 // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/babylon-walk/index.d.ts b/types/babylon-walk/index.d.ts index 02c3f39d10..43c9c1bf3a 100644 --- a/types/babylon-walk/index.d.ts +++ b/types/babylon-walk/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pugjs/babylon-walk // Definitions by: Marek Buchar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as babelTypes from 'babel-types'; diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb22f30c13..07eb74bb32 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Troy Gerwien // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { File, Expression } from 'babel-types'; diff --git a/types/bardjs/index.d.ts b/types/bardjs/index.d.ts index 5f2a5a1863..f701d4c368 100644 --- a/types/bardjs/index.d.ts +++ b/types/bardjs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/wardbell/bardjs // Definitions by: Andrew Archibald // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// diff --git a/types/blockies/index.d.ts b/types/blockies/index.d.ts index f2de8b2c53..2a8cc526ad 100644 --- a/types/blockies/index.d.ts +++ b/types/blockies/index.d.ts @@ -3,12 +3,16 @@ // Definitions by: Leonid Logvinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface BlockiesIcon { - toDataURL(): string; -} -interface BlockiesConfig { - seed: string; -} -declare function blockies(config: BlockiesConfig): BlockiesIcon; - +declare function blockies(config?: blockies.BlockiesConfig): HTMLCanvasElement; export = blockies; + +declare namespace blockies { + interface BlockiesConfig { + size?: number; + scale?: number; + seed?: string; + color?: string; + bgcolor?: string; + spotcolor?: string; + } +} diff --git a/types/blockies/tsconfig.json b/types/blockies/tsconfig.json index f190f0b0c9..db5851dcbb 100644 --- a/types/blockies/tsconfig.json +++ b/types/blockies/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictFunctionTypes": true, diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 2f43555a73..bba7b71c59 100755 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -354,7 +354,7 @@ export type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.too // -------------------------------------------------------------------------------------- declare global { - interface JQuery extends Iterable { + interface JQuery { alert(action?: "close" | "dispose"): this; button(action: "toggle" | "dispose"): this; diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index c63cb0c862..1c7e7e5996 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -1,4 +1,5 @@ import browserSync = require("browser-sync"); +import { EventEmitter } from "events"; (() => { //make sure that the interfaces are correctly exposed @@ -391,6 +392,57 @@ bs.init({ bs.reload(); +browserSync.use( + { + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(opts); + }, + "plugin:name": "test" + }, + { files: "*.css" } +); + +browserSync.use({ + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(bs.name); + } +}); + +browserSync( + { + server: { + baseDir: "test/fixtures" + }, + logLevel: "silent", + open: false + } +); + +var instanceName = "TestInstance"; +var namedInstance = browserSync.create(instanceName); +namedInstance.init({ + server: { index: "./app" }, + https: true +}); + +console.log(namedInstance.getOption("https")); // Should output true. + +var existingInstance = browserSync.get(instanceName); + +browserSync.create("InstanceWithEventEmitter", new EventEmitter()); + +// Should output something greater than 0. +console.log(browserSync.instances.length); + +browserSync.reset(); + +// Should output 0. +console.log(browserSync.instances.length); + +var cleanupTestInstance = browserSync.create("CleanupTest"); +cleanupTestInstance.cleanup(); +console.log(cleanupTestInstance.active); // Should output false. + function browserSyncInit(): browserSync.BrowserSyncInstance { var browser = browserSync.create(); browser.init(); diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index de0a457266..bcf0aa966e 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -456,11 +456,15 @@ declare namespace browserSync { * depending on your use-case. */ (config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * + */ + instances: Array; /** * Create a Browsersync instance * @param name an identifier that can used for retrieval later */ - create(name?: string): BrowserSyncInstance; + create(name?: string, emitter?: NodeJS.EventEmitter): BrowserSyncInstance; /** * Get a single instance by name. This is useful if you have your build scripts in separate files * @param name the identifier used for retrieval @@ -471,6 +475,11 @@ declare namespace browserSync { * @param name the name of the instance */ has(name: string): boolean; + /** + * Reset the state of the module. + * (should only be needed for test environments) + */ + reset(): void; } interface BrowserSyncInstance { @@ -481,6 +490,24 @@ declare namespace browserSync { * depending on your use-case. */ init(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; /** * Reload the browser * The reload method will inform all browsers about changed files and will either cause the browser @@ -510,28 +537,30 @@ declare namespace browserSync { */ stream(opts?: StreamOptions): NodeJS.ReadWriteStream; /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 + * Instance Cleanup. */ - notify(message: string, timeout?: number): void; + cleanup(fn?: (error: NodeJS.ErrnoException, bs: BrowserSyncInstance) => void): void; /** - * This method will close any running server, stop file watching & exit the current process. + * Register a plugin. + * Must implement at least a 'plugin' property that returns + * callable function. + * + * @method use + * @param {object} module The object to be `required`. + * @param {object} options The + * @param {any} cb A callback function that will return any errors. */ - exit(): void; + use(module: { "plugin:name"?: string, plugin: (opts: object, bs: BrowserSyncInstance) => any }, options?: object, cb?: any): void; + /** + * Callback helper to examine what options have been set. + * @param {string} name The key to search options map for. + */ + getOption(name: string): any; /** * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system */ watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; /** * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use * this to emit your own events, such as changed files, logging etc. diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 3b0feb0113..4d30097478 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -182,7 +182,7 @@ export class ObjectID { * @param {number} time optional parameter allowing to pass in a second based timestamp. * @return {string} return the 12 byte id binary string. */ - generate(time?: number): string; + generate(time?: number): Buffer; /** * Returns the generation date (accurate up to the second) that this ID was generated. * @return {date} the generation date diff --git a/types/buffer-from/buffer-from-tests.ts b/types/buffer-from/buffer-from-tests.ts new file mode 100644 index 0000000000..8fdd4fa811 --- /dev/null +++ b/types/buffer-from/buffer-from-tests.ts @@ -0,0 +1,6 @@ +import bufferFrom = require('buffer-from'); + +bufferFrom([1, 2, 3, 4]); // $ExpectType Buffer +bufferFrom(new Uint8Array([1, 2, 3, 4]).buffer, 1, 2); // $ExpectType Buffer +bufferFrom('test', 'utf8'); // $ExpectType Buffer +bufferFrom(bufferFrom('test')); // $ExpectType Buffer diff --git a/types/buffer-from/index.d.ts b/types/buffer-from/index.d.ts new file mode 100644 index 0000000000..412056ed8a --- /dev/null +++ b/types/buffer-from/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for buffer-from 1.1 +// Project: https://github.com/LinusU/buffer-from#readme +// Definitions by: Nat Burns +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function bufferFrom(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; +declare function bufferFrom(str: string, encoding?: string): Buffer; +declare function bufferFrom(data: ReadonlyArray | Buffer): Buffer; + +export = bufferFrom; diff --git a/types/buffer-from/tsconfig.json b/types/buffer-from/tsconfig.json new file mode 100644 index 0000000000..195d0a78b6 --- /dev/null +++ b/types/buffer-from/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-from-tests.ts" + ] +} diff --git a/types/buffer-from/tslint.json b/types/buffer-from/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buffer-from/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/buffer-reader/buffer-reader-tests.ts b/types/buffer-reader/buffer-reader-tests.ts new file mode 100644 index 0000000000..9868131c93 --- /dev/null +++ b/types/buffer-reader/buffer-reader-tests.ts @@ -0,0 +1,28 @@ +import BufferReader from 'buffer-reader'; + +const buffer = new Buffer(1000); +const reader = new BufferReader(buffer); +reader.append(new Buffer(1)); +reader.tell(); +reader.seek(1); +reader.move(2); +reader.restAll(); +reader.nextBuffer(2); +reader.nextString(5); +reader.nextString(5, 'utf8'); +reader.nextStringZero(); +reader.nextStringZero('utf8'); +reader.nextInt8(); +reader.nextUInt8(); +reader.nextInt16LE(); +reader.nextUInt16LE(); +reader.nextInt16BE(); +reader.nextUInt16BE(); +reader.nextInt32LE(); +reader.nextUInt32LE(); +reader.nextInt32BE(); +reader.nextUInt32BE(); +reader.nextFloatLE(); +reader.nextFloatBE(); +reader.nextDouble32LE(); +reader.nextDouble32BE(); diff --git a/types/buffer-reader/index.d.ts b/types/buffer-reader/index.d.ts new file mode 100644 index 0000000000..e83f081e69 --- /dev/null +++ b/types/buffer-reader/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for buffer-reader 0.1 +// Project: https://github.com/villadora/node-buffer-reader +// Definitions by: nrlquaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +export = BufferReader; + +declare class BufferReader { + /** + * Create a new reader, if no buffer provided, a empty buffer will be used. + */ + constructor(buffer?: Buffer) + /** + * Append new buffer to the end of current reader. + * @param buffer buffer to append + */ + append(buffer: Buffer): void; + /** + * Return current position of the reader. + */ + tell(): number; + /** + * Set new position of the reader, if the pos is invalid, an exception will be raised. + * @param position new position + */ + seek(position: number): void; + /** + * Move the position of reader by offset, offset can be negative; it can be used to skip some bytes. + * @param offset offset to move by + */ + move(offset: number): void; + /** + * Get all the remaining bytes as a Buffer. + */ + restAll(): Buffer; + /** + * Read a buffer with specified length. + * @param length specified length + */ + nextBuffer(length: number): Buffer; + /** + * Read next length of bytes as String, encoding default is 'utf8'. + * @param length length of the string to read + * @param encoding encoding of the string + */ + nextString(length: number, encoding?: string): string; + /** + * Read next bytes till the end of buffer as null-terminated string, encoding default is 'utf8'. + * @param encoding encoding of the string + */ + nextStringZero(encoding?: string): string; + /** + * Read next bytes as Int8, the value is just as the same format Buffer in nodejs doc. + */ + nextInt8(): number; + /** + * Read next bytes as UInt8, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt8(): number; + /** + * Read next bytes as Int16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16LE(): number; + /** + * Read next bytes as UInt16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16LE(): number; + /** + * Read next bytes as Int16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16BE(): number; + /** + * Read next bytes as UInt16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16BE(): number; + /** + * Read next bytes as Int32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32LE(): number; + /** + * Read next bytes as UInt32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32LE(): number; + /** + * Read next bytes as Int32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32BE(): number; + /** + * Read next bytes as UInt32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32BE(): number; + /** + * Read next bytes as FloatLE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatLE(): number; + /** + * Read next bytes as FloatBE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatBE(): number; + /** + * Read next bytes as Double32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32LE(): number; + /** + * Read next bytes as Double32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32BE(): number; +} diff --git a/types/buffer-reader/tsconfig.json b/types/buffer-reader/tsconfig.json new file mode 100644 index 0000000000..da70d80fe1 --- /dev/null +++ b/types/buffer-reader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-reader-tests.ts" + ] +} diff --git a/types/buffer-reader/tslint.json b/types/buffer-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buffer-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-spies/chai-spies-tests.ts b/types/chai-spies/chai-spies-tests.ts index f5247ba13f..7bc9530164 100644 --- a/types/chai-spies/chai-spies-tests.ts +++ b/types/chai-spies/chai-spies-tests.ts @@ -24,7 +24,12 @@ let array = [ 1, 2, 3 ]; chai.spy.on(array, 'push'); // or you can track multiple object's methods -chai.spy.on(array, 'push', 'pop'); +chai.spy.on(array, ['push', 'pop']); + +// or you can track multiple object's methods +chai.spy.on(array, 'push', function(item) { + array.push(item); +}); array.push(5); @@ -149,4 +154,20 @@ spy.should.not.have.been.called.above(3); expect(spy).to.have.been.called.below(3); expect(spy).to.not.have.been.called.lt(3); spy.should.have.been.called.lt(3); -spy.should.not.have.been.called.below(3); \ No newline at end of file +spy.should.not.have.been.called.below(3); + +// You can also create sandbox +let sb = chai.spy.sandbox(); + +sb.on(array, 'pop', () => { + return 1; +}) + +let one = array.pop(); +expect(one).to.equal(1); + +// Can restore methods in sandbox +sb.restore(); +array.push(2); +let two = array.pop(); +expect(two).to.equal(2); diff --git a/types/chai-spies/index.d.ts b/types/chai-spies/index.d.ts index 75f702ca37..bb37fa8cd4 100644 --- a/types/chai-spies/index.d.ts +++ b/types/chai-spies/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for chai-spies +// Type definitions for chai-spies 1.0.0 // Project: https://github.com/chaijs/chai-spies // Definitions by: Ilya Kuznetsov +// Harm van der Werf +// Jouni Suorsa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,7 +23,7 @@ declare namespace Chai { * ```ts * expect(spy).to.be.spy; * spy.should.be.spy; - * ``` + * ``` */ spy: Assertion; @@ -32,7 +34,7 @@ declare namespace Chai { * expect(spy).to.have.been.called(); * spy.should.have.been.called(); * ``` - * Note that ```called``` can be used as a chainable method. + * Note that ```called``` can be used as a chainable method. */ called: ChaiSpies.Called; @@ -61,7 +63,32 @@ declare namespace Chai { } declare namespace ChaiSpies { + interface Sandbox { + /** + * #### chai.spy.on (function) + * + * Wraps an object method into spy. All calls will pass through to the original function. + * + * @param {Object} object + * @param {String} methodNames names to spy on + * @param {function} fn replacement function + * @returns function to actually call + */ + on(object: Object, methodNames: string | string[], fn?: (parameters: any[]|any) => any): any; + /** + * #### chai.spy.restore (function) + * + * Restores previously wrapped object's method. + * Restores all spied objects of a sandbox if called without parameters. + * + * @function + * @param {Object} [object] + * @param {String|String[]} [methods] name or names + * @return {Sandbox} Sandbox instance + */ + restore(object?: Object, methodNames?: string | string[]): void; + } interface Spy { /** * #### chai.spy (function) @@ -72,9 +99,9 @@ declare namespace ChaiSpies { * var spy = chai.spy(original) * , e_spy = chai.spy(); * ``` - * @param fn function to spy on. @default ```function () {}``` + * @param fn function to spy on. @default ```function () {}``` * @returns function to actually call - */ + */ (): SpyFunc0Proxy; (fn: SpyFunc0): SpyFunc0Proxy; (fn: SpyFunc1): SpyFunc1Proxy; @@ -107,10 +134,11 @@ declare namespace ChaiSpies { * var spy = chai.spy.on(Array, 'isArray'); * ``` * @param {Object} object - * @param {String} method name to spy on + * @param {String} method names to spy on + * @param {function} fn replacement function * @returns function to actually call - */ - on(object: Object, ...methodNames: string[]): any; + */ + on(object: Object, methodNames: string | string[], fn?: (parameters: any[]|any) => any): any; /** * #### chai.spy.object (function) @@ -123,10 +151,24 @@ declare namespace ChaiSpies { * @param {String[]|Object} method names or method definitions * @returns object with spied methods */ - object(name: string, methods: string[]): any; - object(methods: string[]): any; - object(name: string, methods: T): T; - object(methods: T): T; + object(name: string, methods: string[]): any; + object(methods: string[]): any; + object(name: string, methods: T): T; + object(methods: T): T; + + /** + * #### chai.spy.restore (function) + * + * Restores spy assigned to DEFAULT sandbox + * + * Restores previously wrapped object's method. + * Restores all spied objects of a sandbox if called without parameters. + * + * @param {Object} [object] + * @param {String|String[]} [methods] name or names + * @return {Sandbox} Sandbox instance + */ + restore(object?: Object, methodNames?: string | string[]): void; /** * #### chai.spy.returns (function) @@ -141,6 +183,18 @@ declare namespace ChaiSpies { */ returns(value: T): SpyFunc0Proxy; + + /** + * ### chai.spy.sandbox + * + * Creates a sandbox. + * + * Sandbox is a set of spies. + * Sandbox allows to track methods on objects and restore original methods with on restore call. + * + * @returns {Sandbox} + */ + sandbox(): Sandbox; } interface Called { @@ -158,12 +212,12 @@ declare namespace ChaiSpies { * spy.should.not.have.been.called.once; * ``` */ - once: Chai.Assertion; + once: Chai.Assertion; /** * ####.twice * Assert that a spy has been called exactly twice. - * ```ts + * ```ts * expect(spy).to.have.been.called.twice; * expect(spy).to.not.have.been.called.twice; * spy.should.have.been.called.twice; @@ -215,7 +269,7 @@ declare namespace ChaiSpies { * ```ts * expect(spy).to.have.been.called.above(3); * spy.should.not.have.been.called.above(3); - * ``` + * ``` */ above(n: number): Chai.Assertion; @@ -225,7 +279,7 @@ declare namespace ChaiSpies { * ```ts * expect(spy).to.have.been.called.gt(3); * spy.should.not.have.been.called.gt(3); - * ``` + * ``` */ gt(n: number): Chai.Assertion; @@ -235,7 +289,7 @@ declare namespace ChaiSpies { * ```ts * expect(spy).to.have.been.called.below(3); * spy.should.not.have.been.called.below(3); - * ``` + * ``` */ below(n: number): Chai.Assertion; @@ -245,7 +299,7 @@ declare namespace ChaiSpies { * ```ts * expect(spy).to.have.been.called.lt(3); * spy.should.not.have.been.called.lt(3); - * ``` + * ``` */ lt(n: number): Chai.Assertion; } @@ -301,7 +355,7 @@ declare namespace ChaiSpies { * spy.should.have.been.called.with('foo'); * ``` * Will also pass for ```spy('foo', 'bar')``` and ```spy(); spy('foo')```. - * If used with multiple arguments, assert that a spy has been called with all the given arguments at least once. + * If used with multiple arguments, assert that a spy has been called with all the given arguments at least once. * ```ts * spy('foo', 'bar', 1); * expect(spy).to.have.been.called.with('bar', 'foo'); @@ -389,7 +443,7 @@ declare namespace ChaiSpies { * * Resets __spy object parameters for instantiation and reuse * @returns proxy spy object - */ + */ reset(): this; } @@ -397,77 +451,77 @@ declare namespace ChaiSpies { (): R; } - interface SpyFunc1 { - (a: A1): R; + interface SpyFunc1 { + (a: A1): R; } - interface SpyFunc2 { - (a: A1, b: A2): R; + interface SpyFunc2 { + (a: A1, b: A2): R; } - interface SpyFunc3 { - (a: A1, b: A2, c: A3): R; + interface SpyFunc3 { + (a: A1, b: A2, c: A3): R; } - interface SpyFunc4 { - (a: A1, b: A2, c: A3, d: A4): R; + interface SpyFunc4 { + (a: A1, b: A2, c: A3, d: A4): R; } - interface SpyFunc5 { - (a: A1, b: A2, c: A3, d: A4, e: A5): R; + interface SpyFunc5 { + (a: A1, b: A2, c: A3, d: A4, e: A5): R; } - interface SpyFunc6 { - (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6): R; + interface SpyFunc6 { + (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6): R; } - interface SpyFunc7 { - (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7): R; + interface SpyFunc7 { + (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7): R; } - interface SpyFunc8 { - (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8): R; + interface SpyFunc8 { + (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8): R; } - - interface SpyFunc9 { - (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9): R; + + interface SpyFunc9 { + (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9): R; } - - interface SpyFunc10 { - (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9, j: A10): R; + + interface SpyFunc10 { + (a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9, j: A10): R; } interface SpyFunc0Proxy extends SpyFunc0, Resetable { } - interface SpyFunc1Proxy extends SpyFunc1, Resetable { + interface SpyFunc1Proxy extends SpyFunc1, Resetable { } - interface SpyFunc2Proxy extends SpyFunc2, Resetable { + interface SpyFunc2Proxy extends SpyFunc2, Resetable { } - interface SpyFunc3Proxy extends SpyFunc3, Resetable { + interface SpyFunc3Proxy extends SpyFunc3, Resetable { } - interface SpyFunc4Proxy extends SpyFunc4, Resetable { + interface SpyFunc4Proxy extends SpyFunc4, Resetable { } - interface SpyFunc5Proxy extends SpyFunc5, Resetable { + interface SpyFunc5Proxy extends SpyFunc5, Resetable { } - interface SpyFunc6Proxy extends SpyFunc6, Resetable { + interface SpyFunc6Proxy extends SpyFunc6, Resetable { } - interface SpyFunc7Proxy extends SpyFunc7, Resetable { + interface SpyFunc7Proxy extends SpyFunc7, Resetable { } - interface SpyFunc8Proxy extends SpyFunc8, Resetable { + interface SpyFunc8Proxy extends SpyFunc8, Resetable { } - - interface SpyFunc9Proxy extends SpyFunc9, Resetable { + + interface SpyFunc9Proxy extends SpyFunc9, Resetable { } - - interface SpyFunc10Proxy extends SpyFunc10, Resetable { + + interface SpyFunc10Proxy extends SpyFunc10, Resetable { } } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index f19514fe71..2c81c42aeb 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1361,6 +1361,39 @@ suite('assert', () => { assert.notDeepEqual(circularObject, secondCircularObject); }); + test('deepStrictEqual', () => { + assert.deepStrictEqual({tea: 'chai'}, {tea: 'chai'}); + assert.throws(() => assert.deepStrictEqual({tea: 'chai'}, {tea: 'black'})); + + const obja = Object.create({tea: 'chai'}); + const objb = Object.create({tea: 'chai'}); + + assert.deepStrictEqual(obja, objb); + + const obj1 = Object.create({tea: 'chai'}); + const obj2 = Object.create({tea: 'black'}); + + assert.throws(() => assert.deepStrictEqual(obj1, obj2)); + }); + + test('deepStrictEqual (ordering)', () => { + const a = {a: 'b', c: 'd'}; + const b = {c: 'd', a: 'b'}; + assert.deepStrictEqual(a, b); + }); + + test('deepStrictEqual (circular)', () => { + const circularObject: any = {}; + const secondCircularObject: any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepStrictEqual(circularObject, secondCircularObject); + + secondCircularObject.field2 = secondCircularObject; + assert.deepStrictEqual(circularObject, secondCircularObject); + }); + test('isNull', () => { assert.isNull(null); assert.isNull(undefined); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index d0f5ab099c..d260973b71 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -353,7 +353,7 @@ declare namespace Chai { notStrictEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is deeply equal to expected. + * Asserts that actual is deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -363,7 +363,7 @@ declare namespace Chai { deepEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is not deeply equal to expected. + * Asserts that actual is not deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -372,6 +372,16 @@ declare namespace Chai { */ notDeepEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts that actual is deeply strict equal (===) to expected. + * + * @type T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + /** * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index cb3db72855..8063cf2629 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -506,6 +506,7 @@ declare namespace Chart { } interface CommonAxe { + bounds?: string; type?: ScaleType | string; display?: boolean; id?: string; diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index 53ba63497c..270e6e0970 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -247,7 +247,7 @@ new Chartist.Pie('.ct-chart', { value: 70, name: 'Series 3', className: 'my-custom-class-three', - meta: 'Meta Three' + meta: { description: 'Meta Three' } }] }); diff --git a/types/chartist/index.d.ts b/types/chartist/index.d.ts index a4fb2c832d..80cc589ee2 100644 --- a/types/chartist/index.d.ts +++ b/types/chartist/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chartist v0.9.81 // Project: https://github.com/gionkunz/chartist-js -// Definitions by: Matt Gibbs , Simon Pfeifer , Cassey Lottman , Anastasiia Antonova +// Definitions by: Matt Gibbs , Simon Pfeifer , Cassey Lottman , Anastasiia Antonova , Sunny Juneja // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Chartist { @@ -101,7 +101,7 @@ declare namespace Chartist { value?: number; data?: Array; className?: string; - meta?: string; // I assume this could probably be a number as well? + meta?: any; } interface IChartistBase { diff --git a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts new file mode 100644 index 0000000000..21adf13fb0 --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts @@ -0,0 +1,92 @@ +import { Break, BreakClip } from "./cast.framework.messages"; + +export = cast.framework.breaks; + +declare namespace cast.framework.breaks { + class BreakSeekData { + constructor(seekFrom: number, seekTo: number, breaks: Break[]); + + /** + * List of breaks + */ + breaks: Break[]; + + /** + * Current playback time + */ + seekFrom: number; + + /** + * The time to seek to + */ + seekTo: number; + } + + /** Provide context information for break clip load interceptor. */ + class BreakClipLoadInterceptorContext { + constructor(brk: Break); + + /** + * The container break for the break clip + */ + break: Break; + } + + /** Interface to manage breaks */ + interface BreakManager { + /** + * Get current media break by id. + */ + getBreakById(id: string): Break; + + /** + * Get current media break clip by id + */ + getBreakClipById(id: string): BreakClip; + + /** Get current media break clips. */ + getBreakClips(): BreakClip[]; + + /** Get current media breaks. */ + getBreaks(): Break[]; + + /** Returns true if watched breaks should be played. */ + getPlayWatchedBreak(): boolean; + + /** + * Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started. + * If interceptor is null it will reset the interceptor to default one. + * By default VAST fetching and parsing logic in default interceptor. + * So if customized interceptor is set by developer; + * the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor. + */ + setBreakClipLoadInterceptor( + interceptor: ( + breakClip: BreakClip, + breakClipLoaderContext?: BreakClipLoadInterceptorContext + ) => void + ): void; + + /** + * Provide an interceptor for developer to specify what breaks they want to play after seek. + */ + setBreakSeekInterceptor( + seekInterceptor: (breakSeekData: BreakSeekData) => void + ): void; + + /** + * Set a flag to control if the watched client stitching break should be played. + */ + setPlayWatchedBreak(playWatchedBreak: boolean): void; + + /** + * Provide an interceptor to modify VAST tracking URL before it is being sent to server. + * The input of the interceptor is a string of the tracking URL. + * The interceptor can either return a modified string of URL or a Promise of modified string of URL. + * The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF. + */ + setVastTrackingInterceptor( + interceptor?: (trackingUrl: string) => void + ): void; + } +} diff --git a/types/chromecast-caf-receiver/cast.framework.d.ts b/types/chromecast-caf-receiver/cast.framework.d.ts new file mode 100644 index 0000000000..28b0c69e2d --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.d.ts @@ -0,0 +1,783 @@ +import { EventType } from "./cast.framework.events"; +import { + PlayerState, + PlayStringId, + ErrorType, + ErrorReason, + IdleReason, + MessageType, + Track, + TextTrackStyle, + QueueItem, + LoadRequestData, + QueueData, + Break, + LiveSeekableRange, + MediaInformation, + ErrorData, + RequestData +} from "./cast.framework.messages"; +import { BreakManager } from "./cast.framework.breaks"; +import { EventHandler, RequestHandler, BinaryHandler } from "./index"; +import { + EventType as SystemEventType, + ApplicationData, + Sender, + StandbyState, + SystemState +} from "./cast.framework.system"; + +export = cast.framework; +type HTMLMediaElement = any; +declare namespace cast.framework { + type LoggerLevel = + | "DEBUG" + | "VERBOSE" + | "INFO" + | "WARNING" + | "ERROR" + | "NONE"; + + type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE"; + + /** + * Manages text tracks. + */ + class TextTracksManager { + constructor(params?: any); + + /** + * Adds text tracks to the list. + */ + addTracks(tracks: Track[]): void; + + /** + * Creates a text track. + */ + createTrack(): Track; + + /** + * Gets all active text ids. + */ + getActiveIds(): number[]; + + /** + * Gets all active text tracks. + */ + getActiveTracks(): Track[]; + + /** + * Returns the current text track style. + */ + getTextTracksStyle(): TextTrackStyle; + + /** + * Gets text track by id. + */ + getTrackById(id: number): Track; + + /** + * Returns all text tracks. + */ + getTracks(): Track[]; + + /** + * Gets text tracks by language. + */ + getTracksByLanguage(language: string): Track[]; + + /** + * Sets text tracks to be active by id. + */ + setActiveByIds(newIds: number[]): void; + + /** + * Sets text tracks to be active by language. + */ + setActiveByLanguage(language: string): void; + + /** + * Sets text track style. + */ + setTextTrackStyle(style: TextTrackStyle): void; + } + + /** + * QueueManager exposes several queue manipulation APIs to developers. + */ + class QueueManager { + constructor(params?: any); + + /** + * Returns the current queue item. + */ + getCurrentItem(): QueueItem; + + /** + * Returns the index of the current queue item. + */ + getCurrentItemIndex(): number; + + /** + * Returns the queue items. + */ + getItems(): QueueItem[]; + + /** + * Inserts items into the queue. + */ + insertItems(items: QueueItem[], insertBefore?: number): void; + + /** + * Removes items from the queue. + */ + removeItems(itemIds: number[]): void; + + /** + * Sets whether to limit the number of queue items to be reported in Media Status (default is true). + */ + setQueueStatusLimit(limitQueueItemsInStatus: boolean): void; + + /** + * Updates existing queue items by matching itemId. + */ + updateItems(items: QueueItem[]): void; + } + + /** + * Base implementation of a queue. + */ + class QueueBase { + /** + * Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items; + * often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before + * the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned. + */ + fetchItems( + itemId: number, + nextCount: number, + prevCount: number + ): QueueItem[] | Promise; + + /** + * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. + * If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media + * in the load request data. + */ + initialize( + requestData: LoadRequestData + ): QueueData | Promise; + + /** + * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. + */ + nextItems(itemId?: number): QueueItem[] | Promise; + + /** + * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. + */ + onCurrentItemIdChanged(itemId: number): void; + + /** + * A callback for informing the following items have been inserted into the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsInserted(items: QueueItem[], insertBefore?: number): void; + + /** + * A callback for informing the following items have been removed from the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsRemoved(itemIds: number[]): void; + + /** + * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. + */ + prevItems(itemId?: number): QueueItem[] | Promise; + + /** + * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. + */ + shuffle(): QueueItem[] | Promise; + } + + /** + * Controls and monitors media playback. + */ + class PlayerManager { + constructor(params?: any); + + /** + * Adds an event listener for player event. + */ + addEventListener: ( + eventType: EventType | EventType[], + eventListener: EventHandler + ) => void; + + /** + * Sends a media status message to all senders (broadcast). Applications use this to send a custom state change. + */ + broadcastStatus( + includeMedia?: boolean, + requestId?: number, + customData?: any, + includeQueueItems?: boolean + ): void; + + getAudioTracksManager(): AudioTracksManager; + + /** + * Returns current time in sec in currently-playing break clip. + */ + getBreakClipCurrentTimeSec(): number; + + /** + * Returns duration in sec of currently-playing break clip. + */ + getBreakClipDurationSec(): number; + + /** + * Obtain the breaks (Ads) manager. + */ + getBreakManager(): BreakManager; + + /** + * Returns list of breaks. + */ + getBreaks(): Break[]; + + /** + * Gets current time in sec of current media. + */ + getCurrentTimeSec(): number; + + /** + * Gets duration in sec of currently playing media. + */ + getDurationSec(): number; + + /** + * Returns live seekable range with start and end time in seconds. The values are media time based. + */ + getLiveSeekableRange(): LiveSeekableRange; + + /** + * Gets media information of current media. + */ + getMediaInformation(): MediaInformation; + + /** + * Returns playback configuration. + */ + getPlaybackConfig(): PlaybackConfig; + + /** + * Returns current playback rate. + */ + getPlaybackRate(): number; + + /** + * Gets player state. + */ + getPlayerState(): PlayerState; + + /** + * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; + * so it can be used in next session in the cast options). + */ + getPreferredPlaybackRate(): number; + + /** + * Get the preferred text track language. + */ + getPreferredTextLanguage(): string; + + /** + * Obtain QueueManager API. + */ + getQueueManager(): QueueManager; + + getTextTracksManager(): TextTracksManager; + + /** + * Loads media. + */ + load(loadRequest: LoadRequestData): Promise; + + /** + * Pauses currently playing media. + */ + pause(): void; + + /** + * Plays currently paused media. + */ + play(): void; + + /** + * Requests a text string to be played back locally on the receiver device. + */ + playString(stringId: PlayStringId, args?: string[]): Promise; + + /** + * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. + */ + refreshCredentials(): Promise; + + /** + * Removes the event listener added for given player event. If event listener is not added; it will be ignored. + */ + removeEventListener( + eventType: EventType | EventType[], + eventListener: EventHandler + ): void; + + /** + * Seeks in current media. + */ + seek(seekTime: number): void; + + /** + * Sends an error to a specific sender + */ + sendError( + senderId: string, + requestId: number, + type: ErrorType, + reason?: ErrorReason, + customData?: any + ): void; + + /** + * Send local media request. + */ + sendLocalMediaRequest(request: RequestData): void; + + /** + * Sends a media status message to a specific sender. + */ + sendStatus( + senderId: string, + requestId: number, + includeMedia?: boolean, + customData?: any, + includeQueueItems?: boolean + ): void; + + /** + * Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state + * (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value; + * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended + * behavior. + */ + setIdleReason(idleReason: IdleReason): void; + + /** + * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. + */ + setMediaElement(mediaElement: HTMLMediaElement): void; + + /** + * Sets media information. + */ + setMediaInformation( + mediaInformation: MediaInformation, + opt_broadcast?: boolean + ): void; + + /** + * Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data + * and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config; + * or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server. + */ + setMediaPlaybackInfoHandler( + handler: ( + loadRequestData: LoadRequestData, + playbackConfig: PlaybackConfig + ) => void + ): void; + + /** + * Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part + * of the media status. By default the media contentId is used as the content url. + */ + setMediaUrlResolver( + resolver: (loadRequestData: LoadRequestData) => void + ): void; + + /** + * Provide an interceptor of incoming and outgoing messages. + * The interceptor can update the request data; and return updated data; a promise of + * updated data if need to get more data from the server; or null if the request should not be handled. + * Note that if load message interceptor is provided; and no interceptor is provided for preload - + * the load interceptor will be called for preload messages. + */ + setMessageInterceptor( + type: MessageType, + interceptor: (requestData: RequestData) => Promise + ): void; + + /** + * Sets playback configuration on the PlayerManager. + */ + setPlaybackConfig(playbackConfig: PlaybackConfig): void; + + /** + * Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest + * playback rate that was provided by a load request or explicit set of playback rate. + */ + setPreferredPlaybackRate(preferredPlaybackRate: number): void; + + /** + * Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language + * by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media). + */ + setPreferredTextLanguage(preferredTextLanguage: string): void; + + /** + * Stops currently playing media. + */ + stop(): void; + } + + /** + * Configuration to customize playback behavior. + */ + class PlaybackConfig { + /** + * Duration of buffered media in seconds to start buffering. + */ + autoPauseDuration?: number; + + /** + * Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering. + */ + autoResumeDuration?: number; + + /** + * Minimum number of buffered segments to start/resume playback. + */ + autoResumeNumberOfSegments?: number; + + /** + * A function to customize request to get a caption segment. + */ + captionsRequestHandler?: RequestHandler; + + /** + * Initial bandwidth in bits in per second. + */ + initialBandwidth?: number; + + /** + * Custom license data. + */ + licenseCustomData?: string; + + /** + * Handler to process license data. The handler is passed the license data; and returns the modified license data. + */ + licenseHandler?: BinaryHandler; + + /** + * A function to customize request to get a license. + */ + licenseRequestHandler?: RequestHandler; + + /** + * Url for acquiring the license. + */ + licenseUrl?: string; + + /** + * Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest. + */ + manifestHandler?: (manifest: string) => string; + + /** + * A function to customize request to get a manifest. + */ + manifestRequestHandler?: RequestHandler; + + /** + * Preferred protection system to use for decrypting content. + */ + protectionSystem: ContentProtection; + + /** + * Handler to process segment data. The handler is passed the segment data; and returns the modified segment data. + */ + segmentHandler?: BinaryHandler; + + /** + * A function to customize request information to get a media segment. + */ + segmentRequestHandler?: RequestHandler; + + /** + * Maximum number of times to retry a network request for a segment. + */ + segmentRequestRetryLimit?: number; + } + /** + * HTTP(s) Request/Response information. + */ + class NetworkRequestInfo { + /** + * The content of the request. Can be used to modify license request body. + */ + content: Uint8Array; + + /** + * An object containing properties that you would like to send in the header. + */ + headers: any; + + /** + * The URL requested. + */ + url: string; + + /** + * Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers. + */ + withCredentials: boolean; + } + /** Cast receiver context options. All options are optionals. */ + class CastReceiverOptions { + /** + * Optional map of custom messages namespaces to initialize and their types. + * Custom messages namespaces need to be initiated before the application started; + * so it is best to provide the namespaces in the receiver options. + * (The default type of a message bus is JSON; if not provided here). + */ + customNamespaces?: any; + + /** + * Sender id used for local requests. Default value is 'local'. + */ + localSenderId?: string; + + /** + * Maximum time in seconds before closing an idle sender connection. + * Setting this value enables a heartbeat message to keep the connection alive. + * Used to detect unresponsive senders faster than typical TCP timeouts. + * The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play. + * Default value is 10 seconds. + */ + maxInactivity?: number; + + /** + * Optional media element to play content with. Default behavior is to use the first found media element in the page. + */ + mediaElement?: HTMLMediaElement; + + /** + * Optional playback configuration. + */ + playbackConfig?: PlaybackConfig; + + /** + * If this is true; the watched client stitching break will also be played. + */ + playWatchedBreak?: boolean; + + /** + * Preferred value for player playback rate. It is used if playback rate value is not provided in the load request. + */ + preferredPlaybackRate?: number; + + /** + * Preferred text track language. It is used if no active track is provided in the load request. + */ + preferredTextLanguage?: string; + + /** + * Optional queue implementation. + */ + queue?: QueueBase; + + /** + * Text that represents the application status. + * It should meet internationalization rules as may be displayed by the sender application. + */ + statusText?: string; + + /** + * A bitmask of media commands supported by the application. + * LOAD; PLAY; STOP; GET_STATUS must always be supported. + * If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too. + */ + supportedCommands?: number; + + /** + * Indicate that MPL should be used for DASH content. + */ + useLegacyDashSupport?: boolean; + + /** + * An integer used as an internal version number. + * This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases. + */ + versionCode?: number; + } + + /** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */ + class CastReceiverContext { + /** Returns the CastReceiverContext singleton instance. */ + static getInstance(): CastReceiverContext; + + constructor(params: any); + + /** + * Sets message listener on custom message channel. + */ + addCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Add listener to cast system events. + */ + addEventListener( + type: SystemEventType | SystemEventType[], + handler: EventHandler + ): void; + + /** + * Checks if the given media params of video or audio streams are supported by the platform. + */ + canDisplayType( + mimeType: string, + codecs?: string, + width?: number, + height?: number, + framerate?: number + ): boolean; + + /** + * Provides application information once the system is ready; otherwise it will be null. + */ + getApplicationData(): ApplicationData; + + /** + * Provides device capabilities information once the system is ready; otherwise it will be null. + * If an empty object is returned; the device does not expose any capabilities information. + */ + getDeviceCapabilities(): any; + + /** + * Get Player instance that can control and monitor media playback. + */ + getPlayerManager(): PlayerManager; + + /** + * Get a sender by sender id + */ + getSender(senderId: string): Sender; + + /** + * Gets a list of currently-connected senders. + */ + getSenders(): Sender[]; + + /** + * Reports if the cast application's HDMI input is in standby. + */ + getStandbyState(): StandbyState; + + /** + * Provides application information about the system state. + */ + getSystemState(): SystemState; + + /** + * Reports if the cast application is the HDMI active input. + */ + getVisibilityState(): any; + + /** + * When the application calls start; the system will send the ready event to indicate + * that the application information is ready and the application can send messages as soon as there is one sender connected. + */ + isSystemReady(): boolean; + + /** + * Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start. + * This function is a no-op if players were already loaded (start was called). + */ + loadPlayerLibraries(useLegacyDashSupport?: boolean): void; + + /** + * Remove a message listener on custom message channel. + */ + removeCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Remove listener to cast system events. + */ + removeEventListener(type: EventType, handler: EventHandler): void; + + /** + * Sends a message to a specific sender. + */ + sendCustomMessage( + namespace: string, + senderId: string, + message: any + ): void; + + /** + * This function should be called in response to the feedbackstarted event if the application + * add debug state information to log in the feedback report. + * It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log. + */ + sendFeedbackMessage(feedbackMessage: string): void; + + /** + * Sets the application state. The application should call this when its state changes. + * If undefined or set to an empty string; the value of the Application Name established during application + * registration is used for the application state by default. + */ + setApplicationState(statusText: string): void; + + /** + * Sets the receiver inactivity timeout. + * It is recommended to set the maximum inactivity value when calling Start and not changing it. + * This API is just provided for development/debugging purposes. + */ + setInactivityTimeout(maxInactivity: number): void; + + /** + * Sets the log verbosity level. + */ + setLoggerLevel(level: LoggerLevel): void; + + /** + * Initializes system manager and media manager; so that receiver app can receive requests from senders. + */ + start(options?: CastReceiverOptions): CastReceiverContext; + + /** + * Shutdown receiver application. + */ + stop(): void; + } + + /** Manages audio tracks. */ + class AudioTracksManager { + constructor(params: any); + getActiveId(): number; + getActiveTrack(): Track; + getTrackById(id: number): Track; + getTracks(): Track[]; + getTracksByLanguage(language: string): Track[]; + setActiveById(id: number): void; + setActiveByLanguage(language: string): void; + } +} diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts new file mode 100644 index 0000000000..03b70ca459 --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -0,0 +1,426 @@ +import { + RequestData, + MediaInformation, + Track, + MediaStatus +} from "./cast.framework.messages"; +export = cast.framework.events; + +declare namespace cast.framework.events { + type EventType = + | "ALL" + | "ABORT" + | "CAN_PLAY" + | "CAN_PLAY_THROUGH" + | "DURATION_CHANGE" + | "EMPTIED" + | "ENDED" + | "LOADED_DATA" + | "LOADED_METADATA" + | "LOAD_START" + | "PAUSE" + | "PLAY" + | "PLAYING" + | "PROGRESS" + | "RATE_CHANGE" + | "SEEKED" + | "SEEKING" + | "STALLED" + | "TIME_UPDATE" + | "SUSPEND" + | "WAITING" + | "BITRATE_CHANGED" + | "BREAK_STARTED" + | "BREAK_ENDED" + | "BREAK_CLIP_LOADING" + | "BREAK_CLIP_STARTED" + | "BREAK_CLIP_ENDED" + | "BUFFERING" + | "CACHE_LOADED" + | "CACHE_HIT" + | "CACHE_INSERTED" + | "CLIP_STARTED" + | "CLIP_ENDED" + | "EMSG" + | "ERROR" + | "ID3" + | "MEDIA_STATUS" + | "MEDIA_FINISHED" + | "PLAYER_PRELOADING" + | "PLAYER_PRELOADING_CANCELLED" + | "PLAYER_LOAD_COMPLETE" + | "PLAYER_LOADING" + | "SEGMENT_DOWNLOADED" + | "REQUEST_SEEK" + | "REQUEST_LOAD" + | "REQUEST_STOP" + | "REQUEST_PAUSE" + | "REQUEST_PLAY" + | "REQUEST_PLAY_AGAIN" + | "REQUEST_PLAYBACK_RATE_CHANGE" + | "REQUEST_SKIP_AD" + | "REQUEST_VOLUME_CHANGE" + | "REQUEST_EDIT_TRACKS_INFO" + | "REQUEST_EDIT_AUDIO_TRACKS" + | "REQUEST_SET_CREDENTIALS" + | "REQUEST_LOAD_BY_ENTITY" + | "REQUEST_USER_ACTION" + | "REQUEST_DISPLAY_STATUS" + | "REQUEST_CUSTOM_COMMAND" + | "REQUEST_FOCUS_STATE" + | "REQUEST_QUEUE_LOAD" + | "REQUEST_QUEUE_INSERT" + | "REQUEST_QUEUE_UPDATE" + | "REQUEST_QUEUE_REMOVE" + | "REQUEST_QUEUE_REORDER" + | "REQUEST_QUEUE_GET_ITEM_RANGE" + | "REQUEST_QUEUE_GET_ITEMS" + | "REQUEST_QUEUE_GET_ITEM_IDS" + | "REQUEST_PRECACHE"; + + type DetailedErrorCode = + | "MEDIA_UNKNOWN" + | "MEDIA_ABORTED" + | "MEDIA_DECODE" + | "MEDIA_NETWORK" + | "MEDIA_SRC_NOT_SUPPORTED" + | "SOURCE_BUFFER_FAILURE" + | "MEDIAKEYS_UNKNOWN" + | "MEDIAKEYS_NETWORK" + | "MEDIAKEYS_UNSUPPORTED" + | "MEDIAKEYS_WEBCRYPTO" + | "NETWORK_UNKNOWN" + | "SEGMENT_NETWORK" + | "HLS_NETWORK_MASTER_PLAYLIST" + | "HLS_NETWORK_PLAYLIST" + | "HLS_NETWORK_NO_KEY_RESPONSE" + | "HLS_NETWORK_KEY_LOAD" + | "HLS_NETWORK_INVALID_SEGMENT" + | "HLS_SEGMENT_PARSING" + | "DASH_NETWORK" + | "DASH_NO_INIT" + | "SMOOTH_NETWORK" + | "SMOOTH_NO_MEDIA_DATA" + | "MANIFEST_UNKNOWN" + | "HLS_MANIFEST_MASTER" + | "HLS_MANIFEST_PLAYLIST" + | "DASH_MANIFEST_UNKNOWN" + | "DASH_MANIFEST_NO_PERIODS" + | "DASH_MANIFEST_NO_MIMETYPE" + | "DASH_INVALID_SEGMENT_INFO" + | "SMOOTH_MANIFEST" + | "SEGMENT_UNKNOWN" + | "TEXT_UNKNOWN" + | "APP" + | "BREAK_CLIP_LOADING_ERROR" + | "BREAK_SEEK_INTERCEPTOR_ERROR" + | "IMAGE_ERROR" + | "LOAD_INTERRUPTED" + | "GENERIC"; + + type EndedReason = + | "END_OF_STREAM" + | "ERROR" + | "STOPPED" + | "INTERRUPTED" + | "SKIPPED" + | "BREAK_SWITCH"; + + /** + * Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event. + */ + class SegmentDownloadedEvent extends Event { + constructor(downloadTime?: number, size?: number); + + /** + * The time it took to download the segment; in milliseconds. + */ + downloadTime?: number; + + /** + * The number of bytes in the segment. + */ + size?: number; + } + + /** + * Event data for all events that represent requests made to the receiver. + */ + class RequestEvent extends Event { + constructor( + type: EventType, + requestData?: RequestData, + senderId?: string + ); + + /** + * The data that was sent with the request. + */ + requestData?: RequestData; + + /** + * The sender id the request came from. + */ + senderId?: string; + } + + /** + * Event data superclass for all events dispatched by @see{@link PlayerManager} + */ + class Event { + constructor(type: EventType); + + /** + * Type of the event. + */ + type: EventType; + } + /** + * Event data for @see{@link EventType.MEDIA_STATUS} event. + */ + class MediaStatusEvent extends Event { + constructor(type: EventType, mediaStatus?: MediaStatus); + + /** + * The media status that was sent. + */ + mediaStatus?: MediaStatus; + } + /** + * Event data for pause events forwarded from the MediaElement. + */ + class MediaPauseEvent extends Event { + constructor(currentMediaTime?: number, ended?: boolean); + + /** + * Indicate if the media ended (indicates the pause was fired due to stream reached the end). + */ + ended?: boolean; + } + /** + * Event data for @see{@link EventType.MEDIA_FINISHED} event. + */ + class MediaFinishedEvent extends Event { + constructor(currentMediaTime?: number, endedReason?: EndedReason); + + /** + * The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started). + */ + currentTime?: number; + + /** + * The reason the media finished. + */ + endedReason?: EndedReason; + } + /** + * Event data for all events forwarded from the MediaElement. + */ + class MediaElementEvent extends Event { + constructor(type: EventType, currentMediaTime?: number); + + /** + * The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet. + */ + currentMediaTime?: number; + } + /** + * Event data for all events pertaining to processing a load / preload request. made to the player. + */ + class LoadEvent extends Event { + constructor(type: EventType, media?: MediaInformation); + + /** + * Information about the media being loaded. + */ + media: MediaInformation; + } + /** + * Event data for @see{@link EventType.INBAND_TRACK_ADDED} event. + */ + class InbandTrackAddedEvent { + constructor(track: Track); + + /** + * Added track. + */ + track: Track; + } + + /** Event data for @see{@link EventType.ID3} event. */ + class Id3Event extends Event { + constructor(segmentData: Uint8Array); + + /** + * The segment data. + */ + segmentData: Uint8Array; + } + /** + * Event data for @see{@link EventType.EMSG} event. + */ + class EmsgEvent extends Event { + constructor(emsgData: any); + + /** + * The time that the event ends (in presentation time). Undefined if using legacy Dash support. + */ + endTime: any; + + /** + * The duration of the event (in units of timescale). Undefined if using legacy Dash support. + */ + eventDuration: any; + + /** + * A field identifying this instance of the message. Undefined if using legacy Dash support. + */ + id: any; + + /** + * Body of the message. Undefined if using legacy Dash support. + */ + messageData: any; + + /** + * The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support. + */ + presentationTimeDelta: any; + + /** + * Identifies the message scheme. Undefined if using legacy Dash support. + */ + schemeIdUri: any; + + /** + * The segment data. This is only defined if using legacy Dash support. + */ + segmentData: any; + + /** + * The time that the event starts (in presentation time). Undefined if using legacy Dash support. + */ + startTime: any; + + /** + * Provides the timescale; in ticks per second. Undefined if using legacy Dash support. + */ + timescale: any; + + /** + * Specifies the value for the event. Undefined if using legacy Dash support. + */ + value: any; + } + /** + * Event data for @see{@link EventType.CLIP_ENDED} event. + */ + class ClipEndedEvent extends Event { + constructor(currentMediaTime: number, endedReason?: EndedReason); + + /** + * The time in media (in seconds) when clip ended. + */ + currentMediaTime: number; + + /** + * The reason the clip ended. + */ + endedReason?: EndedReason; + } + + /** + * Event data for @see{@link EventType.CACHE_LOADED} event. + */ + class CacheLoadedEvent extends Event { + constructor(media?: MediaInformation); + + /** + * Information about the media being cached. + */ + media: MediaInformation; + } + + class CacheItemEvent extends Event { + constructor(type: EventType, url: string); + + /** + * The URL of data fetched from cache + */ + url: string; + } + + class BufferingEvent extends Event { + constructor(isBuffering: boolean); + + /** + * True if the player is entering a buffering state. + */ + isBuffering: boolean; + } + + class BreaksEvent extends Event { + constructor( + type: EventType, + currentMediaTime?: number, + index?: number, + total?: number, + whenSkippable?: number, + endedReason?: EndedReason, + breakClipId?: string, + breakId?: string + ); + + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + + /** + * The break clip's id. Refer to BreakClip.id + */ + breakClipId?: string; + + /** + * The time in the currently playing media when the break event occurred. + */ + currentMediaTime?: number; + + /** + * The reason the break clip ended. + */ + endedReason?: EndedReason; + + /** + * Index of break clip; which starts from 1. + */ + index: number; + + /** + * Total number of break clips. + */ + total: number; + + /** + * When to skip current break clip in sec; after break clip begins to play. + */ + whenSkippable?: number; + } + + /** + * Event data for @see {@link EventType.BITRATE_CHANGED} event. + */ + class BitrateChangedEvent { + constructor(totalBitrate?: number); + + /** The bitrate of the media (audio and video) in bits per second. */ + totalBitrate: number; + } + + class ErrorEvent extends Event { + constructor(detailedErrorCode: DetailedErrorCode, error?: any); + + detailedErrorCode: DetailedErrorCode; + error?: any; + } +} diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts new file mode 100644 index 0000000000..d6dda6d145 --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -0,0 +1,1900 @@ +import { Event, DetailedErrorCode } from "./cast.framework.events"; +export = cast.framework.messages; + +declare namespace cast.framework.messages { + type UserAction = + | "LIKE" + | "DISLIKE" + | "FOLLOW" + | "UNFOLLOW" + | "FLAG" + | "SKIP_AD"; + + type UserActionContext = + | "UNKNOWN_CONTEXT" + | "ALBUM" + | "ARTIST" + | "PLAYLIST" + | "EPISODE" + | "SERIES" + | "MOVIE" + | "CHANNEL" + | "TEAM" + | "PLAYER" + | "COACH"; + + type TextTrackType = + | "SUBTITLES" + | "CAPTIONS" + | "DESCRIPTIONS" + | "CHAPTERS" + | "METADATA"; + + type TextTrackWindowType = "NONE" | "NORMAL" | "ROUNDED_CORNERS"; + + type TrackType = "TEXT" | "AUDIO" | "VIDEO"; + + type TextTrackFontGenericFamily = + | "SANS_SERIF" + | "MONOSPACED_SANS_SERIF" + | "SERIF" + | "MONOSPACED_SERIF" + | "CASUAL" + | "CURSIVE" + | "SMALL_CAPITALS"; + + type TextTrackFontStyle = "NORMAL" | "BOLD" | "BOLD_ITALIC" | "ITALIC"; + + type TextTrackEdgeType = + | "NONE" + | "OUTLINE" + | "DROP_SHADOW" + | "RAISED" + | "DEPRESSED"; + + type Command = + | "PAUSE" + | "SEEK" + | "STREAM_VOLUME" + | "STREAM_MUTE" + | "ALL_BASIC_MEDIA" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_SHUFFLE" + | "SKIP_AD"; + + type SeekResumeState = "PLAYBACK_START" | "PLAYBACK_PAUSE"; + + type StreamingProtocolType = + | "UNKNOWN" + | "MPEG_DASH" + | "HLS" + | "SMOOTH_STREAMING"; + + type StreamType = "BUFFERED" | "LIVE" | "NONE"; + + type FocusState = "IN_FOCUS" | "NOT_IN_FOCUS"; + + type ExtendedPlayerState = "LOADING"; + + type ErrorType = + | "INVALID_PLAYER_STATE" + | "LOAD_FAILED" + | "LOAD_CANCELLED" + | "INVALID_REQUEST" + | "ERROR"; + + type ErrorReason = + | "INVALID_COMMAND" + | "INVALID_PARAMS" + | "INVALID_MEDIA_SESSION_ID" + | "SKIP_LIMIT_REACHED" + | "NOT_SUPPORTED" + | "LANGUAGE_NOT_SUPPORTED" + | "END_OF_QUEUE" + | "APP_ERROR" + | "AUTHENTICATION_EXPIRED" + | "PREMIUM_ACCOUNT_REQUIRED" + | "CONCURRENT_STREAM_LIMIT" + | "PARENTAL_CONTROL_RESTRICTED" + | "NOT_AVAILABLE_IN_REGION" + | "CONTENT_ALREADY_PLAYING" + | "INVALID_REQUEST" + | "GENERIC_LOAD_ERROR"; + + type RepeatMode = + | "REPEAT_OFF" + | "REPEAT_ALL" + | "REPEAT_SINGLE" + | "REPEAT_ALL_AND_SHUFFLE"; + + type IdleReason = "CANCELLED" | "INTERRUPTED" | "FINISHED" | "ERROR"; + + type HlsSegmentFormat = "AAC" | "AC3" | "MP3" | "TS" | "TS_AAC"; + + type HdrType = "SDR" | "HDR" | "DV"; + + type PlayStringId = + | "FREE_TRIAL_ABOUT_TO_EXPIRE" + | "SUBSCRIPTION_ABOUT_TO_EXPIRE" + | "STREAM_HIJACKED"; + + type GetStatusOptions = "NO_METADATA" | "NO_QUEUE_ITEMS"; + + type MessageType = + | "MEDIA_STATUS" + | "CLOUD_STATUS" + | "QUEUE_CHANGE" + | "QUEUE_ITEMS" + | "QUEUE_ITEM_IDS" + | "GET_STATUS" + | "LOAD" + | "PAUSE" + | "STOP" + | "PLAY" + | "SKIP_AD" + | "PLAY_AGAIN" + | "SEEK" + | "SET_PLAYBACK_RATE" + | "SET_VOLUME" + | "EDIT_TRACKS_INFO" + | "EDIT_AUDIO_TRACKS" + | "PRECACHE" + | "PRELOAD" + | "QUEUE_LOAD" + | "QUEUE_INSERT" + | "QUEUE_UPDATE" + | "QUEUE_REMOVE" + | "QUEUE_REORDER" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_GET_ITEM_RANGE" + | "QUEUE_GET_ITEMS" + | "QUEUE_GET_ITEM_IDS" + | "QUEUE_SHUFFLE" + | "SET_CREDENTIALS" + | "LOAD_BY_ENTITY" + | "USER_ACTION" + | "DISPLAY_STATUS" + | "FOCUS_STATE" + | "CUSTOM_COMMAND"; + + type PlayerState = "IDLE" | "PLAYING" | "PAUSED" | "BUFFERING"; + + type QueueChangeType = + | "INSERT" + | "REMOVE" + | "ITEMS_CHANGE" + | "UPDATE" + | "NO_CHANGE"; + + type QueueType = + | "ALBUM" + | "PLAYLIST" + | "AUDIOBOOK" + | "RADIO_STATION" + | "PODCAST_SERIES" + | "TV_SERIES" + | "VIDEO_PLAYLIST" + | "LIVE_TV" + | "MOVIE"; + + type MetadataType = + | "GENERIC" + | "MOVIE" + | "TV_SHOW" + | "MUSIC_TRACK" + | "PHOTO"; + + /** + * RefreshCredentials request data. + */ + interface RefreshCredentialsRequestData { + [key: string]: any; + } + + /** + * Media event SET_VOLUME request data. + */ + interface VolumeRequestData extends RequestData { + /** + * The media stream volume + */ + volume?: Volume; + } + + /** + * Represents the volume of a media session stream. + */ + interface Volume { + /** + * Value from 0 to 1 that represents the current stream volume level. + */ + level?: number; + + /** + * Whether the stream is muted. + */ + muted?: boolean; + } + + /** + * Video information such as video resolution and High Dynamic Range (HDR). + */ + class VideoInformation { + constructor(width: number, height: number, hdrType: HdrType); + + width: number; + + height: number; + + hdrType: HdrType; + } + + /** + * VAST ad request configuration. + */ + interface VastAdsRequest { + /** + * Specifies a VAST document to be used as the ads response instead of making a + * request via an ad tag url. + * This can be useful for debugging and other situations where a VAST response is + * already available. + */ + adsResponse?: string; + + /** + * URL for VAST file. + */ + adTagUrl?: string; + } + + /** + * UserAction request data. + */ + interface UserActionRequestData { + /** + * Optional request source. + * It contain the assistent query that initiate the request. + */ + source?: string; + + /** + * User action to be handled by the application. + */ + userAction?: UserAction; + + /** + * Optional context information for the user action. + */ + userActionContext?: UserActionContext; + } + + /** + * A TV episode media description. + */ + interface TvShowMediaMetadata { + /** + * TV episode number. A positive integer. + */ + episode?: number; + + /** + * @deprecated use episode instead + */ + episodeNumber?: number; + + /** + * @deprecated use episode instead + */ + episodeTitle?: string; + + /** + * Content images. Examples would include cover art or a thumbnail of + * the currently playing media. + */ + images?: Image[]; + + /** + * ISO 8601 date when the episode originally aired; e.g. 2014-02-10. + */ + originalAirdate?: string; + + /** + * @deprecated use originalAirdate instead. + */ + releaseYear?: number; + + /** + * TV episode season. A positive integer. + */ + season?: number; + + /** + * @deprecated use season instead. + */ + seasonNumber?: number; + + /** + * TV series title. + */ + seriesTitle?: string; + + /** + * TV episode title. + */ + title?: string; + } + /** + * Describes track metadata information. + */ + class Track { + constructor(trackId: number, trackType: TrackType); + + /** + * Custom data set by the receiver application. + */ + customData?: string; + + /** + * Language tag as per RFC 5646 (If subtype is “SUBTITLES” it is mandatory). + */ + language?: string; + + /** + * A descriptive; human readable name for the track. For example "Spanish". + */ + name?: string; + + /** + * For text tracks; the type of text track. + */ + subtype?: string; + + /** + * It can be the url of the track or any other identifier that allows the receiver + * to find the content (when the track is not inband or included in the manifest). + * For example it can be the url of a vtt file. + */ + trackContentId?: string; + + /** + * It represents the MIME type of the track content. For example if the track + * is a vtt file it will be ‘text/vtt’. This field is needed for out of band tracks; + * so it is usually provided if a trackContentId has also been provided. + * It is not mandatory if the receiver has a way to identify the content from + * the trackContentId; but recommended. + * The track content type; if provided; must be consistent with the track type. + */ + trackContentType?: string; + + /** + * Unique identifier of the track within the context of a MediaInformation object. + */ + trackId?: number; + + /** + * The type of track. + */ + type: TrackType; + } + /** + * Describes style information for a text track. + */ + interface TextTrackStyle { + /** + * The background 32 bit RGBA color. The alpha channel should be used for transparent backgrounds. + */ + backgroundColor?: string; + + /** + * Custom data set by the receiver application. + */ + customData?: any; + + /** + * RGBA color for the edge; this value will be ignored if edgeType is NONE. + */ + edgeColor?: string; + + edgeType?: TextTrackEdgeType; + + /** + * If the font is not available in the receiver the fontGenericFamily will be used. + */ + fontFamily?: string; + + /** + * The text track generic family. + */ + fontGenericFamily?: TextTrackFontGenericFamily; + + /** + * The font scaling factor for the text track (the default is 1). + */ + fontScale?: number; + + /** + * The text track font style. + */ + fontStyle?: TextTrackFontStyle; + + /** + * The foreground 32 bit RGBA color. + */ + foregroundColor?: string; + + /** + * 32 bit RGBA color for the window. This value will be ignored if windowType is NONE. + */ + windowColor?: string; + + /** + * Rounded corner radius absolute value in pixels (px). This value will be ignored + * if windowType is not ROUNDED_CORNERS. + */ + windowRoundedCornerRadius?: number; + + /** + * The window concept is defined in CEA-608 and CEA-708. In WebVTT is called a region. + */ + windowType?: TextTrackWindowType; + } + + /** + * Media event playback rate request data. + */ + interface SetPlaybackRateRequestData extends RequestData { + /** + * New playback rate (>0). + */ + playbackRate?: number; + + /** + * New playback rate relative to current playback rate. + * New rate will be the result of multiplying the current rate with the value. + * For example a value of 1.1 will increase rate by 10%. + * (Only used if the playbackRate value is not provided). + */ + relativePlaybackRate?: number; + } + + /** + * SetCredentials request data. + */ + interface SetCredentialsRequestData { + /** + * Credentials to use by receiver. + */ + credentials?: string; + + /** + * If it is a response for refresh credentials; it will indicate the request id + * of the refresh credentials request. + */ + forRequestId?: number; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; + } + + /** + * Media event SEEK request data. + */ + interface SeekRequestData extends RequestData { + /** + * Seconds since beginning of content. + */ + currentTime?: number; + + /** + * Seconds relative to the current playback position. If this field is defined; + * the currentTime field will be ignored. + */ + relativeTime?: number; + + /** + * The playback state after a SEEK request. + */ + resumeState?: SeekResumeState; + } + + /** + * Provides seekable range in seconds. + */ + class SeekableRange { + constructor(start?: number, end?: number); + + /** + * End of the seekable range in seconds. + */ + end?: number; + + /** + * Start of the seekable range in seconds. + */ + start?: number; + } + + /** + * Media event request data. + */ + class RequestData { + constructor(type: MessageType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + } + + /** + * Media event UPDATE queue request data. + */ + interface QueueUpdateRequestData { + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; the currentItem will point to + * the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * List of queue items to be updated. No reordering will happen; the items will + * retain the existing order. + */ + items?: QueueItem[]; + + /** + * Skip/Go back number of items with respect to the position of currentItem + * (it can be negative). If it is out of boundaries; the currentItem will be the + * next logical item in the queue wrapping around the boundaries. + * The new currentItem position will follow the rules of the queue repeat behavior. + */ + jump?: number; + + /** + * Behavior of the queue when all items have been played. + */ + repeatMode?: RepeatMode; + + /** + * Shuffle the queue items when the update is processed. + * After the queue items are shuffled; the item at the currentItem position will + * be loaded. + */ + shuffle?: boolean; + } + + /** + * Media event queue REORDER request data. + */ + class QueueReorderRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion (if not provided; + * the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like + * the QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the reordered list. + * If the ID is not found or it is not provided; + * the reordered list will be appended at the end of the existing list. + */ + insertBefore?: number; + + /** + * IDs of the items to be reordered; in the new order. + * Items not provided will keep their existing order. + * The provided list will be inserted at the position determined by insertBefore. + * For example: + * If insertBefore is not specified Existing queue: “A”;”D”;”G”;”H”;”B”;”E” itemIds: + * “D”;”H”;”B” New Order: “A”;”G”;”E”;“D”;”H”;”B” + * If insertBefore is “A” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “D”;”H”;”B”;“A”;”G”;”E” + * If insertBefore is “G” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “A”;“D”;”H”;”B”;”G”;”E” + */ + itemIds: number[]; + } + + /** + * Media event queue REMOVE request data. + */ + class QueueRemoveRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * IDs of queue items to be deleted. + */ + itemIds?: number[]; + } + /** + * Media event queue LOAD request data. + */ + class QueueLoadRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * Seconds (since the beginning of content) to start playback of the first item to + * be played. If provided; this value will take precedence over the + * startTime value provided at the QueueItem level but only the first + * time the item is played. This is to cover the common case where the user + * casts the item that was playing locally so the currentTime does not apply + * to the item permanently like the QueueItem startTime does. + * It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * Behavior of the queue when all items have been played. + */ + items: QueueItem[]; + + /** + * Id of the request; used to correlate request/response. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the items array that must be the first currentItem + * (the item that will be played first). Note this is the index of the array + * (starts at 0) and not the itemId (as it is not known until the queue is created). + * If repeatMode is REPEAT_OFF playback will end when the last item in the array is + * played (elements before the startIndex will not be played). + * This may be useful for continuation scenarios where the user was already + * using the sender app and in the middle decides to cast. + * In this way the sender app does not need to map between the local and remote queue + * positions or saves one extra QUEUE_UPDATE request. + */ + startIndex?: number; + } + + /** + * Queue item information. Application developers may need to create a QueueItem to + * insert a queue element using InsertQueueItems. In this case they should not + * provide an itemId (as the actual itemId will be assigned when the item is inserted + * in the queue). This prevents ID collisions with items added from a sender app. + */ + class QueueItem { + constructor(opt_itemId?: number); + + /** + * Array of Track trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds?: number[]; + + /** + * If the autoplay parameter is not specified or is true; the media player + * will begin playing the element in the queue when the item becomes the currentItem. + */ + autoplay?: boolean; + + /** + * The application can define any extra queue item information needed. + */ + customData?: any; + + /** + * Unique identifier of the item in the queue. + * The attribute is optional because for LOAD or INSERT should not be provided + * (as it will be assigned by the receiver when an item is first created/inserted). + */ + itemId?: number; + + /** + * Metadata (including contentId) of the playlist element. + */ + media?: MediaInformation; + + /** + * Playback duration of the item; if it is larger than the actual duration - + * startTime it will be ignored (default behavior). + * It can be negative; in such case the duration will be the actual asset + * duration minus the duration provided. + * It can be used for photo slideshows to control the duration the item should + * be presented or for live events to control the duration that the program + * should be played. It may be useful for autoplay scenarios to avoid displaying all + * the credits after an episode has ended. + */ + playbackDuration?: number; + + /** + * This parameter is a hint for the receiver to preload this media + * item before it is played. It allows for a smooth transition between items + * played from the queue. The time is expressed in seconds; relative to + * the beginning of this item playback (usually the end of the previous item playback). + * Only positive values are valid. For example; if the value is 10 seconds; this item + * will be preloaded 10 seconds before the previous item has finished. + * The receiver will try to honor this value but will not guarantee it; + * for example if the value is larger than the previous item duration the + * receiver may just preload this item shortly after the previous item has started playing + * (there will never be two items being preloaded in parallel). + * Also; if an item is inserted in the queue just after the currentItem and the time to preload is higher than the + * time left on the currentItem; the preload will just happen as soon as possible. + */ + preloadTime?: number; + + /** + * Seconds since beginning of content. If the content is live content; + * and startTime is not specified; the stream will start at the live position. + */ + startTime?: number; + } + + /** + * Media event queue INSERT request data. + */ + class QueueInsertRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * ID of the current media Item after the insertion (if not provided; + * the currentItem value will be the same as before the insertion). + */ + currentItemId?: number; + + /** + * Index (relative to the items array; starting with 0) of the new current media Item. + * For inserted items we use the index (similar to startIndex in QUEUE_LOAD) and not + * currentItemId; because the itemId is unknown until the items are inserted. + * If not provided; the currentItem value will be the same as before the insertion + * (unless currentItemId is provided). This param allows to make atomic the common use + * case of insert and play an item. + */ + currentItemIndex?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the inserted list. + * If the ID is not found or it is not provided; the list will be appended at + * the end of the existing list. + */ + insertBefore?: number; + + /** + * List of queue items. The itemId field of the items should be empty. + * It is sorted (first element will be played first). + */ + items: QueueItem[]; + } + + /** + * Represents a data message containing the full list of queue ids. + */ + interface QueueIds { + /** + * List of queue item ids. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; + } + + /** + * Queue data as part of the LOAD request. + */ + class QueueData { + constructor( + id?: string, + name?: string, + description?: string, + repeatMode?: RepeatMode, + items?: QueueItem[], + startIndex?: number, + startTime?: number + ); + + /** + * Description of the queue. + */ + description?: string; + + /** + * Optional Queue entity id; provide Google Assistant deep link. + */ + entity?: string; + + /** + * Id of the queue. + */ + id?: string; + + /** + * Array of queue items. It is sorted (first element will be played first). + */ + items?: QueueItem[]; + + /** + * Name of the queue. + */ + name?: string; + + /** + * Queue type; e.g. album; playlist; radio station; tv series; etc. + */ + queueType?: QueueType; + + /** + * Continuous playback behavior of the queue. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the queue that should be used to start playback first. + */ + startIndex?: number; + + /** + * Seconds (since the beginning of content) to start playback of the first item. + */ + startTime?: number; + } + + /** + * Represents a queue change message; such as insert; remove; and update. + */ + interface QueueChange { + /** + * The actual queue change type. + */ + changeType?: QueueChangeType; + + /** + * The id to insert the list of itemIds before. + */ + insertBefore?: number; + + /** + * List of changed itemIds. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + /** + * The queue change sequence ID. Used to coordinate state sync between various + * senders and the receiver. + */ + sequenceNumber?: number; + + type: MessageType; + } + + /** + * Media event PRELOAD request data. + */ + class PreloadRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(itemId: number); + + /** + * The ID of the queue item. + */ + itemId: number; + } + + /** + * Media event PRECACHE request data. (Some fields of the load request; + * like autoplay and queueData; are ignored). + */ + class PrecacheRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; and + * currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; + * the media player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(data?: string); + + /** + * Application precache data. + */ + precacheData?: string; + } + + /** + * PlayString request data. + */ + class PlayStringRequestData { + constructor(stringId: PlayStringId, opt_arguments?: string[]); + + /** + * An optional array of string values to be filled into the text. + */ + arguments?: string[]; + + /** + * An identifier for the text to be played back. + */ + stringId: PlayStringId; + } + + /** + * A photo media description. + */ + interface PhotoMediaMetadata { + /** + * Name of the photographer. + */ + artist?: string; + + /** + * ISO 8601 date and time the photo was taken; e.g. 2014-02-10T15:47:00Z. + */ + creationDateTime?: string; + + /** + * Photo height; in pixels. + */ + height?: number; + + /** + * Images associated with the content. Examples would include a photo thumbnail. + */ + images: Image[]; + + /** + * Latitude. + */ + latitude?: number; + + /** + * Location where the photo was taken. For example; "Seattle; Washington; USA". + */ + location?: string; + + /** + * Longitude. + */ + longitude?: number; + + /** + * Photo title. + */ + title?: string; + + /** + * Photo width; in pixels. + */ + width?: number; + } + + /** + * A music track media description. + */ + interface MusicTrackMediaMetadata { + /** + * Album artist name. + */ + albumArtist?: string; + + /** + * Album name. + */ + albumName?: string; + + /** + * Track artist name. + */ + artist?: string; + + /** + * @deprecated: use @see{@link artist} instead + */ + artistName: string; + + /** + * Track composer name. + */ + composer?: string; + + /** + * Disc number. A positive integer. + */ + discNumber?: number; + + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the track was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: Use @see{@link releaseDate} instead + */ + releaseYear?: string; + + /** + * Track name. + */ + songName?: string; + + /** + * Track title. + */ + title?: string; + + /** + * Track number in album. A positive integer. + */ + trackNumber?: number; + } + + /** + * A movie media description. + */ + interface MovieMediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the movie was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Movie studio. + */ + studio?: string; + + /** + * Movie subtitle. + */ + subtitle?: string; + + /** + * Movie title. + */ + title?: string; + } + /** + * Represents the status of a media session. + */ + interface MediaStatus { + /** + * List of IDs corresponding to the active tracks. + */ + activeTrackIds: number[]; + + /** + * Status of break; if receiver is playing break. + * This field will be defined only when receiver is playing break. + */ + breakStatus: BreakStatus; + + /** + * ID of this media item (the item that originated the status change). + */ + currentItemId?: number; + + /** + * The current playback position. + */ + currentTime: number; + + /** + * Application-specific media status. + */ + customData?: any; + + /** + * Extended media status information. + */ + extendedStatus: ExtendedMediaStatus; + + /** + * If the state is IDLE; the reason the player went to IDLE state. + */ + idleReason: IdleReason; + + /** + * List of media queue items. + */ + items: QueueItem[]; + + /** + * Seekable range of a live or event stream. It uses relative media time in seconds. + * It will be undefined for VOD streams. + */ + liveSeekableRange: LiveSeekableRange; + + /** + * ID of the media Item currently loading. If there is no item being loaded; + * it will be undefined. + */ + loadingItemId?: number; + + /** + * The media information. + */ + media: MediaInformation; + + /** + * Unique id for the session. + */ + mediaSessionId: number; + + /** + * The playback rate. + */ + playbackRate: number; + + /** + * The playback state. + */ + playerState: PlayerState; + + /** + * ID of the next Item; only available if it has been preloaded. + * Media items can be preloaded and cached temporarily in memory; + * so when they are loaded later on; the process is faster + * (as the media does not have to be fetched from the network). + */ + preloadedItemId?: number; + + /** + * Queue data. + */ + queueData: QueueData; + + /** + * The behavior of the queue when all items have been played. + */ + repeatMode: RepeatMode; + + /** + * The commands supported by this player. + */ + supportedMediaCommands: number; + + type: MessageType; + + /** + * The video information. + */ + videoInfo: VideoInformation; + + /** + * The current stream volume. + */ + volume: Volume; + } + /** + * Common media metadata used as part of MediaInformation + */ + class MediaMetadata { + constructor(type: MetadataType); + + /** + * The type of metadata + */ + metadataType: MetadataType; + } + + /** + * Represents the media information. + */ + interface MediaInformation { + /** + * Partial list of break clips that includes current break clip that receiver + * is playing or ones that receiver will play shortly after; instead of sending + * whole list of clips. This is to avoid overflow of MediaStatus message. + */ + breakClips: BreakClip[]; + + /** + * List of breaks. + */ + breaks: Break[]; + + /** + * Typically the url of the media. + */ + contentId: string; + + /** + * The content MIME type. + */ + contentType: string; + + /** + * Optional media url; to allow using contentId for real id. If contentUrl + * is provided; it will be used as media url; otherwise the contentId will + * be used as the media url. + */ + contentUrl?: string; + + /** + * Application-specific media information. + */ + customData?: any; + + /** + * The media duration. + */ + duration?: number; + + /** + * Optional Media entity; provide Google Assistant deep link. + */ + entity?: string; + + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat: HlsSegmentFormat; + + /** + * The media metadata. + */ + metadata: MediaMetadata; + + /** + * The stream type. + */ + streamType: StreamType; + + /** + * The style of text track. + */ + textTrackStyle: TextTrackStyle; + + /** + * The media tracks. + */ + tracks: Track[]; + } + + /** + * Media event LOAD request data. + */ + interface LoadRequestData extends RequestData { + /** + * Array of trackIds that are active. If the array is not provided; the + * default tracks will be active. + */ + activeTrackIds: number[]; + + /** + * If the autoplay parameter is specified; the media player will begin + * playing the content when it is loaded. Even if autoplay is not + * specified;the media player implementation may choose to begin playback + * immediately. + */ + autoplay?: boolean; + + /** + * Optional user credentials. + */ + credentials?: string; + + /** + * Optional credentials type. The type 'cloud' is a reserved type used by + * load requests that were originated by voice assistant commands. + */ + credentialsType?: string; + + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + + /** + * The media playback rate. + */ + playbackRate?: number; + + /** + * Queue data. + */ + queueData: QueueData; + } + + /** + * LoadByEntity request data. + */ + interface LoadByEntityRequestData { + /** + * Content entity information; typically represented by a stringified JSON object + */ + entity: string; + + /** + * Shuffle the items to play. + */ + shuffle?: boolean; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; + } + + /** + * Provides live seekable range with start and end time in seconds and two more + * attributes. + */ + class LiveSeekableRange { + constructor( + start?: number, + end?: number, + isMovingWindow?: boolean, + isLiveDone?: boolean + ); + + /** + * A boolean value indicates whether a live stream is ended. If it is done; + * the end of live seekable range should stop updating. + */ + isLiveDone?: boolean; + + /** + * A boolean value indicates whether the live seekable range is a moving window. + * If false; it will be either a expanding range or a fixed range meaning live + * has ended. + */ + isMovingWindow?: boolean; + } + + /** + * Represents a data message containing item information for each requested ids. + */ + interface ItemsInfo { + /** + * List of changed itemIds. + */ + items: QueueItem[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; + } + + /** + * An image that describes a receiver application or media item. + * This could be an application icon; cover art; or a thumbnail. + */ + class Image { + constructor(url: string); + + /** + * The height of the image. + */ + height?: number; + + /** + * the URL to the image + */ + url: string; + + /** + * The width of the image + */ + width?: number; + } + /** Media event GET_STATUS request data. */ + interface GetStatusRequestData extends RequestData { + /** + * The options of a GET_STATUS request. + */ + options: GetStatusOptions; + } + + /** + * Get items info request data. + */ + class GetItemsInfoRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * List of item ids to be requested. + */ + itemIds: number[]; + } + /** + * A generic media description. + */ + interface GenericMediaMetadata extends MediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date and/or time when the content was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated - use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Content subtitle. + */ + subtitle?: string; + + /** + * Content title. + */ + title?: string; + } + + /** + * Focus state change message. + */ + interface FocusStateRequestData { + /** + * The focus state of the app. + */ + state: FocusState; + } + + /** Fetch items request data. */ + class FetchItemsRequestData extends RequestData { + constructor(itemId: number, nextCount: number, prevCount: number); + + /** + * ID of the reference media item for fetching more items. + */ + itemId: number; + + /** + * Number of items after the reference item to be fetched. + */ + nextCount: number; + + /** + * Number of items before the reference item to be fetched. + */ + prevCount: number; + } + + /** + * Extended media status information + */ + class ExtendedMediaStatus { + constructor( + playerState: MediaInformation, + opt_media?: MediaInformation + ); + + media: MediaInformation; + + playerState: ExtendedPlayerState; + } + + /** Event data for @see{@link EventType.ERROR} event. */ + class ErrorEvent extends Event { + constructor(detailedErrorCode?: DetailedErrorCode, error?: any); + + /** + * An error code representing the cause of the error. + */ + detailedErrorCode?: DetailedErrorCode; + + /** + * The error object. + * This could be an Error object (e.g.; if an Error was thrown in an event handler) + * or an object with error information (e.g.; if the receiver received an invalid + * command). + */ + error?: any; + } + + class ErrorData { + constructor(type: ErrorType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the request; used to correlate request/response. + */ + requestId?: number; + } + + /** Media event EDIT_TRACKS_INFO request data. */ + interface EditTracksInfoRequestData extends RequestData { + /** + * Array of the Track trackIds that should be active. + * If it is not provided; the active tracks will not change. + * If the array is empty; no track will be active. + */ + activeTrackIds?: number[]; + + /** + * Flag to enable or disable text tracks. + * If false it will disable all text tracks; + * if true it will enable the first text track; or the previous active text tracks. + * This flag is ignored if activeTrackIds or language is provided. + */ + enableTextTracks?: boolean; + + /** + * Indicates that the provided language was not explicit user request; but rather + * inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + /** + * Language for the tracks that should be active. The language field will take + * precedence over activeTrackIds if both are specified. + */ + language?: string; + + textTrackStyle?: TextTrackStyle; + } + + /** + * Media event EDIT_AUDIO_TRACKS request data. If language is not provided; + * the default audio track for the media will be enabled. + */ + interface EditAudioTracksRequestData extends RequestData { + /** + * Indicates that the provided language was not explicit user request; + * but rather inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + language?: string; + } + + /** DisplayStatus request data. */ + interface DisplayStatusRequestData { + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; + } + + /** CustomCommand request data. */ + interface CustomCommandRequestData { + /** + * Custom Data; typically represented by a stringified JSON object. + */ + data: string; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; + } + + class BreakStatus { + constructor(currentBreakTime: number, currentBreakClipTime: number); + + /** + * Id of current break clip. + */ + breakClipId: string; + + /** + * Id of current break. + */ + breakId: string; + + /** + * Time in sec elapsed after current break clip starts. + */ + currentBreakClipTime: number; + + /** + * Time in sec elapsed after current break starts. + */ + currentBreakTime: number; + + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable: number; + } + + /** + * Represents break clip (e.g. a clip of ad during ad break) + */ + class BreakClip { + constructor(id: string); + + /** + * Url of page that sender will display; when end user clicks link on sender UI; while receiver is playing this clip. + */ + clickThroughUrl?: string; + /** + * Typically the url of the break media (playing on the receiver). + */ + contentId?: string; + /** + * The content MIME type. + */ + contentType?: string; + /** + * Optional break media url; to allow using contentId for real id. + * If contentUrl is provided; it will be used as media url; + * otherwise the contentId will be used as the media url. + */ + contentUrl?: string; + /** + * Application-specific break clip data. + */ + customData?: any; + /** + * Duration of break clip in sec. + */ + duration?: number; + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat?: HlsSegmentFormat; + /** + * Unique id of break clip. + */ + id: string; + /** + * Url of content that sender will display while receiver is playing this clip. + */ + posterUrl?: string; + /** + * Title of break clip. Sender might display this on its screen; if provided. + */ + title?: string; + /** + * VAST ad request configuration. Used if contentId or contentUrl is not provided. + */ + vastAdsRequest?: VastAdsRequest; + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable?: number; + } + + /** Represents break (e.g. ad break) included in main video. */ + class Break { + constructor(id: string, breakClipIds: string[], position: number); + /** + * List of ids of break clip that this break includes. + */ + breakClipIds: string[]; + /** + * Duration of break in sec. + */ + duration?: number; + /** + * Unique id of break. + */ + id: string; + /** + * If true; indicates this is embedded break in main stream. + */ + + isEmbedded?: boolean; + /** + * Whether break is watched. + * Sender can change color of progress bar marker corresponding to this break once + * this field changes from false to true; + * denoting that the end-user already watched this break. + */ + isWatched: boolean; + + /** + * Where the break is located inside main video. -1 represents the end of main video. + */ + position: number; + } +} diff --git a/types/chromecast-caf-receiver/cast.framework.system.d.ts b/types/chromecast-caf-receiver/cast.framework.system.d.ts new file mode 100644 index 0000000000..d055e252fb --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.system.d.ts @@ -0,0 +1,198 @@ +import { EventType } from "./cast.framework.events"; +export = cast.framework.system; + +declare namespace cast.framework.system { + type EventType = + // Fired when the system is ready. + | "READY" + // Fired when the application is terminated + | "SHUTDOWN" + // Fired when a new sender has connected. + | "SENDER_CONNECTED" + // Fired when a sender has disconnected. + | "SENDER_DISCONNECTED" + // Fired when there is a system error. + | "ERROR" + // Fired when the system volume has changed. + | "SYSTEM_VOLUME_CHANGED" + // Fired when the visibility of the application has changed + // (for example after a HDMI Input change or when the TV is turned + // off/on and the cast device is externally powered). + // Note that this API has the same effect as the webkitvisibilitychange event raised + // by your document, we provided it as CastReceiverManager API for convenience and + // to avoid a dependency on a webkit-prefixed event. + | "VISIBILITY_CHANGED" + // Fired when the standby state of the TV has changed. + // This event is related to the visibility chnaged event, as if the TV is in standby + // the visibility will be false, the visibility is more granular + // (as it also detects that the TV has selected a different channel) + // but it is not reliably detected in all TVs, + // standby can be used in those cases as most TVs implement it. + | "STANDBY_CHANGED" + | "MAX_VIDEO_RESOLUTION_CHANGED" + | "FEEDBACK_STARTED"; + + type SystemState = + | "NOT_STARTED" + | "STARTING_IN_BACKGROUND" + | "STARTING" + | "READY" + | "STOPPING_IN_BACKGROUND" + | "STOPPING"; + + type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN"; + + type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN"; + + /** + * Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off). + */ + class VisibilityChangedEvent { + constructor(isVisible: boolean); + + /** + * Whether the Cast device is the active input or not. + */ + isVisible: boolean; + } + + /** + * Represents the system volume data. + */ + interface SystemVolumeData { + /** + * The level (from 0.0 to 1.0) of the system volume + */ + level: number; + + /** + * Whether the system volume is muted or not. + */ + muted: boolean; + } + /** + * Event dispatched by @see{CastReceiverManager} when the system volume changes. + */ + class SystemVolumeChangedEvent extends Event { + constructor(volume: SystemVolumeData); + + /** + * The system volume data + */ + data: SystemVolumeData; + } + /** + * Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state. + */ + class StandbyChangedEvent { + constructor(isStandby: boolean); + + isStandby: boolean; + } + /** + * Whether the TV is in standby or not. + */ + interface ShutdownEvent extends Event { + [key: string]: any; + } + + /** + * Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected. + */ + class SenderDisconnectedEvent extends Event { + constructor(senderId: string, userAgent: string); + /** + * The ID of the sender connected. + */ + senderId: string; + + /** + * The user agent of the sender. + */ + userAgent: string; + + /** + * The reason the sender was disconnected. + */ + reason?: DisconnectReason; + } + + /** + * Event dispatched by @see{@link CastReceiverManager} when a sender is connected. + */ + class SenderConnectedEvent extends Event { + constructor(senderId: string, userAgent: string); + /** + * The ID of the sender connected. + */ + senderId: string; + + /** + * The user agent of the sender. + */ + userAgent: string; + } + + /** + * Represents the data of a connected sender device. + */ + interface Sender { + /** + * The sender Id. + */ + id: string; + + /** + * Indicate the sender supports large messages (>64KB) + */ + largeMessageSupported?: boolean; + + /** + * The userAgent of the sender. + */ + userAgent?: string; + } + + /** + * Event dispatched by CastReceiverManager when the system is ready. + */ + class ReadyEvent { + constructor(applicationData: ApplicationData); + + /** + * The application data + */ + data: ApplicationData; + } + + /** + * Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution. + */ + class MaxVideoResolutionChangedEvent extends Event { + constructor(height: number); + + /** + * Maximum video resolution requested by the system. The value of 0 means there is no restriction. + */ + height: number; + } + /** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */ + interface FeedbackStartedEvent extends Event { + [key: string]: any; + } + /** Event dispatched by @see{@link CastReceiverContext} which contains system information. */ + class Event { + constructor(type: EventType, data?: any); + type: EventType; + data?: any; + } + + /** Represents the data of the launched application. */ + interface ApplicationData { + id(): string; + launchingSenderId(): string; + name(): string; + namespaces(): string[]; + sessionId(): number; + } +} diff --git a/types/chromecast-caf-receiver/cast.framework.ui.d.ts b/types/chromecast-caf-receiver/cast.framework.ui.d.ts new file mode 100644 index 0000000000..77d93c8082 --- /dev/null +++ b/types/chromecast-caf-receiver/cast.framework.ui.d.ts @@ -0,0 +1,197 @@ +import { PlayerDataEventType } from "./cast.framework.ui"; +import { MediaMetadata } from "./cast.framework.messages"; +import { PlayerDataChangedEventHandler } from "./index"; + +export = cast.framework.ui; + +declare namespace cast.framework.ui { + type ContentType = "video" | "audio" | "image"; + + type State = + | "launching" + | "idle" + | "loading" + | "buffering" + | "paused" + | "playing"; + + type PlayerDataEventType = + | "ANY_CHANGE" + | "STATE_CHANGED" + | "IS_SEEKING_CHANGED" + | "DURATION_CHANGED" + | "CURRENT_TIME_CHANGED" + | "METADATA_CHANGED" + | "TITLE_CHANGED" + | "SUBTITLE_CHANGED" + | "THUMBNAIL_URL_CHANGED" + | "NEXT_TITLE_CHANGED" + | "NEXT_SUBTITLE_CHANGED" + | "NEXT_THUMBNAIL_URL_CHANGED" + | "PRELOADING_NEXT_CHANGED" + | "CONTENT_TYPE_CHANGED" + | "IS_LIVE_CHANGED" + | "BREAK_PERCENTAGE_POSITIONS_CHANGED" + | "IS_PLAYING_BREAK_CHANGED" + | "IS_BREAK_SKIPPABLE_CHANGED" + | "WHEN_SKIPPABLE_CHANGED" + | "NUMBER_BREAK_CLIPS_CHANGED" + | "CURRENT_BREAK_CLIP_NUMBER_CHANGED" + | "DISPLAY_STATUS_CHANGED"; + + /** + * Player data changed event. Provides the changed field (type); and new value. + */ + class PlayerDataChangedEvent { + constructor(type: PlayerDataEventType, field: string, value: any); + + /** + * The field name that was changed. + */ + field: string; + + type: PlayerDataEventType; + + /** + * The new field value. + */ + value: any; + } + /** + * Player data binder. Bind a player data object to the player state. + * The player data will be updated to reflect correctly the current player state without firing any change event. + */ + class PlayerDataBinder { + constructor(playerData: PlayerData); + + /** + * Add listener to player data changes. + */ + addEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; + + /** + * Remove listener to player data changes. + */ + removeEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; + } + /** + * Player data. Provide the player media and break state. + */ + interface PlayerData { + /** + * Array of breaks positions in percentage. + */ + breakPercentagePositions: number[]; + + /** + * Content Type. + */ + contentType: ContentType; + + /** + * The number of the current playing break clip in the break. + */ + currentBreakClipNumber: number; + + /** + * Media current position in seconds; or break current position if playing break. + */ + currentTime: number; + + /** + * Whether the player metadata (ie: title; currentTime) should be displayed. + * This will be true if at least one field in the metadata should be displayed. + * In some cases; displayStatus will be true; but parts of the metadata should be hidden + * (ie: the media title while media is seeking). + * In these cases; additional css can be applied to hide those elements. + * For cases where the media is audio-only; this will almost always be true. + * In cases where the media is video; this will be true when: + * (1) the video is loading; buffering; or seeking + * (2) a play request was made in the last five seconds while media is already playing; + * (3) there is a request made to show the status in the last five seconds; or + * (4) the media was paused in the last five seconds. + */ + displayStatus: boolean; + + /** + * Media duration in seconds; Or break duration if playing break. + */ + duration: number; + + /** + * Indicate break clip can be skipped. + */ + isBreakSkippable: boolean; + + /** + * Indicate if the content is a live stream. + */ + isLive: boolean; + + /** + * Indicate that the receiver is playing a break. + */ + isPlayingBreak: boolean; + + /** + * Indicate the player is seeking (can be either during playing or pausing). + */ + isSeeking: boolean; + + /** + * Media metadata. + */ + metadata: MediaMetadata; + + /** + * Next Item subtitle. + */ + nextSubtitle: string; + + /** + * Next Item thumbnail url. + */ + nextThumbnailUrl: string; + + /** + * Next Item title. + */ + nextTitle: string; + + /** + * Number of break clips in current break. + */ + numberBreakClips: number; + + /** + * Flag to show/hide next item metadata. + */ + preloadingNext: boolean; + + /** + * Current player state. + */ + state: State; + + /** + * Content thumbnail url. + */ + thumbnailUrl: string; + + /** + * Content title. + */ + title: string; + + /** + * Provide the time a break is skipable - relative to current playback time. Undefined if not skippable. + */ + whenSkippable?: number; + } +} diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts new file mode 100644 index 0000000000..08ce57cf86 --- /dev/null +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -0,0 +1,111 @@ +import { + PlayerData, + PlayerDataBinder +} from "chromecast-caf-receiver/cast.framework.ui"; +import { + ReadyEvent, + ApplicationData +} from "chromecast-caf-receiver/cast.framework.system"; +import { + RequestEvent, + Event, + BreaksEvent +} from "chromecast-caf-receiver/cast.framework.events"; +import { + QueueBase, + TextTracksManager, + QueueManager, + PlayerManager +} from "chromecast-caf-receiver/cast.framework"; +import { + BreakSeekData, + BreakClipLoadInterceptorContext, + BreakManager +} from "chromecast-caf-receiver/cast.framework.breaks"; +import { + Break, + BreakClip, + LoadRequestData, + Track, + MediaMetadata +} from "chromecast-caf-receiver/cast.framework.messages"; + +const breaksEvent = new BreaksEvent('BREAK_STARTED'); +breaksEvent.breakId = 'some-break-id'; +breaksEvent.breakClipId = 'some-break-clip-id'; + +const track = new Track(1, "TEXT"); +const breakClip = new BreakClip("id"); +const adBreak = new Break("id", ["id"], 1); +const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); +const pManager = new PlayerManager(); +pManager.addEventListener("STALLED", () => { }); +const ttManager = new TextTracksManager(); +const qManager = new QueueManager(); +const qBase = new QueueBase(); +const items = qBase.fetchItems(1, 3, 4); +const breakSeekData = new BreakSeekData(0, 100, []); +const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak); +const breakManager: BreakManager = { + getBreakById: () => adBreak, + getBreakClipById: () => breakClip, + getBreakClips: () => [breakClip], + getBreaks: () => [adBreak], + getPlayWatchedBreak: () => true, + setBreakClipLoadInterceptor: () => { }, + setBreakSeekInterceptor: () => { }, + setPlayWatchedBreak: () => { }, + setVastTrackingInterceptor: () => { } +}; + +const lrd: LoadRequestData = { + requestId: 1, + activeTrackIds: [1, 2], + media: { + tracks: [], + textTrackStyle: {}, + streamType: "BUFFERED", + metadata: { metadataType: "GENERIC" }, + hlsSegmentFormat: "AAC", + contentId: "id", + contentType: "type", + breakClips: [breakClip], + breaks: [adBreak] + }, + queueData: {} +}; + +const appData: ApplicationData = { + id: () => "id", + launchingSenderId: () => "launch-id", + name: () => "name", + namespaces: () => ["namespace"], + sessionId: () => 1 +}; + +const readyEvent = new ReadyEvent(appData); +const data = readyEvent.data; +const pData: PlayerData = { + breakPercentagePositions: [1], + contentType: "video", + currentBreakClipNumber: 2, + currentTime: 1234, + displayStatus: true, + duration: 222, + isBreakSkippable: false, + isLive: true, + isPlayingBreak: false, + isSeeking: true, + metadata: new MediaMetadata("GENERIC"), + nextSubtitle: "sub", + nextThumbnailUrl: "url", + nextTitle: "title", + numberBreakClips: 3, + preloadingNext: false, + state: "paused", + thumbnailUrl: "url", + title: "title", + whenSkippable: 321 +}; +const binder = new PlayerDataBinder(pData); +binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/chromecast-caf-receiver/index.d.ts b/types/chromecast-caf-receiver/index.d.ts new file mode 100644 index 0000000000..73a13f53ca --- /dev/null +++ b/types/chromecast-caf-receiver/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for chromecast-caf-receiver 3.x +// Project: https://github.com/googlecast +// Definitions by: Craig Bruce +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +/// +/// +/// +/// +/// + +import { PlayerDataChangedEvent } from './cast.framework.ui'; +import { NetworkRequestInfo } from './cast.framework'; +import { Event } from './cast.framework.events'; + +export as namespace cast; +export type EventHandler = (event: Event) => void; +export type PlayerDataChangedEventHandler = ( + event: PlayerDataChangedEvent +) => void; +export type RequestHandler = (request: NetworkRequestInfo) => void; +export type BinaryHandler = (data: Uint8Array) => Uint8Array; diff --git a/types/chromecast-caf-receiver/tsconfig.json b/types/chromecast-caf-receiver/tsconfig.json new file mode 100644 index 0000000000..452dd41e91 --- /dev/null +++ b/types/chromecast-caf-receiver/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": false, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "chromecast-caf-receiver-tests.ts", + "cast.framework.d.ts", + "cast.framework.breaks.d.ts", + "cast.framework.events.d.ts", + "cast.framework.messages.d.ts", + "cast.framework.system.d.ts", + "cast.framework.ui.d.ts" + ] +} diff --git a/types/chromecast-caf-receiver/tslint.json b/types/chromecast-caf-receiver/tslint.json new file mode 100644 index 0000000000..495d29983d --- /dev/null +++ b/types/chromecast-caf-receiver/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} diff --git a/types/config-yaml/config-yaml-tests.ts b/types/config-yaml/config-yaml-tests.ts new file mode 100644 index 0000000000..4ddf61e69f --- /dev/null +++ b/types/config-yaml/config-yaml-tests.ts @@ -0,0 +1,5 @@ +import yaml = require('config-yaml'); + +yaml('./simple.yaml'); +yaml('./simple.yaml', { encoding: 'gbk' }); +yaml('./simple.yaml', { encoding: 'utf-8' }); diff --git a/types/config-yaml/index.d.ts b/types/config-yaml/index.d.ts new file mode 100644 index 0000000000..6f2be7957b --- /dev/null +++ b/types/config-yaml/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for config-yaml 1.1 +// Project: https://github.com/neolao/config-yaml#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +/// +import * as fs from 'fs'; + +export = Yaml; + +declare namespace Yaml { + interface Options { + encoding: string; + } +} + +declare function Yaml(path: fs.PathLike, options?: Partial): any; diff --git a/types/config-yaml/tsconfig.json b/types/config-yaml/tsconfig.json new file mode 100644 index 0000000000..fa349a2f41 --- /dev/null +++ b/types/config-yaml/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "config-yaml-tests.ts" + ] +} diff --git a/types/config-yaml/tslint.json b/types/config-yaml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/config-yaml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cosmiconfig/cosmiconfig-tests.ts b/types/cosmiconfig/cosmiconfig-tests.ts index 508ad00aa0..f25337f3d3 100644 --- a/types/cosmiconfig/cosmiconfig-tests.ts +++ b/types/cosmiconfig/cosmiconfig-tests.ts @@ -1,4 +1,5 @@ -import cosmiconfig, { CosmiconfigResult } from "cosmiconfig"; +import cosmiconfig = require("cosmiconfig"); +import { CosmiconfigResult } from "cosmiconfig"; import * as path from "path"; const explorer = cosmiconfig("yourModuleName", { @@ -22,6 +23,13 @@ Promise.all([ explorer.loadSync(path.join(__dirname, "sample-config.json")), ]).then(result => result); +const result = explorer.searchSync(); +if (result) { + const config = result.config; + const filepath = result.filepath; + const isEmpty = result.isEmpty; +} + explorer.clearLoadCache(); explorer.clearSearchCache(); explorer.clearCaches(); diff --git a/types/cosmiconfig/index.d.ts b/types/cosmiconfig/index.d.ts index eb876b6ef2..94e28e9dab 100644 --- a/types/cosmiconfig/index.d.ts +++ b/types/cosmiconfig/index.d.ts @@ -3,57 +3,62 @@ // Definitions by: ozum // szeck87 // saadq +// jinwoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// -export interface Config { - [key: string]: any; +declare function cosmiconfig(moduleName: string, options?: cosmiconfig.ExplorerOptions): cosmiconfig.Explorer; + +declare namespace cosmiconfig { + interface Config { + [key: string]: any; + } + + type CosmiconfigResult = { + config: Config; + filepath: string; + isEmpty?: boolean; + } | null; + + interface LoaderResult { + config: Config | null; + filepath: string; + } + + type SyncLoader = (filepath: string, content: string) => Config | null; + type AsyncLoader = (filepath: string, content: string) => Config | null | Promise; + + interface LoaderEntry { + sync?: SyncLoader; + async?: AsyncLoader; + } + + interface Loaders { + [key: string]: LoaderEntry; + } + + interface Explorer { + search(searchFrom?: string): Promise; + searchSync(searchFrom?: string): null | CosmiconfigResult; + load(loadPath: string): Promise; + loadSync(loadPath: string): CosmiconfigResult; + clearLoadCache(): void; + clearSearchCache(): void; + clearCaches(): void; + } + + // These are the user options with defaults applied. + interface ExplorerOptions { + stopDir?: string; + cache?: boolean; + transform?: (result: CosmiconfigResult) => Promise | CosmiconfigResult; + packageProp?: string; + loaders?: Loaders; + searchPlaces?: string[]; + ignoreEmptySearchPlaces?: boolean; + } } -export type CosmiconfigResult = { - config: Config; - filePath: string; - isEmpty?: boolean; -} | null; - -export interface LoaderResult { - config: Config | null; - filepath: string; -} - -export type SyncLoader = (filepath: string, content: string) => Config | null; -export type AsyncLoader = (filepath: string, content: string) => Config | null | Promise; - -export interface LoaderEntry { - sync?: SyncLoader; - async?: AsyncLoader; -} - -export interface Loaders { - [key: string]: LoaderEntry; -} - -export interface Explorer { - search(searchFrom?: string): Promise; - searchSync(searchFrom?: string): null | CosmiconfigResult; - load(loadPath: string): Promise; - loadSync(loadPath: string): CosmiconfigResult; - clearLoadCache(): void; - clearSearchCache(): void; - clearCaches(): void; -} - -// These are the user options with defaults applied. -export interface ExplorerOptions { - stopDir?: string; - cache?: boolean; - transform?: (result: CosmiconfigResult) => Promise | CosmiconfigResult; - packageProp?: string; - loaders?: Loaders; - searchPlaces?: string[]; - ignoreEmptySearchPlaces?: boolean; -} - -export default function cosmiconfig(moduleName: string, options?: ExplorerOptions): Explorer; +export = cosmiconfig; diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 25d6151259..39be1cd0e7 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -1,6 +1,26 @@ 'use strict'; -import cytoscape = require('cytoscape'); +// TODO: document all aliases as aliases, not as duplicates! + +const assert = (tag: boolean) => { if (!tag) throw new Error(); }; +const aliases = (...obj: Array<{}>) => { if (obj.slice(1).some((alias) => alias !== obj[0])) throw new Error(); }; +const events = (obj: any) => { + aliases(obj.on, obj.bind, obj.listen, obj.addListener); + aliases(obj.promiseOn, obj.pon); + aliases(obj.off, obj.unbind, obj.unlisten, obj.removeListener); + aliases(obj.emit, obj.trigger); +}; + +// definitions +function oneOf(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E; +function oneOf(a: A, b: B, c: C, d: D): A | B | C | D; +function oneOf(a: A, b: B, c: C): A | B | C; +function oneOf(a: A, b: B): A | B; +function oneOf(...array: T[]): T { + return array[0]; +} + +import cytoscape = require('cytoscape'); const parentCSS = { 'padding-top': '10px', 'padding-left': '10px', @@ -69,6 +89,34 @@ const cy = cytoscape({ ] }, + // initial viewport state: + zoom: 1, + pan: { x: 0, y: 0 }, + + // interaction options: + minZoom: 1e-50, + maxZoom: 1e50, + zoomingEnabled: true, + userZoomingEnabled: true, + panningEnabled: true, + userPanningEnabled: true, + selectionType: 'single', + touchTapThreshold: 8, + desktopTapThreshold: 4, + autolock: false, + autoungrabify: false, + + // rendering options: + headless: false, + styleEnabled: true, + hideEdgesOnViewport: false, + hideLabelsOnViewport: false, + textureOnViewport: false, + motionBlur: false, + motionBlurOpacity: 0.2, + wheelSensitivity: 1, + pixelRatio: 'auto', + layout: { name: 'preset', padding: 5 @@ -80,6 +128,42 @@ cy.on('zoom', (event) => { cy.nodes('$node > node').style('opacity', 0); } }); +cy.off('zoom'); +events(cy); + +cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); +cy.add([ + { data: { id: 'h' }, position: {x: 250, y: 100} } +]); +const nodesBeforeDelete = cy.nodes(); +const edgesBeforeDelete = cy.edges(); + +const removed = cy.remove('#g #h'); +cy.add(removed); +const diffNodes = nodesBeforeDelete.diff(cy.nodes()); +const diffEdges = edgesBeforeDelete.diff(cy.edges()); +assert(diffNodes.left.size() === 0 && diffNodes.right.size() === 0 && diffNodes.both.size() === cy.nodes().size()); +assert(nodesBeforeDelete.same(cy.nodes())); +assert(edgesBeforeDelete.same(cy.edges())); + +const gh = cy.collection().add(cy.$id('g')).union(cy.getElementById('h')); +const gh2 = cy.$('#g #h'); +const gh3 = cy.nodes('#g #h'); +assert(gh2.same(gh)); +assert(gh3.same(gh)); +assert(gh.same(removed)); + +assert(cy.container() === null); // headless mode! + +cy.center(); +cy.center(gh); +aliases(cy.center, cy.centre); + +cy.fit(cy.$('#a #b #h')); + +const {x1, y1, x2, y2, w, h} = cy.extent(); + +aliases(cy.resize, cy.invalidateDimensions); cy.animate({ fit: { @@ -89,8 +173,323 @@ cy.animate({ duration: 500 }); -const node = cy.nodes()[0]; cy.animate({ - center: {eles: node}, + center: {eles: cy.nodes()[0]}, duration: 500 }); + +const anim = cy.animation({ + zoom: { + level: 1, + position: {x: 0, y: 0} + }, + pan: {x: 100, y: 100}, + duration: 100, + easing: 'ease' +}); +cy.stop(true, true); +anim.play(); +assert(anim.playing()); +anim.progress(anim.progress() + 50); +anim.time(anim.time() - 50); +anim.stop(); + +aliases(cy.layout, cy.createLayout, cy.makeLayout); + +// Preconfigured data for layouts (as it could be passed) +const boundingBox = oneOf({x1: 0, x2: 100, y1: 0, y2: 100}, {x1: 0, w: 100, y1: 0, h: 100}); +const positions = oneOf({a: {x: 100, y: 100}}, (node: cytoscape.NodeCollection): cytoscape.Position => ({x: 100, y: 100})); + +// TODO: uncomment after we have the way to add layout options properties from extensions +// const layouts = [ +// cy.layout({ +// name: 'null', +// ready: () => {}, +// stop: () => {} +// }), +// cy.layout({ +// name: 'random', +// fit: true, +// padding: 30, +// boundingBox, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'preset', +// positions, +// zoom: 1, +// pan: {x: 100, y: 100}, +// fit: false, +// padding: 30, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'grid', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// avoidOverlapPadding: 10, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// condense: false, +// rows: oneOf(10, undefined), +// cols: oneOf(10, undefined), +// position: (node) => ({ row: 1, col: 1 }), +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'circle', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// radius: oneOf(1, undefined), +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'concentric', +// fit: true, +// padding: 30, +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// equidistant: false, +// minNodeSpacing: 10, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// height: oneOf(500, undefined), +// width: oneOf(500, undefined), +// spacingFactor: oneOf(1, undefined), +// concentric: (node) => 1, +// levelWidth: (nodes) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'breadthfirst', +// fit: true, +// directed: false, +// padding: 30, +// circle: false, +// spacingFactor: 1.75, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// maximalAdjustments: 0, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'cose', +// ready: () => {}, +// stop: () => {}, +// animate: oneOf(true, false, 'end'), +// animationEasing: oneOf('ease-in-quad', undefined), +// animationDuration: oneOf(500, undefined), +// animateFilter: function ( node, i ){ return true; }, +// animationThreshold: 250, +// refresh: 20, +// fit: true, +// padding: 30, +// boundingBox: undefined, +// nodeDimensionsIncludeLabels: false, +// randomize: false, +// componentSpacing: 40, +// nodeRepulsion: (node) => 2048, +// nodeOverlap: 4, +// idealEdgeLength: (edge) => 32, +// edgeElasticity: (edge) => 32, +// nestingFactor: 1.2, +// gravity: 1, +// numIter: 1000, +// initialTemp: 1000, +// coolingFactor: 0.99, +// minTemp: 1.0, +// weaver: false +// }) +// ]; +// const lay = layouts[0]; +// aliases(lay.run, lay.start); +// events(lay); +// layouts.map(layout => { +// layout.run(); +// layout.stop(); +// }); + +// TODO: cy.style + +cy.png({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100 +}); +aliases(cy.jpg, cy.jpeg); +cy.jpg({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100, + quality: 0.5 +}); +cy.json(cy.json()); + +// Types possible to call methods +const ele = oneOf(cy.nodes()[0], cy.edges()[0]); +const eles = cy.elements(); +const node = cy.nodes()[0]; +const nodes = cy.nodes(); +const edge = cy.edges()[0]; +const edges = cy.edges(); + +assert(ele.cy() === cy); +eles.remove(); +assert(eles.removed()); +assert(!eles.inside()); +eles.restore(); + +([ele, eles, node, nodes, edge, edges] as cytoscape.CollectionReturnValue[]).forEach((elem) => { + aliases(elem.clone, elem.copy); + events(elem); + aliases(elem.data, elem.attr); + aliases(elem.removeData, elem.removeAttr); +}); +// TODO: tests for data flow + +const loops = oneOf(true, false); +node.degree(loops); node.indegree(loops); node.outdegree(loops); +nodes.totalDegree(loops); nodes.minDegree(loops); nodes.maxDegree(loops); +nodes.minIndegree(loops); nodes.maxIndegree(loops); nodes.minOutdegree(loops); nodes.maxOutdegree(loops); + +// tslint:disable-next-line:ban-types +const getsetPos = (func: T): T => { + func('x', func('x')); + func(func()); + func({x: 100, y: 100}); + return func; +}; + +aliases(node.modelPosition, node.point, node.position); +getsetPos(node.position); + +nodes.shift('x', 100); +nodes.shift({x: -100, y: 0}); + +aliases(nodes.modelPositions, nodes.positions, nodes.points); +nodes.positions((node, i) => Object.assign(node.position(), {x: node.position('x') + i})); + +aliases(node.renderedPosition, node.renderedPoint); +getsetPos(node.renderedPoint); + +// TODO: tests for compound nodes (relativePosition, in particular) + +const sizes: number[] = [ + ele.width(), ele.outerWidth(), ele.renderedWidth(), ele.renderedOuterWidth(), + ele.height(), ele.outerHeight(), ele.renderedHeight(), ele.renderedOuterHeight() +]; + +aliases(eles.boundingBox, eles.boundingbox); +aliases(eles.renderedBoundingBox, eles.renderedBoundingbox); + +const flags: boolean[] = [ + node.grabbed(), node.grabbable(), node.locked(), ele.active(), +]; + +const edgePoints: cytoscape.Position[] = [ + ...edge.controlPoints(), ...edge.segmentPoints(), edge.sourceEndpoint(), edge.targetEndpoint(), edge.midpoint() +]; + +aliases(eles.layout, eles.createLayout, eles.makeLayout); +const layout = eles.layout({name: 'random'}).run(); + +eles.select(); +assert(ele.selected()); // as we selected all, and this too +aliases(eles.unselect, eles.deselect); +eles.selectify(); +assert(ele.selectable()); +eles.unselectify(); + +eles.addClass('test'); +eles.toggleClass('test', oneOf(true, false, undefined)); +eles.removeClass('test'); +eles.classes(oneOf('test', undefined)); +eles.flashClass('test flash', oneOf(1000, undefined)); +assert(ele.hasClass('test')); + +eles.style('background-color', 'green'); +Object.keys(eles.style()).map(key => eles.style(key)); +eles.style(eles.style()); +aliases(eles.style, eles.css); +aliases(ele.renderedCss, ele.renderedStyle); + +eles.anySame(nodes); +aliases(eles.contains, eles.has); +aliases(eles.allAreNeighbors, eles.allAreNeighbours); +eles.is('#g'); +eles.allAre('#g'); +eles.some((el, i, els) => true); +eles.every((el, i, els) => true); + +aliases(eles.forEach, eles.each); +const selected: cytoscape.SingularElementArgument[] = [eles.eq(0), eles.first(), eles.last()]; +const collSel = cy.collection(selected); +const selectedNodes: cytoscape.NodeSingular[] = [nodes.eq(0), nodes.first(), nodes.last()]; +const collNodes = cy.collection(selectedNodes); +const selectedEdges: cytoscape.EdgeSingular[] = [edges.eq(0), edges.first(), edges.last()]; +eles.slice(0, -1); +eles.toArray(); + +aliases(eles.getElementById, eles.$id); +aliases(eles.union, eles.add, eles.or, eles.u, eles['+'], eles['|']); +aliases(eles.difference, eles.not, eles.subtract, eles.relativeComplement, eles['\\'], eles['!'], eles['-']); +aliases(eles.absoluteComplement, eles.abscomp, eles.complement); +aliases(eles.intersection, eles.intersect, eles.and, eles.n, eles['&'], eles['.']); +aliases(eles.symmetricDifference, eles.symdiff, eles.xor, eles['^'], eles['(+)'], eles['(-)']); +cy.collection([nodes[0]]).union(nodes[1]).union(eles.$id('g')); +eles.difference(collNodes).abscomp().intersection(collSel).symdiff(collNodes); +const diff = collSel.diff(collNodes); +cy.collection().merge(diff.left).merge(diff.right).merge(diff.both).unmerge(collSel).filter((ele, i, eles) => true); + +eles.sort((a, b) => 1).map((ele, i, eles) => [i, ele]); +eles.reduce((prev, ele, i, eles) => [...prev, [ele, i]], []).concat(['finish']); +const min = eles.min((ele, i, eles) => ele.id.length + i); min.ele.scratch('min', min.value); +const max = eles.max((ele, i, eles) => ele.id.length + i); max.ele.scratch('max', max.value); + +// TODO: traversing (need to actively check the nodes/edeges distinction) +// TODO: algorithms +// TODO: compound nodes (there aren't any in current test case) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index e85041861a..a3226defd2 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.1 +// Type definitions for Cytoscape.js 3.2 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -9,7 +9,7 @@ // // Translation from Objects in help to Typescript interface. // http://js.cytoscape.org/#notation/functions -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /** * cy --> Cy.Core @@ -361,7 +361,7 @@ declare namespace cytoscape { * * The default value is 1. */ - pixelRatio?: number; + pixelRatio?: number | 'auto'; } /** @@ -386,35 +386,42 @@ declare namespace cytoscape { /** * Add elements to the graph and return them. */ - add(eles: ElementDefinition | ElementDefinition[] | Collection): CollectionElements; + add(eles: ElementDefinition | ElementDefinition[] | CollectionArgument): CollectionReturnValue; /** * Remove elements in collecion or match the selector from the graph and return them. */ - remove(eles: Collection | Selector): CollectionElements; + remove(eles: CollectionArgument | Selector): CollectionReturnValue; /** * Get a collection from elements in the graph matching the specified selector or from an array of elements. * If no parameter specified, an empty collection will be returned */ - collection(eles?: Selector | CollectionElements[]): CollectionElements; + collection(eles?: Selector | CollectionArgument[]): CollectionReturnValue; /** * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById */ - getElementById(id: string): CollectionElements; + getElementById(id: string): CollectionReturnValue; + + /** + * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById + */ + $id(id: string): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - $(selector: Selector): CollectionElements; + $(selector: Selector): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - elements(selector?: Selector): CollectionElements; + elements(selector?: Selector): CollectionReturnValue; /** * Get nodes in the graph matching the specified selector. @@ -428,7 +435,7 @@ declare namespace cytoscape { /** * Get elements in the graph matching the specified selector or filter function. */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. @@ -599,14 +606,20 @@ declare namespace cytoscape { ready(fn: EventHandler): void; } - interface ZoomOptions { - /** The zoom level to set. */ - level: number; + interface ZoomOptionsModel { /** The position about which to zoom. */ position: Position; + } + interface ZoomOptionsRendered { /** The rendered position about which to zoom. */ renderedPosition: Position; } + interface ZoomOptionsLevel { + /** The zoom level to set. */ + level: number; + } + type ZoomOptions = ZoomOptionsLevel & (ZoomOptionsModel | ZoomOptionsRendered); + /** * http://js.cytoscape.org/#core/viewport-manipulation */ @@ -615,14 +628,21 @@ declare namespace cytoscape { * Get the HTML DOM element in which the graph is visualised. * A null value is returned if the Core is headless. */ - container(): any; + container(): Element | null; /** * Pan the graph to the centre of a collection. * * @param eles The collection to centre upon. */ - center(eles?: Collection): CollectionElements; + center(eles?: CollectionArgument): this; + + /** + * Pan the graph to the centre of a collection. + * + * @param eles The collection to centre upon. + */ + centre(eles?: CollectionArgument): this; /** * Pan and zooms the graph to fit to a collection. @@ -631,13 +651,13 @@ declare namespace cytoscape { * @param eles [optional] The collection to fit to. * @param padding [optional] An amount of padding (in pixels) to have around the graph */ - fit(eles?: Collection, padding?: number): CollectionElements; + fit(eles?: CollectionArgument, padding?: number): this; /** * Reset the graph to the default zoom level and panning position. * http://js.cytoscape.org/#cy.reset */ - reset(): CollectionElements; + reset(): this; /** * Get the panning position of the graph. @@ -651,7 +671,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position to pan the graph to. */ - pan(renderedPosition?: Position): void; + pan(renderedPosition?: Position): this; /** * Relatively pan the graph by a specified rendered position vector. @@ -659,7 +679,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position vector to pan the graph by. */ - panBy(renderedPosition: Position): void; + panBy(renderedPosition: Position): this; /** * Get whether panning is enabled. @@ -867,7 +887,8 @@ declare namespace cytoscape { * there is no resize or style event for arbitrary DOM elements. * http://js.cytoscape.org/#cy.resize */ - resize(): CollectionElements; + resize(): this; + invalidateDimensions(): this; } /** @@ -875,15 +896,15 @@ declare namespace cytoscape { * */ interface AnimationFitOptions { - eles: CollectionElements | Selector; // to which the viewport will be fitted. + eles: CollectionArgument | Selector; // to which the viewport will be fitted. padding: number; // Padding to use with the fitting. } interface CenterOptions { - eles: CollectionElements | Selector; // to which the viewport will be selected. + eles: CollectionArgument | Selector; // to which the viewport will be selected. } - interface AnimateOptionsCommon { + interface AnimationOptions { /** A zoom level to which the graph will be animated. */ - zoom?: number; + zoom?: ZoomOptions; /** A panning position to which the graph will be animated. */ pan?: Position; /** A relative panning position to which the graph will be animated. */ @@ -892,11 +913,13 @@ declare namespace cytoscape { fit?: AnimationFitOptions; /** An object containing centring options from which the graph will be animated. */ center?: CenterOptions; + /** easing - A transition-timing-function easing style string that shapes the animation progress curve. */ + easing?: string; // TODO: explicit type /** duration - The duration of the animation in milliseconds. */ duration?: number; } - interface AnimateOptions extends AnimateOptionsCommon { + interface AnimateOptions extends AnimationOptions { /** queue - A boolean indicating whether to queue the animation. */ queue?: boolean; /** complete - A function to call when the animation is done. */ @@ -904,14 +927,6 @@ declare namespace cytoscape { /** step - A function to call each time the animation steps. */ step?(): void; } - interface AnimationOptions extends AnimateOptionsCommon { - /** queue - A transition-timing-function easing style string that shapes the animation progress curve. */ - easing?: boolean; - /** complete - A function to call when the animation is done. */ - complete?(): void; - /** step - A function to call each time the animation steps. */ - step?(): void; - } interface CoreAnimation { /** @@ -993,6 +1008,7 @@ declare namespace cytoscape { * An analogue to make a layout on a subset of the graph exists as eles.makeLayout(). */ makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1080,17 +1096,18 @@ declare namespace cytoscape { /** * Export the current graph view as a JPG image in Base64 representation. */ - jpg(options?: ExportOptions): string; + jpg(options?: ExportJpgOptions): string; /** * Export the current graph view as a JPG image in Base64 representation. */ - jpeg(options?: ExportOptions): string; + jpeg(options?: ExportJpgOptions): string; /** * Export the graph as JSON, the same format used at initialisation. */ - json(): string; + json(): object; + json(json: object): this; } /** @@ -1100,13 +1117,14 @@ declare namespace cytoscape { * The input can be any element (node and edge) collection. * http://js.cytoscape.org/#collection */ - interface Collection extends Singular, + interface Collection + extends Singular, CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, CollectionSelection, CollectionStyle, CollectionAnimation, - CollectionComparision, CollectionIteration, - CollectionBuildingUnion, CollectionAlgorithms { } + CollectionComparision, CollectionIteration, + CollectionBuildingFiltering, CollectionAlgorithms { } /** * ele --> Cy.Singular @@ -1127,7 +1145,8 @@ declare namespace cytoscape { /** * The output is a collection of node and edge elements OR single element. */ - type CollectionElements = EdgeCollection | NodeCollection | SingularElement; + type CollectionArgument = EdgeCollection | NodeCollection | SingularElementArgument; + type CollectionReturnValue = EdgeCollection & NodeCollection & SingularElementReturnValue; /** * edges -> Cy.EdgeCollection @@ -1135,7 +1154,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends Collection, EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1143,19 +1162,18 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends Collection, NodeSingular, NodeCollectionMetadata, NodeCollectionPosition, NodeCollectionTraversing, NodeCollectionCompound { } - interface SingularElement extends EdgeSingular, NodeSingular { - // Intentionally empty. - } + type SingularElementArgument = EdgeSingular | NodeSingular; + type SingularElementReturnValue = EdgeSingular & NodeSingular; /** * edge --> Cy.EdgeSingular * a collection of a single edge */ interface EdgeSingular extends Singular, - EdgeSingularData, EdgeSingularTraversing { } + EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular @@ -1172,24 +1190,24 @@ declare namespace cytoscape { * Remove the elements from the graph. * http://js.cytoscape.org/#eles.remove */ - remove(): CollectionElements; + remove(): CollectionReturnValue; /** * Put removed elements back into the graph. * http://js.cytoscape.org/#eles.restore */ - restore(): CollectionElements; + restore(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - clone(): CollectionElements; + clone(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - copy(): CollectionElements; + copy(): CollectionReturnValue; /** * Effectively move edges to different nodes. The modified (actually new) elements are returned. @@ -1207,6 +1225,10 @@ declare namespace cytoscape { * http://js.cytoscape.org/#collection/graph-manipulation */ interface SingularGraphManipulation { + /** + * Get the core instance that owns the element. + */ + cy(): Core; /** * Get whether the element has been removed from the graph. * http://js.cytoscape.org/#ele.removed @@ -1279,8 +1301,8 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.removeData * @param names A space-separated list of fields to delete. */ - removeData(names?: string): CollectionElements; - removeAttr(names?: string): CollectionElements; + removeData(names?: string): CollectionReturnValue; + removeAttr(names?: string): CollectionReturnValue; /** * Get an array of the plain JavaScript object @@ -1313,6 +1335,22 @@ declare namespace cytoscape { * @param obj The object containing name- value pairs to update data fields. */ data(obj: any): void; + /** + * Get a particular data field for the element. + * @param name The name of the field to get. + */ + attr(name?: string): any; + /** + * Set a particular data field for the element. + * @param name The name of the field to set. + * @param value The value to set for the field. + */ + attr(name: string, value: any): void; + /** + * Update multiple data fields at once via an object. + * @param obj The object containing name- value pairs to update data fields. + */ + attr(obj: any): void; /** * Get or set the scratchpad at a particular namespace, @@ -1461,17 +1499,77 @@ declare namespace cytoscape { * Get the (model) position of a node. */ position(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + position(dimension: PositionDimension): number; /** * Set the value of a specified position dimension. * @param dimension The position dimension to set. * @param value The value to set to the dimension. */ - position(dimension: PositionDimension, value?: Position): void; + position(dimension: PositionDimension, value: number): this; /** * Set the position using name-value pairs in the specified object. * @param pos An object specifying name-value pairs representing dimensions to set. */ - position(pos: Position): void; + position(pos: Position): this; + /** + * Get the (model) position of a node. + */ + modelPosition(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + modelPosition(pos: Position): this; + /** + * Get the (model) position of a node. + */ + point(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + point(pos: Position): this; + + /** + * Shift the positions of the nodes by a given model position vector. + * @param dimension The position dimension to shift. + * @param value The value to shift the dimension. + */ + shift(dimension: PositionDimension, value?: number): this; + /** + * Shift the positions of the nodes by a given model position vector. + * @param pos An object specifying name-value pairs representing dimensions to shift. + */ + shift(pos: Position): this; /** * Get or set the rendered (on-screen) position of a node. @@ -1542,8 +1640,8 @@ declare namespace cytoscape { * @param ele The element being iterated over for which the function should return a position to set. * @param ix The index of the element when iterating over the elements in the collection. */ - type ElementPositionFunction = (ele: CollectionElements, ix: number) => void; - type ElementCollectionFunction = (ele: CollectionElements, ix: number, eles: CollectionElements) => void; + type ElementPositionFunction = (ele: NodeSingular, ix: number) => void; + type ElementCollectionFunction = (ele: NodeSingular, ix: number, eles: CollectionArgument) => void; /** * http://js.cytoscape.org/#collection/position--dimensions @@ -1556,9 +1654,7 @@ declare namespace cytoscape { * http://js.cytoscape.org/#nodes.positions */ positions(handler: ElementPositionFunction | Position): void; - modelPositions(handler: ElementPositionFunction | Position): void; - points(handler: ElementPositionFunction | Position): void; /** @@ -1647,11 +1743,13 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.boundingBox */ boundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + boundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; /** * Get the bounding box of the elements in rendered coordinates. * @param options An object containing options for the function. */ renderedBoundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + renderedBoundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; } /** @@ -1668,9 +1766,9 @@ declare namespace cytoscape { * * @param options The layout options. */ - layout(options: LayoutOptions): CollectionElements; - makeLayout(options: LayoutOptions): CoreLayout; - createLayout(options: LayoutOptions): CoreLayout; + layout(options: LayoutOptions): LayoutManipulation; + makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1684,7 +1782,7 @@ declare namespace cytoscape { // easing of animation, if enabled animationEasing?: number; // collection of elements involved in the layout; set by cy.layout() or eles.layout() - eles: CollectionElements; + eles: CollectionArgument; // whether to fit the viewport to the graph fit?: boolean; // padding to leave between graph and viewport @@ -1811,11 +1909,50 @@ declare namespace cytoscape { flashClass(classes: ClassNames, duration?: number): void; /** - * Get or set a particular style property value. - * @param name The name of the visual style property to get. + * Set a particular style property value. + * @param name The name of the visual style property to set. * @param value The value to which the property is set. */ - style(name?: string, value?: any): any; + style(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + style(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + style(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + style(): {[index: string]: any}; + /** + * Set a particular style property value. + * @param name The name of the visual style property to set. + * @param value The value to which the property is set. + */ + css(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + css(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + css(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + css(): {[index: string]: any}; + /** + * Remove all or specific style overrides. + * @param names A space-separated list of property names to remove overrides + */ + removeStyle(names?: string): this; } /** @@ -1977,27 +2114,36 @@ declare namespace cytoscape { * * @param eles The other elements to compare to. */ - same(eles: Collection): boolean; + same(eles: CollectionArgument): boolean; /** * Determine whether this collection contains any of the same elements as another collection. * * @param eles The other elements to compare to. */ - anySame(eles: Collection): boolean; + anySame(eles: CollectionArgument): boolean; + + /** + * Determine whether this collection contains all of the elements of another collection. + */ + contains(eles: CollectionArgument): boolean; + /** + * Determine whether this collection contains all of the elements of another collection. + */ + has(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbors(eles: Collection): boolean; + allAreNeighbors(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbours(eles: Collection): boolean; + allAreNeighbours(eles: CollectionArgument): boolean; /** * Determine whether any element in this collection matches a selector. @@ -2021,7 +2167,7 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - some(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + some(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; /** * Determine whether all elements in this collection satisfy the specified test function. @@ -2032,13 +2178,13 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - every(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + every(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; } /** * http://js.cytoscape.org/#collection/iteration */ - interface CollectionIteration { + interface CollectionIteration { /** * Get the number of elements in the collection. */ @@ -2070,8 +2216,8 @@ declare namespace cytoscape { * eles - The collection of elements being iterated. * @param thisArg [optional] The value for this within the iterating function. */ - each(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; - forEach(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; + each(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; + forEach(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; /** * Get an element at a particular index in the collection. @@ -2080,21 +2226,21 @@ declare namespace cytoscape { * * @param index The index of the element to get. */ - eq(index: number): CollectionElements; + eq(index: number): TOut; /** * Get an element at a particular index in the collection. * * @param index The index of the element to get. */ - [index: number]: CollectionElements; + [index: number]: TOut; /** * Get the first element in the collection. */ - first(): CollectionElements; + first(): TOut; /** * Get the last element in the collection. */ - last(): CollectionElements; + last(): TOut; /** * Get a subset of the elements in the collection based on specified indices. @@ -2106,7 +2252,12 @@ declare namespace cytoscape { * If omitted, all elements from the start position and to the end of the array will be selected. * Use negative numbers to select from the end of an array. */ - slice(start?: number, end?: number): CollectionElements; + slice(start?: number, end?: number): this; + + /** + * Get the collection as an array, maintaining the order of the elements. + */ + toArray(): SingularElementReturnValue[]; } /** @@ -2118,7 +2269,7 @@ declare namespace cytoscape { * @param eles The elements or array of elements to add or elements in the graph matching the selector. * http://js.cytoscape.org/#eles.union */ - type CollectionBuildingUnionFunc = (eles: Collection | Collection[] | Selector) => CollectionElements; + type CollectionBuildingUnionFunc = (eles: CollectionArgument | CollectionArgument[] | Selector) => CollectionReturnValue; /** * Get a new collection, resulting from the collection without some specified elements. @@ -2126,7 +2277,7 @@ declare namespace cytoscape { * @param eles The elements that will not be in the resultant collection. * Elements from the calling collection matching this selector will not be in the resultant collection. */ - type CollectionBuildingDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2135,7 +2286,7 @@ declare namespace cytoscape { * A selector representing the elements to intersect with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionBuildingIntersectionFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingIntersectionFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements that are in the calling collection or the passed collection but not in both. @@ -2144,40 +2295,52 @@ declare namespace cytoscape { * A selector representing the elements to apply the symmetric difference with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionSymmetricDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionSymmetricDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * http://js.cytoscape.org/#collection/building--filtering */ - interface CollectionBuildingUnion { + interface CollectionBuildingFiltering { + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + getElementById(id: string): TOut; + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + $id(id: string): TOut; + /** * Get a new collection, resulting from adding the collection with another one * http://js.cytoscape.org/#eles.union */ union: CollectionBuildingUnionFunc; - // [index: "u"]: CollectionBuildingUnionFunc; + u: CollectionBuildingUnionFunc; add: CollectionBuildingUnionFunc; - // [index: "+"]: CollectionBuildingUnionFunc; + '+': CollectionBuildingUnionFunc; or: CollectionBuildingUnionFunc; - // [index: "|"]: CollectionBuildingUnionFunc; + '|': CollectionBuildingUnionFunc; /** * Get a new collection, resulting from the collection without some specified elements. * http://js.cytoscape.org/#eles.difference */ difference: CollectionBuildingDifferenceFunc; - // [index: "\\"]: CollectionBuildingDifferenceFunc; + subtract: CollectionBuildingDifferenceFunc; + '\\': CollectionBuildingDifferenceFunc; not: CollectionBuildingDifferenceFunc; - // [index: "!"]: CollectionBuildingDifferenceFunc; + '!': CollectionBuildingDifferenceFunc; relativeComplement: CollectionBuildingDifferenceFunc; - // [index: "-"]: CollectionBuildingDifferenceFunc; + '-': CollectionBuildingDifferenceFunc; /** * Get all elements in the graph that are not in the calling collection. * http://js.cytoscape.org/#eles.absoluteComplement */ - absoluteComplement(): CollectionElements; - abscomp(): CollectionElements; - complement(): CollectionElements; + absoluteComplement(): CollectionReturnValue; + abscomp(): CollectionReturnValue; + complement(): CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2186,9 +2349,9 @@ declare namespace cytoscape { intersection: CollectionSymmetricDifferenceFunc; intersect: CollectionSymmetricDifferenceFunc; and: CollectionSymmetricDifferenceFunc; - // [index: "n"]: CollectionSymmetricDifferenceFunc; - // [index: "&"]: CollectionSymmetricDifferenceFunc; - // [index: "."]: CollectionSymmetricDifferenceFunc; + n: CollectionSymmetricDifferenceFunc; + '&': CollectionSymmetricDifferenceFunc; + '.': CollectionSymmetricDifferenceFunc; /** * Get the elements that are in the calling collection @@ -2198,11 +2361,9 @@ declare namespace cytoscape { symmetricDifference: CollectionSymmetricDifferenceFunc; symdiff: CollectionSymmetricDifferenceFunc; xor: CollectionSymmetricDifferenceFunc; - // [index: "^"]: CollectionSymmetricDifferenceFunc; - // [index: "(+)"]: CollectionSymmetricDifferenceFunc; - // [index: "(-)"]: CollectionSymmetricDifferenceFunc; - - // [index: string]: CollectionBuildingDifferenceFunc |CollectionBuildingUnionFunc | CollectionBuildingDifferenceFunc | CollectionSymmetricDifferenceFunc; + '^': CollectionSymmetricDifferenceFunc; + '(+)': CollectionSymmetricDifferenceFunc; + '(-)': CollectionSymmetricDifferenceFunc; /** * Perform a traditional left/right diff on the two collections. @@ -2216,12 +2377,62 @@ declare namespace cytoscape { * both - is the set of elements in both collections. * http://js.cytoscape.org/#eles.diff */ - diff(selector: Selector | Collection): { - left: CollectionElements, - right: CollectionElements, - both: CollectionElements + diff(selector: Selector | CollectionArgument): { + left: CollectionReturnValue, + right: CollectionReturnValue, + both: CollectionReturnValue }; + /** + * Perform a in-place merge of the given elements into the calling collection. + * @param eles The elements to merge in-place or a selector representing the elements to merge. + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.union() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var j = cy.$('#j'); + * var e = cy.$('#e'); + * col.merge( j ).merge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge('#j').merge('#e'); + */ + merge(eles: CollectionArgument | string): this; + /** + * Perform an in-place operation on the calling collection to remove the given elements. + * @param eles The elements to remove in-place or a selector representing the elements to remove . + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.filter() or eles.remove() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var e = cy.$('#e'); + * col.merge( cy.nodes() ); + * col.unmerge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge( cy.nodes() ); + * col.unmerge('#e'); + */ + unmerge(eles: CollectionArgument | string): this; + /** * Get a new collection containing elements that are accepted by the specified filter. * @@ -2231,21 +2442,21 @@ declare namespace cytoscape { * ele - The element being considered. * http://js.cytoscape.org/#eles.filter */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: TOut, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Get the nodes that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - nodes(selector: Selector): NodeCollection; + nodes(selector?: Selector): NodeCollection; /** * Get the edges that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - edges(selector: Selector): EdgeCollection; + edges(selector?: Selector): EdgeCollection; /** * Get a new collection containing the elements sorted by the @@ -2257,7 +2468,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.sort */ - sort(sort: (ele1: CollectionElements, ele2: CollectionElements) => number): CollectionElements; + sort(sort: (ele1: CollectionArgument, ele2: CollectionArgument) => number): CollectionReturnValue; /** * Get an array containing values mapped from the collection. @@ -2270,7 +2481,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.map */ - map(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): any[]; + map(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): any[]; /** * Reduce a single value by applying a @@ -2282,11 +2493,13 @@ declare namespace cytoscape { * ele The current element. * ix The index of the current element. * eles The collection of elements being reduced. - * + * @param initialValue The initial value for reducing + * It is used also for type inference of output, but the type can be + * also stated explicitly as generic * http://js.cytoscape.org/#eles.reduce */ - reduce(fn: (prevVal: any, ele: CollectionElements, - ix: number, eles: CollectionElements) => any): number[]; + reduce(fn: (prevVal: T, ele: SingularElementReturnValue, + ix: number, eles: CollectionReturnValue) => T, initialValue: T): T; /** * Find a minimum value in a collection. @@ -2299,7 +2512,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.min */ - min(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + min(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The minimum value found. */ @@ -2307,7 +2520,7 @@ declare namespace cytoscape { /** * The element that corresponds to the minimum value. */ - ele: CollectionElements + ele: CollectionArgument }; /** @@ -2321,7 +2534,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.max */ - max(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + max(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The maximum value found. */ @@ -2329,7 +2542,7 @@ declare namespace cytoscape { /** * The element that corresponds to the maximum value. */ - ele: CollectionElements + ele: CollectionArgument }; } @@ -2351,7 +2564,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - neighborhood(selector?: Selector): CollectionElements; + neighborhood(selector?: Selector): CollectionReturnValue; /** * Get the open neighbourhood of the elements. @@ -2362,7 +2575,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - openNeighborhood(selector?: Selector): CollectionElements; + openNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the closed neighbourhood of the elements. * @@ -2372,13 +2585,54 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - closedNeighborhood(selector?: Selector): CollectionElements; + closedNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the connected components, considering only the elements in the calling collection. * An array of collections is returned, with each collection representing a component. */ - components(): Collection; + components(): CollectionReturnValue[]; + } + /** + * http://js.cytoscape.org/#collection/edge-points + */ + interface EdgeSingularPoints { + /** + * Get an array of control point model positions for a {@code curve-style: bezier) or {@code curve-style: unbundled-bezier} edge. + * + * While the control points may be specified relatively in the CSS, + * this function returns the absolute model positions of the control points. + * The points are specified in the order of source-to-target direction. + * This function works for bundled beziers, but it is not applicable to the middle, straight-line edge in the bundle. + */ + controlPoints(): Position[]; + /** + * Get an array of segment point model positions (i.e. bend points) for a {@code curve-style: segments} edge. + * + * While the segment points may be specified relatively in the stylesheet, + * this function returns the absolute model positions of the segment points. + * The points are specified in the order of source-to-target direction. + */ + segmentPoints(): Position[]; + /** + * Get the model position of where the edge ends, towards the source node. + */ + sourceEndpoint(): Position; + /** + * Get the model position of where the edge ends, towards the target node. + */ + targetEndpoint(): Position; + /** + * Get the model position of the midpoint of the edge. + * + * The midpoint is, by default, where the edge’s label is centred. It is also the position towards which mid arrows point. + * For curve-style: unbundled-bezier edges, the midpoint is the middle extremum if the number of control points is odd. + * For an even number of control points, the midpoint is where the two middle-most control points meet. + * This is the middle inflection point for bilaterally symmetric or skew symmetric edges, for example. + * For curve-style: segments edges, the midpoint is the middle segment point if the number of segment points is odd. + * For an even number of segment points, the overall midpoint is the midpoint of the middle-most line segment (i.e. the mean of the middle two segment points). + */ + midpoint(): Position; } interface EdgeSingularTraversing { /** @@ -2457,7 +2711,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesWith(eles: Collection | Selector): EdgeCollection; + edgesWith(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges coming from the collection (i.e. the source) going to another collection (i.e. the target). @@ -2465,7 +2719,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesTo(eles: Collection | Selector): EdgeCollection; + edgesTo(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges connected to the nodes in the collection. @@ -2537,7 +2791,7 @@ declare namespace cytoscape { /** * The root nodes (selector or collection) to start the search from. */ - roots: Selector | Collection; + roots: Selector | CollectionArgument; /** * A handler function that is called when a node is visited in the search. */ @@ -2552,7 +2806,7 @@ declare namespace cytoscape { * The path of the search. * - The path returned includes edges such that if path[i] is a node, then path[i - 1] is the edge used to get to that node. */ - path: CollectionElements; + path: CollectionArgument; /** * The node found by the search * - If no node was found, then found is empty. @@ -2568,7 +2822,7 @@ declare namespace cytoscape { /** * The root node (selector or collection) where the algorithm starts. */ - root: Selector | Collection; + root: Selector | CollectionArgument; /** * A function that returns the positive numeric weight for this edge. @@ -2596,14 +2850,14 @@ declare namespace cytoscape { * The path starts with the source node and includes the edges between the nodes in the path such that if pathTo(node)[i] is an edge, * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] is the next node in the path. */ - pathTo(node: NodeSingular): Collection; + pathTo(node: NodeSingular): CollectionReturnValue; } /** * http://js.cytoscape.org/#eles.aStar */ interface SearchAStarOptions { - root: Selector | Collection; - goal: Selector | Collection; + root: Selector | CollectionArgument; + goal: Selector | CollectionArgument; weight?: WeightFn; heuristic?(node: NodeCollection): number; directed?: boolean; @@ -2614,7 +2868,7 @@ declare namespace cytoscape { interface SearchAStarResult { found: boolean; distance: number; - path: Collection; + path: CollectionReturnValue; } /** @@ -2641,7 +2895,7 @@ declare namespace cytoscape { * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] * is the next node in the path. */ - path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): Collection; + path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): CollectionReturnValue; } /** @@ -2670,7 +2924,7 @@ declare namespace cytoscape { * function that computes the shortest path from root node to the argument node * (either objects or selector string) */ - pathTo(node: NodeSingular | Selector): Collection; + pathTo(node: NodeSingular | Selector): CollectionReturnValue; /** * function that computes the shortest distance from root node to argument node @@ -4368,13 +4622,13 @@ declare namespace cytoscape { * Start running the layout * http://js.cytoscape.org/#layout.run */ - run(): void; - start(): void; + run(): this; + start(): this; /** * Stop running the (asynchronous/discrete) layout * http://js.cytoscape.org/#layout.stop */ - stop(): void; + stop(): this; } interface LayoutEvents { /** diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 9a2f9ae34a..9f32212f6b 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -3277,7 +3277,7 @@ declare namespace d3 { round(round: boolean): Treemap; sticky(): boolean; - sticky(sticky: boolean): boolean; + sticky(sticky: boolean): Treemap; mode(): string; mode(mode: "squarify"): Treemap; diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 2fd3f3ae45..a8f63a999e 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1432,6 +1432,11 @@ declare namespace DataTables { */ tabIndex?: number; + /** + * Enable or disable datatables responsive. Since: 1.10 + */ + responsive?: boolean | object; + //#endregion "Options" //#region "Callbacks" diff --git a/types/dc/dc-tests.ts b/types/dc/dc-tests.ts index 643594276d..7e1a49727e 100644 --- a/types/dc/dc-tests.ts +++ b/types/dc/dc-tests.ts @@ -1,3 +1,8 @@ +import * as CrossFilter from 'crossfilter'; +import * as d3 from "d3"; +import * as dc from "dc"; + + interface IYelpData { city: string; review_count: number; diff --git a/types/dc/index.d.ts b/types/dc/index.d.ts index 4ba0e5e4ab..9100acdc26 100644 --- a/types/dc/index.d.ts +++ b/types/dc/index.d.ts @@ -5,10 +5,6 @@ // matthias jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files - -/// - import * as d3 from "d3"; export = dc; diff --git a/types/decompress/decompress-tests.ts b/types/decompress/decompress-tests.ts index 9cb8949d99..5ed96c0b46 100644 --- a/types/decompress/decompress-tests.ts +++ b/types/decompress/decompress-tests.ts @@ -19,3 +19,24 @@ decompress('unicorn.zip', 'dist', { }).then((files: decompress.File[]) => { console.log('done!'); }); + +// Test decompress with no output to filesystem +decompress('unicorn.zip') + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with no write to filesystem`); + } + ); + +// Test decompress with DecompressOptions as second argument +decompress( + 'unicorn.zip', + { + filter: file => path.extname(file.path) !== '.exe' + } +) + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with filter options`); + } + ); diff --git a/types/decompress/index.d.ts b/types/decompress/index.d.ts index 745bebcd2e..2c4f464558 100644 --- a/types/decompress/index.d.ts +++ b/types/decompress/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for decompress 4.2 // Project: https://github.com/kevva/decompress#readme // Definitions by: York Yao +// Jesse Bethke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = decompress; -declare function decompress(input: string | Buffer, output: string, opts?: decompress.DecompressOptions): Promise; +declare function decompress(input: string | Buffer, output?: string | decompress.DecompressOptions, opts?: decompress.DecompressOptions): Promise; declare namespace decompress { interface File { diff --git a/types/devexpress-aspnetcore-bootstrap/devexpress-aspnetcore-bootstrap-tests.ts b/types/devexpress-aspnetcore-bootstrap/devexpress-aspnetcore-bootstrap-tests.ts new file mode 100644 index 0000000000..55eae3c27f --- /dev/null +++ b/types/devexpress-aspnetcore-bootstrap/devexpress-aspnetcore-bootstrap-tests.ts @@ -0,0 +1,13 @@ +declare let button: DevExpress.AspNetCore.BootstrapButton; +button.on('click', e => {}); +button.doClick(); +button.once('click', e => {}); + +declare let accordion: DevExpress.AspNetCore.BootstrapAccordion; +accordion.on('init', e => {}); +const firstGroup = accordion.getGroup(0); +if (firstGroup) { + const groupText = firstGroup.getText(); + const item = firstGroup.getItemByName('item10'); + item && item.getEnabled(); +} diff --git a/types/devexpress-aspnetcore-bootstrap/index.d.ts b/types/devexpress-aspnetcore-bootstrap/index.d.ts new file mode 100644 index 0000000000..51d1c2ebb4 --- /dev/null +++ b/types/devexpress-aspnetcore-bootstrap/index.d.ts @@ -0,0 +1,2496 @@ +// Type definitions for DevExpress ASP.NET 181.3 +// Project: http://devexpress.com/ +// Definitions by: DevExpress Inc. +// Andrey Skubarenko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace DevExpress.AspNetCore { + enum BootstrapSchedulerGroupType { + Date = "Date", + None = "None", + Resource = "Resource", + } + enum BootstrapSchedulerViewType { + Day = "Day", + WorkWeek = "WorkWeek", + Week = "Week", + Month = "Month", + Timeline = "Timeline", + FullWeek = "FullWeek", + Agenda = "Agenda", + } + enum BootstrapSchedulerAppointmentType { + Normal = "Normal", + Pattern = "Pattern", + Occurrence = "Occurrence", + ChangedOccurrence = "ChangedOccurrence", + DeletedOccurrence = "DeletedOccurrence", + } + enum BootstrapSchedulerRecurrenceRange { + NoEndDate = "NoEndDate", + OccurrenceCount = "OccurrenceCount", + EndByDate = "EndByDate", + } + enum BootstrapSchedulerRecurrenceType { + Daily = "Daily", + Weekly = "Weekly", + Monthly = "Monthly", + Yearly = "Yearly", + Hourly = "Hourly", + } + enum WeekDays { + Sunday = 1, + Monday = 2, + Tuesday = 4, + Wednesday = 8, + Thursday = 16, + Friday = 32, + Saturday = 64, + WeekendDays = 65, + WorkDays = 62, + EveryDay = 127, + } + enum WeekOfMonth { + None = 0, + First = 1, + Second = 2, + Third = 3, + Fourth = 4, + Last = 5, + } + enum BootstrapPopupControlCloseReason { + API = "API", + CloseButton = "CloseButton", + OuterMouseClick = "OuterMouseClick", + MouseOut = "MouseOut", + Escape = "Escape", + } + + const Utils: { + getControls: () => Control[]; + getSerializedEditorValuesInContainer: (containerOrId: string | HTMLElement, processInvisibleEditors?: boolean) => any; + getEditorValuesInContainer: (containerOrId: string | HTMLElement, processInvisibleEditors?: boolean) => any; + }; + + interface EventArgs { + readonly sender: Control; + } + + interface CancelEventArgs extends EventArgs { + cancel: boolean; + } + + interface BeginCallbackEventArgs extends EventArgs { + readonly command: string; + } + + interface ProcessingModeEventArgs extends EventArgs { + processOnServer: boolean; + } + + interface ProcessingModeCancelEventArgs extends ProcessingModeEventArgs { + cancel: boolean; + } + + interface GlobalBeginCallbackEventArgs extends BeginCallbackEventArgs { + readonly control: Control; + } + + interface EndCallbackEventArgs extends EventArgs { // tslint:disable-line:no-empty-interface + } + + interface GlobalEndCallbackEventArgs extends EndCallbackEventArgs { + readonly control: Control; + } + + interface CustomDataCallbackEventArgs extends EventArgs { + result: string; + } + + interface CallbackErrorEventArgs extends EventArgs { + handled: boolean; + message: string; + } + + interface GlobalCallbackErrorEventArgs extends CallbackErrorEventArgs { + readonly control: Control; + } + + interface EditValidationEventArgs extends EventArgs { + errorText: string; + isValid: boolean; + value: string; + } + + interface ValidationCompletedEventArgs extends EventArgs { + readonly container: any; + readonly firstInvalidControl: Control; + readonly firstVisibleInvalidControl: Control; + readonly invisibleControlsValidated: boolean; + isValid: boolean; + readonly validationGroup: string; + } + + interface EditClickEventArgs extends EventArgs { + readonly htmlElement: any; + readonly htmlEvent: any; + } + + interface EditKeyEventArgs extends EventArgs { + readonly htmlEvent: any; + } + + class Control { + protected readonly instance: any; + protected constructor(instance: any); + readonly name: string; + adjustControl(): void; + getHeight(): number; + getMainElement(): any; + getParentControl(): any; + getVisible(): boolean; + getWidth(): number; + inCallback(): boolean; + sendMessageToAssistiveTechnology(message: string): void; + setHeight(height: number): void; + setVisible(visible: boolean): void; + setWidth(width: number): void; + on(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; + once(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; + off(): this; // tslint:disable-line:no-unnecessary-generics + off(eventName: K): this; // tslint:disable-line:unified-signatures no-unnecessary-generics + off(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; // tslint:disable-line:unified-signatures + } + interface ControlEventMap { + "init": EventArgs; + } + + class BootstrapClientEdit extends Control { + focus(): void; + getCaption(): string; + getEnabled(): boolean; + getErrorText(): string; + getInputElement(): any; + getIsValid(): boolean; + getReadOnly(): boolean; + getValue(): any; + setCaption(caption: string): void; + setEnabled(value: boolean): void; + setErrorText(errorText: string): void; + setIsValid(isValid: boolean): void; + setReadOnly(readOnly: boolean): void; + setValue(value: any): void; + validate(): void; + on(eventName: K, callback: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; + } + interface BootstrapClientEditEventMap extends ControlEventMap { + "gotFocus": EventArgs; + "lostFocus": EventArgs; + "validation": EditValidationEventArgs; + "valueChanged": ProcessingModeEventArgs; + } + + interface AccordionItemEventArgs extends ProcessingModeEventArgs { + readonly htmlElement: object; + readonly htmlEvent: object; + readonly item: BootstrapAccordionItem; + } + + interface AccordionGroupEventArgs extends EventArgs { + readonly group: BootstrapAccordionGroup; + } + + interface AccordionGroupCancelEventArgs extends ProcessingModeCancelEventArgs { + readonly group: BootstrapAccordionGroup; + } + + interface AccordionGroupClickEventArgs extends AccordionGroupCancelEventArgs { + readonly htmlElement: object; + readonly htmlEvent: object; + } + + class BootstrapAccordion extends Control { + collapseAll(): void; + expandAll(): void; + getActiveGroup(): BootstrapAccordionGroup | null; + getGroup(index: number): BootstrapAccordionGroup | null; + getGroupByName(name: string): BootstrapAccordionGroup | null; + getGroupCount(): number; + getItemByName(name: string): BootstrapAccordionItem | null; + getSelectedItem(): BootstrapAccordionItem | null; + setActiveGroup(group: BootstrapAccordionGroup): void; + setSelectedItem(item: BootstrapAccordionItem): void; + on(eventName: K, callback: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; + } + interface BootstrapAccordionEventMap extends ControlEventMap { + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "endCallback": EndCallbackEventArgs; + "expandedChanged": AccordionGroupEventArgs; + "expandedChanging": AccordionGroupCancelEventArgs; + "headerClick": AccordionGroupClickEventArgs; + "itemClick": AccordionItemEventArgs; + } + + class BootstrapAccordionGroup { + protected readonly instance: any; + protected constructor(instance: any); + readonly index: number; + readonly name: string; + readonly navBar: BootstrapAccordion | null; + getEnabled(): boolean; + getExpanded(): boolean; + getHeaderBadgeIconCssClass(): string; + getHeaderBadgeText(): string; + getItem(index: number): BootstrapAccordionItem | null; + getItemByName(name: string): BootstrapAccordionItem | null; + getItemCount(): number; + getText(): string; + getVisible(): boolean; + setExpanded(value: boolean): void; + setHeaderBadgeIconCssClass(cssClass: string): void; + setHeaderBadgeText(text: string): void; + setText(text: string): void; + setVisible(value: boolean): void; + } + + class BootstrapAccordionItem { + protected readonly instance: any; + protected constructor(instance: any); + readonly group: BootstrapAccordionGroup | null; + readonly index: number; + readonly name: string; + readonly navBar: BootstrapAccordion | null; + getBadgeIconCssClass(): string; + getBadgeText(): string; + getEnabled(): boolean; + getIconCssClass(): string; + getImageUrl(): string; + getNavigateUrl(): string; + getText(): string; + getVisible(): boolean; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setEnabled(value: boolean): void; + setIconCssClass(cssClass: string): void; + setImageUrl(value: string): void; + setNavigateUrl(value: string): void; + setText(value: string): void; + setVisible(value: boolean): void; + } + + class BootstrapBinaryImage extends BootstrapClientEdit { + clear(): void; + getUploadedFileName(): string; + getValue(): any; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + setSize(width: number, height: number): void; + setValue(value: any): void; + on(eventName: K, callback: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; + } + interface BootstrapBinaryImageEventMap extends BootstrapClientEditEventMap { + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "click": EditClickEventArgs; + "endCallback": EndCallbackEventArgs; + } + + interface ButtonClickEventArgs extends ProcessingModeEventArgs { + readonly cancelEventAndBubble: boolean; + } + + class BootstrapButton extends Control { + doClick(): void; + focus(): void; + getBadgeIconCssClass(): string; + getBadgeText(): string; + getChecked(): boolean; + getEnabled(): boolean; + getImageUrl(): string; + getText(): string; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setChecked(value: boolean): void; + setEnabled(value: boolean): void; + setImageUrl(value: string): void; + setText(value: string): void; + on(eventName: K, callback: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; + } + interface BootstrapButtonEventMap extends ControlEventMap { + "checkedChanged": ProcessingModeEventArgs; + "click": ButtonClickEventArgs; + "gotFocus": EventArgs; + "lostFocus": EventArgs; + } + + interface CalendarCustomDisabledDateEventArgs extends EventArgs { + readonly date: Date; + isDisabled: boolean; + } + + class BootstrapCalendar extends BootstrapClientEdit { + clearSelection(): void; + deselectDate(date: Date): void; + deselectRange(start: Date, end: Date): void; + getEnabled(): boolean; + getMaxDate(): Date; + getMinDate(): Date; + getSelectedDate(): Date; + getSelectedDates(): Date[]; + getVisibleDate(): Date; + isDateSelected(date: Date): boolean; + selectDate(date: Date): void; + selectRange(start: Date, end: Date): void; + setEnabled(enabled: boolean): void; + setMaxDate(date: Date): void; + setMinDate(date: Date): void; + setSelectedDate(date: Date): void; + setVisibleDate(date: Date): void; + on(eventName: K, callback: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; + } + interface BootstrapCalendarEventMap extends BootstrapClientEditEventMap { + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "customDisabledDate": CalendarCustomDisabledDateEventArgs; + "endCallback": EndCallbackEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "selectionChanged": ProcessingModeEventArgs; + "visibleMonthChanged": ProcessingModeEventArgs; + } + + interface GridToolbarItemClickEventArgs extends ProcessingModeEventArgs { + readonly item: BootstrapMenuItem; + readonly toolbarIndex: number; + readonly toolbarName: string; + usePostBack: boolean; + } + + class BootstrapGridBase extends Control { + getToolbar(index: number): BootstrapMenu | null; + getToolbarByName(name: string): BootstrapMenu | null; + on(eventName: K, callback: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; + } + interface BootstrapGridBaseEventMap extends ControlEventMap { + "toolbarItemClick": GridToolbarItemClickEventArgs; + } + + interface CardViewColumnCancelEventArgs extends CancelEventArgs { + readonly column: BootstrapCardViewColumn; + } + + interface CardViewCardFocusingEventArgs extends CancelEventArgs { + readonly htmlEvent: any; + readonly visibleIndex: number; + } + + interface CardViewCardClickEventArgs extends CancelEventArgs { + readonly htmlEvent: any; + readonly visibleIndex: number; + } + + interface CardViewCustomButtonEventArgs extends ProcessingModeEventArgs { + readonly buttonID: string; + readonly visibleIndex: number; + } + + interface CardViewSelectionEventArgs extends ProcessingModeEventArgs { + readonly isAllRecordsOnPage: boolean; + readonly isChangedOnServer: boolean; + readonly isSelected: boolean; + readonly visibleIndex: number; + } + + interface CardViewFocusEventArgs extends ProcessingModeEventArgs { + readonly isChangedOnServer: boolean; + } + + interface CardViewBatchEditStartEditingEventArgs extends CancelEventArgs { + readonly cardValues: any; + focusedColumn: BootstrapCardViewColumn; + readonly visibleIndex: number; + } + + interface CardViewBatchEditEndEditingEventArgs extends CancelEventArgs { + readonly cardValues: any; + readonly visibleIndex: number; + } + + interface CardViewBatchEditCardValidatingEventArgs extends EventArgs { + readonly validationInfo: any; + readonly visibleIndex: number; + } + + interface CardViewBatchEditConfirmShowingEventArgs extends CancelEventArgs { + readonly requestTriggerID: string; + } + + interface CardViewBatchEditTemplateCellFocusedEventArgs extends EventArgs { + readonly column: BootstrapCardViewColumn; + handled: boolean; + } + + interface CardViewBatchEditChangesSavingEventArgs extends CancelEventArgs { + readonly deletedValues: any; + readonly insertedValues: any; + readonly updatedValues: any; + } + + interface CardViewBatchEditChangesCancelingEventArgs extends CancelEventArgs { + readonly deletedValues: any; + readonly insertedValues: any; + readonly updatedValues: any; + } + + interface CardViewBatchEditCardInsertingEventArgs extends CancelEventArgs { + readonly visibleIndex: number; + } + + interface CardViewBatchEditCardDeletingEventArgs extends CancelEventArgs { + readonly cardValues: any; + readonly visibleIndex: number; + } + + interface CardViewFocusedCellChangingEventArgs extends CancelEventArgs { + readonly cellInfo: BootstrapCardViewCellInfo; + } + + class BootstrapCardView extends BootstrapGridBase { + readonly batchEditApi: BootstrapCardViewBatchEditApi | null; + addNewCard(): void; + applyFilter(filterExpression: string): void; + applySearchPanelFilter(value: string): void; + cancelEdit(): void; + clearFilter(): void; + closeFilterControl(): void; + deleteCard(visibleIndex: number): void; + deleteCardByKey(key: any): void; + focus(): void; + focusEditor(column: BootstrapCardViewColumn): void; + focusEditor(columnIndex: number): void; // tslint:disable-line:unified-signatures + focusEditor(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + getCardKey(visibleIndex: number): string; + getColumn(columnIndex: number): BootstrapCardViewColumn | null; + getColumnByField(columnFieldName: string): BootstrapCardViewColumn | null; + getColumnById(columnId: string): BootstrapCardViewColumn | null; + getColumnCount(): number; + getEditValue(column: BootstrapCardViewColumn): string; + getEditValue(columnIndex: number): string; // tslint:disable-line:unified-signatures + getEditValue(columnFieldNameOrId: string): string; // tslint:disable-line:unified-signatures unified-signatures + getEditor(column: BootstrapCardViewColumn): BootstrapClientEdit; + getEditor(columnIndex: number): BootstrapClientEdit; // tslint:disable-line:unified-signatures + getEditor(columnFieldNameOrId: string): BootstrapClientEdit; // tslint:disable-line:unified-signatures unified-signatures + getFocusedCardIndex(): number; + getFocusedCell(): BootstrapCardViewCellInfo | null; + getPageCount(): number; + getPageIndex(): number; + getPopupEditForm(): BootstrapPopupControl | null; + getSelectedCardCount(): number; + getSelectedKeysOnPage(): any[]; + getTopVisibleIndex(): number; + getVerticalScrollPosition(): number; + getVisibleCardsOnPage(): number; + gotoPage(pageIndex: number): void; + hideCustomizationWindow(): void; + isCardSelectedOnPage(visibleIndex: number): boolean; + isCustomizationWindowVisible(): boolean; + isEditing(): boolean; + isNewCardEditing(): boolean; + moveColumn(column: BootstrapCardViewColumn): void; + moveColumn(columnIndex: number): void; // tslint:disable-line:unified-signatures + moveColumn(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + moveColumn(column: BootstrapCardViewColumn, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures + moveColumn(columnIndex: number, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures + moveColumn(columnFieldNameOrId: string, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + moveColumn(column: BootstrapCardViewColumn, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures + moveColumn(columnIndex: number, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures unified-signatures + moveColumn(columnFieldNameOrId: string, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + nextPage(): void; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + prevPage(): void; + refresh(): void; + selectAllCardsOnPage(): void; + selectCardOnPage(visibleIndex: number): void; + selectCardOnPage(visibleIndex: number, selected: boolean): void; // tslint:disable-line:unified-signatures + selectCards(): void; + selectCardsByKey(keys: any[]): void; + selectCardsByKey(key: any): void; // tslint:disable-line:unified-signatures + selectCardsByKey(keys: any[], selected: boolean): void; // tslint:disable-line:unified-signatures + selectCardsByKey(key: any, selected: boolean): void; // tslint:disable-line:unified-signatures unified-signatures + setEditValue(column: BootstrapCardViewColumn, value: string): void; + setEditValue(columnIndex: number, value: string): void; // tslint:disable-line:unified-signatures + setEditValue(columnFieldNameOrId: string, value: string): void; // tslint:disable-line:unified-signatures unified-signatures + setFilterEnabled(isFilterEnabled: boolean): void; + setFocusedCardIndex(visibleIndex: number): void; + setFocusedCell(cardVisibleIndex: number, columnIndex: number): void; + setSearchPanelCustomEditor(editor: BootstrapClientEdit): void; + setVerticalScrollPosition(position: number): void; + showCustomizationWindow(): void; + showFilterControl(): void; + sortBy(column: BootstrapCardViewColumn): void; + sortBy(columnIndex: number): void; // tslint:disable-line:unified-signatures + sortBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(column: BootstrapCardViewColumn, sortOrder: string): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + sortBy(column: BootstrapCardViewColumn, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + sortBy(column: BootstrapCardViewColumn, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + startEditCard(visibleIndex: number): void; + startEditCardByKey(key: any): void; + unselectAllCardsOnPage(): void; + unselectCardOnPage(visibleIndex: number): void; + unselectCards(): void; + unselectCardsByKey(keys: any[]): void; + unselectCardsByKey(key: any): void; // tslint:disable-line:unified-signatures + unselectFilteredCards(): void; + updateEdit(): void; + on(eventName: K, callback: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; + } + interface BootstrapCardViewEventMap extends BootstrapGridBaseEventMap { + "batchEditCardDeleting": CardViewBatchEditCardDeletingEventArgs; + "batchEditCardInserting": CardViewBatchEditCardInsertingEventArgs; + "batchEditCardValidating": CardViewBatchEditCardValidatingEventArgs; + "batchEditChangesCanceling": CardViewBatchEditChangesCancelingEventArgs; + "batchEditChangesSaving": CardViewBatchEditChangesSavingEventArgs; + "batchEditConfirmShowing": CardViewBatchEditConfirmShowingEventArgs; + "batchEditEndEditing": CardViewBatchEditEndEditingEventArgs; + "batchEditStartEditing": CardViewBatchEditStartEditingEventArgs; + "batchEditTemplateCellFocused": CardViewBatchEditTemplateCellFocusedEventArgs; + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "cardClick": CardViewCardClickEventArgs; + "cardDblClick": CardViewCardClickEventArgs; + "cardFocusing": CardViewCardFocusingEventArgs; + "columnSorting": CardViewColumnCancelEventArgs; + "customButtonClick": CardViewCustomButtonEventArgs; + "customizationWindowCloseUp": EventArgs; + "endCallback": EndCallbackEventArgs; + "focusedCardChanged": CardViewFocusEventArgs; + "focusedCellChanging": CardViewFocusedCellChangingEventArgs; + "selectionChanged": CardViewSelectionEventArgs; + } + + class BootstrapCardViewBatchEditApi { + protected readonly instance: any; + protected constructor(instance: any); + addNewCard(): void; + deleteCard(visibleIndex: number): void; + deleteCardByKey(key: any): void; + getCardVisibleIndices(includeDeleted: boolean): number[]; + getDeletedCardIndices(): number[]; + getInsertedCardIndices(): number[]; + isDeletedCard(visibleIndex: number): boolean; + isNewCard(visibleIndex: number): boolean; + recoverCard(visibleIndex: number): void; + recoverCardByKey(key: any): void; + validateCard(visibleIndex: number): boolean; + validateCards(validateOnlyModified: boolean): boolean; + } + + class BootstrapCardViewColumn { + protected readonly instance: any; + protected constructor(instance: any); + } + + class BootstrapCardViewCellInfo { + protected readonly instance: any; + protected constructor(instance: any); + readonly cardVisibleIndex: number; + endEdit(): void; + getCellTextContainer(visibleIndex: number, columnFieldNameOrId: string): any; + getCellValue(visibleIndex: number, columnFieldNameOrId: string, initial: boolean): any; + getColumnDisplayText(columnFieldNameOrId: string, value: any): string; + getEditCellInfo(): BootstrapCardViewCellInfo | null; + hasChanges(): boolean; + moveFocusBackward(): boolean; + moveFocusForward(): boolean; + resetChanges(visibleIndex: number): void; + resetChanges(visibleIndex: number, columnIndex: number): void; // tslint:disable-line:unified-signatures + setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any): void; + setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any, displayText: string, cancelCellHighlighting: boolean): void; + startEdit(visibleIndex: number, columnIndex: number): void; + } + + interface BootstrapChartEventArgsBase extends EventArgs { + readonly component: any; + readonly element: any; + } + + interface BootstrapChartErrorEventArgs extends BootstrapChartEventArgsBase { + readonly target: any; + } + + interface BootstrapChartElementActionEventArgs extends BootstrapChartEventArgsBase { + readonly target: any; + } + + interface BootstrapChartElementClickEventArgs extends BootstrapChartElementActionEventArgs { + readonly jQueryEvent: any; + } + + interface BootstrapChartExportEventArgs extends BootstrapChartEventArgsBase { + cancel: boolean; + readonly data: any; + readonly fileName: string; + readonly format: string; + } + + interface BootstrapChartOptionChangedEventArgs extends BootstrapChartEventArgsBase { + readonly fullName: string; + readonly name: string; + readonly previousValue: any; + readonly value: any; + } + + interface BootstrapChartZoomEndEventArgs extends BootstrapChartEventArgsBase { + readonly rangeEnd: any; + readonly rangeStart: any; + } + + class BootstrapChart extends Control { + exportTo(format: string, fileName: string): void; + getDataSource(): any; + getInstance(): any; + print(): void; + setDataSource(dataSource: any): void; + setOptions(options: any): void; + on(eventName: K, callback: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; + } + interface BootstrapChartEventMap extends ControlEventMap { + "argumentAxisClick": BootstrapChartElementClickEventArgs; + "disposing": BootstrapChartEventArgsBase; + "done": BootstrapChartEventArgsBase; + "drawn": BootstrapChartEventArgsBase; + "exported": BootstrapChartEventArgsBase; + "exporting": BootstrapChartExportEventArgs; + "fileSaving": BootstrapChartExportEventArgs; + "incidentOccurred": BootstrapChartErrorEventArgs; + "init": BootstrapChartEventArgsBase; + "legendClick": BootstrapChartElementClickEventArgs; + "optionChanged": BootstrapChartOptionChangedEventArgs; + "pointClick": BootstrapChartElementClickEventArgs; + "pointHoverChanged": BootstrapChartElementActionEventArgs; + "pointSelectionChanged": BootstrapChartElementActionEventArgs; + "seriesClick": BootstrapChartElementClickEventArgs; + "seriesHoverChanged": BootstrapChartElementActionEventArgs; + "seriesSelectionChanged": BootstrapChartElementActionEventArgs; + "tooltipHidden": BootstrapChartElementActionEventArgs; + "tooltipShown": BootstrapChartElementActionEventArgs; + "zoomEnd": BootstrapChartZoomEndEventArgs; + "zoomStart": BootstrapChartEventArgsBase; + } + + class BootstrapPolarChart extends Control { + exportTo(format: string, fileName: string): void; + getDataSource(): any; + getInstance(): any; + print(): void; + setDataSource(dataSource: any): void; + setOptions(options: any): void; + on(eventName: K, callback: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; + } + interface BootstrapPolarChartEventMap extends ControlEventMap { + "argumentAxisClick": BootstrapChartElementClickEventArgs; + "disposing": BootstrapChartEventArgsBase; + "done": BootstrapChartEventArgsBase; + "drawn": BootstrapChartEventArgsBase; + "exported": BootstrapChartEventArgsBase; + "exporting": BootstrapChartExportEventArgs; + "fileSaving": BootstrapChartExportEventArgs; + "incidentOccurred": BootstrapChartErrorEventArgs; + "init": BootstrapChartEventArgsBase; + "legendClick": BootstrapChartElementClickEventArgs; + "optionChanged": BootstrapChartOptionChangedEventArgs; + "pointClick": BootstrapChartElementClickEventArgs; + "pointHoverChanged": BootstrapChartElementActionEventArgs; + "pointSelectionChanged": BootstrapChartElementActionEventArgs; + "seriesClick": BootstrapChartElementClickEventArgs; + "seriesHoverChanged": BootstrapChartElementActionEventArgs; + "seriesSelectionChanged": BootstrapChartElementActionEventArgs; + "tooltipHidden": BootstrapChartElementActionEventArgs; + "tooltipShown": BootstrapChartElementActionEventArgs; + } + + class BootstrapPieChart extends Control { + exportTo(format: string, fileName: string): void; + getDataSource(): any; + getInstance(): any; + print(): void; + setDataSource(dataSource: any): void; + setOptions(options: any): void; + on(eventName: K, callback: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; + } + interface BootstrapPieChartEventMap extends ControlEventMap { + "disposing": BootstrapChartEventArgsBase; + "done": BootstrapChartEventArgsBase; + "drawn": BootstrapChartEventArgsBase; + "exported": BootstrapChartEventArgsBase; + "exporting": BootstrapChartExportEventArgs; + "fileSaving": BootstrapChartExportEventArgs; + "incidentOccurred": BootstrapChartErrorEventArgs; + "init": BootstrapChartEventArgsBase; + "legendClick": BootstrapChartElementClickEventArgs; + "optionChanged": BootstrapChartOptionChangedEventArgs; + "pointClick": BootstrapChartElementClickEventArgs; + "pointHoverChanged": BootstrapChartElementActionEventArgs; + "pointSelectionChanged": BootstrapChartElementActionEventArgs; + "tooltipHidden": BootstrapChartElementActionEventArgs; + "tooltipShown": BootstrapChartElementActionEventArgs; + } + + class BootstrapCheckBox extends BootstrapClientEdit { + getCheckState(): string; + getChecked(): boolean; + getText(): string; + setCheckState(checkState: string): void; + setChecked(isChecked: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; + } + interface BootstrapCheckBoxEventMap extends BootstrapClientEditEventMap { + "checkedChanged": ProcessingModeEventArgs; + } + + class BootstrapRadioButton extends BootstrapClientEdit { + getCheckState(): string; + getChecked(): boolean; + getText(): string; + setCheckState(checkState: string): void; + setChecked(isChecked: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; + } + interface BootstrapRadioButtonEventMap extends BootstrapClientEditEventMap { + "checkedChanged": ProcessingModeEventArgs; + } + + class BootstrapComboBox extends BootstrapClientEdit { + addItem(texts: string[]): number; + addItem(text: string): number; // tslint:disable-line:unified-signatures + addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures + addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures + addItemCssClass(index: number, className: string): void; + addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + adjustDropDownWindow(): void; + beginUpdate(): void; + clearItems(): void; + endUpdate(): void; + ensureDropDownLoaded(callbackFunction: any): void; + findItemByText(text: string): BootstrapListBoxItem | null; + findItemByValue(value: any): BootstrapListBoxItem | null; + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getItem(index: number): BootstrapListBoxItem | null; + getItemBadgeIconCssClass(index: number): string; + getItemBadgeText(index: number): string; + getItemCount(): number; + getSelectedIndex(): number; + getSelectedItem(): BootstrapListBoxItem | null; + getText(): string; + hideDropDown(): void; + insertItem(index: number, texts: string[]): void; + insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures + insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures + makeItemVisible(index: number): void; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + removeItem(index: number): void; + removeItemCssClass(index: number, className: string): void; + removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setItemBadgeIconCssClass(index: number, cssClass: string): void; + setItemBadgeText(index: number, text: string): void; + setItemHtml(index: number, html: string): void; + setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; + setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; + setItemTooltip(index: number, tooltip: string): void; + setSelectedIndex(index: number): void; + setSelectedItem(item: BootstrapListBoxItem): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string, applyFilter: boolean): void; + showDropDown(): void; + on(eventName: K, callback: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; + } + interface BootstrapComboBoxEventMap extends BootstrapClientEditEventMap { + "beginCallback": BeginCallbackEventArgs; + "buttonClick": ButtonEditClickEventArgs; + "callbackError": CallbackErrorEventArgs; + "closeUp": EventArgs; + "customHighlighting": ListEditCustomHighlightingEventArgs; + "dropDown": EventArgs; + "endCallback": EndCallbackEventArgs; + "itemFiltering": ListEditItemFilteringEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "queryCloseUp": CancelEventArgs; + "selectedIndexChanged": ProcessingModeEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + interface ParseDateEventArgs extends EventArgs { + readonly date: Date; + readonly handled: boolean; + readonly value: string; + } + + class BootstrapDateEdit extends BootstrapClientEdit { + adjustDropDownWindow(): void; + getButtonVisible(number: number): boolean; + getCalendar(): BootstrapCalendar | null; + getCaretPosition(): number; + getDate(): Date; + getMaxDate(): Date; + getMinDate(): Date; + getRangeDayCount(): number; + getText(): string; + getTimeEdit(): BootstrapTimeEdit | null; + hideDropDown(): void; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setDate(date: Date): void; + setMaxDate(date: Date): void; + setMinDate(date: Date): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + showDropDown(): void; + on(eventName: K, callback: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; + } + interface BootstrapDateEditEventMap extends BootstrapClientEditEventMap { + "buttonClick": ButtonEditClickEventArgs; + "calendarCustomDisabledDate": CalendarCustomDisabledDateEventArgs; + "closeUp": EventArgs; + "dateChanged": ProcessingModeEventArgs; + "dropDown": EventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "parseDate": ParseDateEventArgs; + "queryCloseUp": CancelEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapDropDownEdit extends BootstrapClientEdit { + adjustDropDownWindow(): void; + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getKeyValue(): string; + getText(): string; + hideDropDown(): void; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setKeyValue(keyValue: string): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + showDropDown(): void; + on(eventName: K, callback: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; + } + interface BootstrapDropDownEditEventMap extends BootstrapClientEditEventMap { + "buttonClick": ButtonEditClickEventArgs; + "closeUp": EventArgs; + "dropDown": EventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "queryCloseUp": CancelEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapFormLayout extends Control { + getItemByName(name: string): BootstrapFormLayoutItem | null; + on(eventName: K, callback: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; + } + interface BootstrapFormLayoutEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapFormLayoutItem { + protected readonly instance: any; + protected constructor(instance: any); + readonly formLayout: BootstrapFormLayout | null; + readonly name: string; + readonly parent: BootstrapFormLayoutItem | null; + getCaption(): string; + getItemByName(name: string): BootstrapFormLayoutItem | null; + getVisible(): boolean; + setCaption(caption: string): void; + setVisible(value: boolean): void; + } + + interface GridViewColumnCancelEventArgs extends CancelEventArgs { + readonly column: BootstrapGridViewColumn; + } + + interface GridViewColumnProcessingModeEventArgs extends ProcessingModeEventArgs { + readonly column: BootstrapGridViewColumn; + } + + interface GridViewRowCancelEventArgs extends CancelEventArgs { + readonly visibleIndex: number; + } + + interface GridViewSelectionEventArgs extends ProcessingModeEventArgs { + readonly isAllRecordsOnPage: boolean; + readonly isChangedOnServer: boolean; + readonly isSelected: boolean; + readonly visibleIndex: number; + } + + interface GridViewFocusEventArgs extends ProcessingModeEventArgs { + readonly isChangedOnServer: boolean; + } + + interface GridViewRowFocusingEventArgs extends GridViewRowCancelEventArgs { + readonly htmlEvent: any; + } + + interface GridViewRowClickEventArgs extends GridViewRowCancelEventArgs { + readonly htmlEvent: any; + } + + interface GridViewContextMenuEventArgs extends EventArgs { + readonly htmlEvent: any; + readonly index: number; + readonly menu: any; + readonly objectType: string; + showBrowserMenu: boolean; + } + + interface GridViewContextMenuItemClickEventArgs extends ProcessingModeEventArgs { + readonly elementIndex: number; + handled: boolean; + readonly item: BootstrapMenuItem; + readonly objectType: string; + usePostBack: boolean; + } + + interface GridViewCustomButtonEventArgs extends ProcessingModeEventArgs { + readonly buttonID: string; + readonly visibleIndex: number; + } + + interface GridViewColumnMovingEventArgs extends EventArgs { + allow: boolean; + readonly destinationColumn: BootstrapGridViewColumn; + readonly isDropBefore: boolean; + readonly isGroupPanel: boolean; + readonly sourceColumn: BootstrapGridViewColumn; + } + + interface GridViewBatchEditConfirmShowingEventArgs extends CancelEventArgs { + readonly requestTriggerID: string; + } + + interface GridViewBatchEditStartEditingEventArgs extends CancelEventArgs { + focusedColumn: BootstrapGridViewColumn; + readonly rowValues: any; + readonly visibleIndex: number; + } + + interface GridViewBatchEditEndEditingEventArgs extends CancelEventArgs { + readonly rowValues: any; + readonly visibleIndex: number; + } + + interface GridViewBatchEditRowValidatingEventArgs extends EventArgs { + readonly validationInfo: any; + readonly visibleIndex: number; + } + + interface GridViewBatchEditTemplateCellFocusedEventArgs extends EventArgs { + readonly column: BootstrapGridViewColumn; + handled: boolean; + } + + interface GridViewBatchEditChangesSavingEventArgs extends CancelEventArgs { + readonly deletedValues: any; + readonly insertedValues: any; + readonly updatedValues: any; + } + + interface GridViewBatchEditChangesCancelingEventArgs extends CancelEventArgs { + readonly deletedValues: any; + readonly insertedValues: any; + readonly updatedValues: any; + } + + interface GridViewBatchEditRowInsertingEventArgs extends CancelEventArgs { + readonly visibleIndex: number; + } + + interface GridViewBatchEditRowDeletingEventArgs extends CancelEventArgs { + readonly rowValues: any; + readonly visibleIndex: number; + } + + interface GridViewFocusedCellChangingEventArgs extends CancelEventArgs { + readonly cellInfo: BootstrapGridViewCellInfo; + } + + class BootstrapGridView extends BootstrapGridBase { + readonly batchEditApi: BootstrapGridViewBatchEditApi | null; + addNewRow(): void; + applyFilter(filterExpression: string): void; + applyOnClickRowFilter(): void; + applySearchPanelFilter(value: string): void; + autoFilterByColumn(column: BootstrapGridViewColumn, val: string): void; + autoFilterByColumn(columnIndex: number, val: string): void; // tslint:disable-line:unified-signatures + autoFilterByColumn(columnFieldNameOrId: string, val: string): void; // tslint:disable-line:unified-signatures unified-signatures + cancelEdit(): void; + clearFilter(): void; + closeFilterControl(): void; + collapseAll(): void; + collapseAllDetailRows(): void; + collapseDetailRow(visibleIndex: number): void; + collapseRow(visibleIndex: number): void; + collapseRow(visibleIndex: number, recursive: boolean): void; // tslint:disable-line:unified-signatures + deleteRow(visibleIndex: number): void; + deleteRowByKey(key: any): void; + expandAll(): void; + expandAllDetailRows(): void; + expandDetailRow(visibleIndex: number): void; + expandRow(visibleIndex: number): void; + expandRow(visibleIndex: number, recursive: boolean): void; // tslint:disable-line:unified-signatures + focus(): void; + focusEditor(column: BootstrapGridViewColumn): void; + focusEditor(columnIndex: number): void; // tslint:disable-line:unified-signatures + focusEditor(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + getAutoFilterEditor(column: BootstrapGridViewColumn): any; + getAutoFilterEditor(columnIndex: number): any; // tslint:disable-line:unified-signatures + getAutoFilterEditor(columnFieldNameOrId: string): any; // tslint:disable-line:unified-signatures unified-signatures + getColumn(columnIndex: number): BootstrapGridViewColumn | null; + getColumnByField(columnFieldName: string): BootstrapGridViewColumn | null; + getColumnById(columnId: string): BootstrapGridViewColumn | null; + getColumnCount(): number; + getColumnLayout(): any; + getEditValue(column: BootstrapGridViewColumn): string; + getEditValue(columnIndex: number): string; // tslint:disable-line:unified-signatures + getEditValue(columnFieldNameOrId: string): string; // tslint:disable-line:unified-signatures unified-signatures + getEditor(column: BootstrapGridViewColumn): BootstrapClientEdit; + getEditor(columnIndex: number): BootstrapClientEdit; // tslint:disable-line:unified-signatures + getEditor(columnFieldNameOrId: string): BootstrapClientEdit; // tslint:disable-line:unified-signatures unified-signatures + getFocusedCell(): BootstrapGridViewCellInfo | null; + getFocusedRowIndex(): number; + getHorizontalScrollPosition(): number; + getPageCount(): number; + getPageIndex(): number; + getPopupEditForm(): BootstrapPopupControl | null; + getRowIndicesVisibleInViewPort(includePartiallyVisible: boolean): number[]; + getRowKey(visibleIndex: number): string; + getSelectedKeysOnPage(): any[]; + getSelectedRowCount(): number; + getTopVisibleIndex(): number; + getVerticalScrollPosition(): number; + getVisibleRowsOnPage(): number; + gotoPage(pageIndex: number): void; + groupBy(column: BootstrapGridViewColumn): void; + groupBy(columnIndex: number): void; // tslint:disable-line:unified-signatures + groupBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + groupBy(column: BootstrapGridViewColumn, groupIndex: number): void; // tslint:disable-line:unified-signatures + groupBy(columnIndex: number, groupIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures + groupBy(columnFieldNameOrId: string, groupIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + groupBy(column: BootstrapGridViewColumn, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures + groupBy(columnIndex: number, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures + groupBy(columnFieldNameOrId: string, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + hideCustomizationWindow(): void; + isCustomizationWindowVisible(): boolean; + isDataRow(visibleIndex: number): boolean; + isEditing(): boolean; + isGroupRow(visibleIndex: number): boolean; + isGroupRowExpanded(visibleIndex: number): boolean; + isNewRowEditing(): boolean; + isRowSelectedOnPage(visibleIndex: number): boolean; + makeRowVisible(visibleIndex: number): void; + nextPage(): void; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + prevPage(): void; + refresh(): void; + selectAllRowsOnPage(): void; + selectRowOnPage(visibleIndex: number): void; + selectRowOnPage(visibleIndex: number, selected: boolean): void; // tslint:disable-line:unified-signatures + selectRows(): void; + selectRowsByKey(keys: any[]): void; + selectRowsByKey(key: any): void; // tslint:disable-line:unified-signatures + selectRowsByKey(keys: any[], selected: boolean): void; // tslint:disable-line:unified-signatures + selectRowsByKey(key: any, selected: boolean): void; // tslint:disable-line:unified-signatures unified-signatures + setColumnLayout(columnLayout: any): void; + setEditValue(column: BootstrapGridViewColumn, value: string): void; + setEditValue(columnIndex: number, value: string): void; // tslint:disable-line:unified-signatures + setEditValue(columnFieldNameOrId: string, value: string): void; // tslint:disable-line:unified-signatures unified-signatures + setFilterEnabled(isFilterEnabled: boolean): void; + setFixedColumnScrollableRows(scrollableRowSettings: any): void; + setFocusedCell(rowVisibleIndex: number, columnIndex: number): void; + setFocusedRowIndex(visibleIndex: number): void; + setHorizontalScrollPosition(position: number): void; + setSearchPanelCustomEditor(editor: BootstrapClientEdit): void; + setVerticalScrollPosition(position: number): void; + showCustomizationDialog(): void; + showCustomizationWindow(): void; + showFilterControl(): void; + sortBy(column: BootstrapGridViewColumn): void; + sortBy(columnIndex: number): void; // tslint:disable-line:unified-signatures + sortBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(column: BootstrapGridViewColumn, sortOrder: string): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + sortBy(column: BootstrapGridViewColumn, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + sortBy(column: BootstrapGridViewColumn, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures + sortBy(columnIndex: number, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures + sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures + startEditRow(visibleIndex: number): void; + startEditRowByKey(key: any): void; + ungroup(column: BootstrapGridViewColumn): void; + ungroup(columnIndex: number): void; // tslint:disable-line:unified-signatures + ungroup(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures + unselectAllRowsOnPage(): void; + unselectFilteredRows(): void; + unselectRowOnPage(visibleIndex: number): void; + unselectRows(): void; + unselectRowsByKey(keys: any[]): void; + unselectRowsByKey(key: any): void; // tslint:disable-line:unified-signatures + updateEdit(): void; + on(eventName: K, callback: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; + } + interface BootstrapGridViewEventMap extends BootstrapGridBaseEventMap { + "batchEditChangesCanceling": GridViewBatchEditChangesCancelingEventArgs; + "batchEditChangesSaving": GridViewBatchEditChangesSavingEventArgs; + "batchEditConfirmShowing": GridViewBatchEditConfirmShowingEventArgs; + "batchEditEndEditing": GridViewBatchEditEndEditingEventArgs; + "batchEditRowDeleting": GridViewBatchEditRowDeletingEventArgs; + "batchEditRowInserting": GridViewBatchEditRowInsertingEventArgs; + "batchEditRowValidating": GridViewBatchEditRowValidatingEventArgs; + "batchEditStartEditing": GridViewBatchEditStartEditingEventArgs; + "batchEditTemplateCellFocused": GridViewBatchEditTemplateCellFocusedEventArgs; + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "columnGrouping": GridViewColumnCancelEventArgs; + "columnMoving": GridViewColumnMovingEventArgs; + "columnResized": GridViewColumnProcessingModeEventArgs; + "columnResizing": GridViewColumnCancelEventArgs; + "columnSorting": GridViewColumnCancelEventArgs; + "columnStartDragging": GridViewColumnCancelEventArgs; + "contextMenu": GridViewContextMenuEventArgs; + "contextMenuItemClick": GridViewContextMenuItemClickEventArgs; + "customButtonClick": GridViewCustomButtonEventArgs; + "customizationWindowCloseUp": EventArgs; + "detailRowCollapsing": GridViewRowCancelEventArgs; + "detailRowExpanding": GridViewRowCancelEventArgs; + "endCallback": EndCallbackEventArgs; + "focusedCellChanging": GridViewFocusedCellChangingEventArgs; + "focusedRowChanged": GridViewFocusEventArgs; + "rowClick": GridViewRowClickEventArgs; + "rowCollapsing": GridViewRowCancelEventArgs; + "rowDblClick": GridViewRowClickEventArgs; + "rowExpanding": GridViewRowCancelEventArgs; + "rowFocusing": GridViewRowFocusingEventArgs; + "selectionChanged": GridViewSelectionEventArgs; + } + + class BootstrapGridViewBatchEditApi { + protected readonly instance: any; + protected constructor(instance: any); + addNewRow(): void; + deleteRow(visibleIndex: number): void; + deleteRowByKey(key: any): void; + endEdit(): void; + getCellTextContainer(visibleIndex: number, columnFieldNameOrId: string): any; + getCellValue(visibleIndex: number, columnFieldNameOrId: string, initial: boolean): any; + getColumnDisplayText(columnFieldNameOrId: string, value: any): string; + getDeletedRowIndices(): number[]; + getEditCellInfo(): BootstrapGridViewCellInfo | null; + getInsertedRowIndices(): number[]; + getRowVisibleIndices(includeDeleted: boolean): number[]; + hasChanges(): boolean; + isDeletedRow(visibleIndex: number): boolean; + isNewRow(visibleIndex: number): boolean; + moveFocusBackward(): boolean; + moveFocusForward(): boolean; + recoverRow(visibleIndex: number): void; + recoverRowByKey(key: any): void; + resetChanges(visibleIndex: number): void; + resetChanges(visibleIndex: number, columnIndex: number): void; // tslint:disable-line:unified-signatures + setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any): void; + setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any, displayText: string, cancelCellHighlighting: boolean): void; + startEdit(visibleIndex: number, columnIndex: number): void; + validateRow(visibleIndex: number): boolean; + validateRows(validateOnlyModified: boolean): boolean; + } + + class BootstrapGridViewColumn { + protected readonly instance: any; + protected constructor(instance: any); + readonly fieldName: string; + readonly index: number; + readonly name: string; + readonly visible: boolean; + } + + class BootstrapGridViewCellInfo { + protected readonly instance: any; + protected constructor(instance: any); + readonly rowVisibleIndex: number; + } + + class BootstrapHyperLink extends Control { + getBadgeIconCssClass(): string; + getBadgeText(): string; + getCaption(): string; + getEnabled(): boolean; + getNavigateUrl(): string; + getText(): string; + getValue(): any; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setCaption(caption: string): void; + setEnabled(value: boolean): void; + setNavigateUrl(url: string): void; + setText(text: string): void; + setValue(value: any): void; + on(eventName: K, callback: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; + } + interface BootstrapHyperLinkEventMap extends ControlEventMap { + "click": EditClickEventArgs; + } + + interface ListEditItemSelectedChangedEventArgs extends ProcessingModeEventArgs { + readonly index: number; + readonly isSelected: boolean; + } + + interface ListEditCustomHighlightingEventArgs extends EventArgs { + readonly filter: string; + highlighting: any; + } + + interface ListEditItemFilteringEventArgs extends EventArgs { + readonly filter: string; + isFit: boolean; + readonly item: BootstrapListBoxItem; + } + + class BootstrapListBox extends BootstrapClientEdit { + addItem(texts: string[]): number; + addItem(text: string): number; // tslint:disable-line:unified-signatures + addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures + addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures + addItemCssClass(index: number, className: string): void; + addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + beginUpdate(): void; + clearItems(): void; + endUpdate(): void; + findItemByText(text: string): BootstrapListBoxItem | null; + findItemByValue(value: any): BootstrapListBoxItem | null; + getItem(index: number): BootstrapListBoxItem | null; + getItemBadgeIconCssClass(index: number): string; + getItemBadgeText(index: number): string; + getItemCount(): number; + getSelectedIndex(): number; + getSelectedIndices(): number[]; + getSelectedItem(): BootstrapListBoxItem | null; + getSelectedItems(): BootstrapListBoxItem[]; + getSelectedValues(): any[]; + insertItem(index: number, texts: string[]): void; + insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures + insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures + makeItemVisible(index: number): void; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + removeItem(index: number): void; + removeItemCssClass(index: number, className: string): void; + removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + selectAll(): void; + selectIndices(indices: number[]): void; + selectItems(items: BootstrapListBoxItem[]): void; + selectValues(values: any[]): void; + setItemBadgeIconCssClass(index: number, cssClass: string): void; + setItemBadgeText(index: number, text: string): void; + setItemHtml(index: number, html: string): void; + setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; + setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; + setItemTooltip(index: number, tooltip: string): void; + setSelectedIndex(index: number): void; + setSelectedItem(item: BootstrapListBoxItem): void; + unselectAll(): void; + unselectIndices(indices: number[]): void; + unselectItems(items: BootstrapListBoxItem[]): void; + unselectValues(values: any[]): void; + on(eventName: K, callback: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; + } + interface BootstrapListBoxEventMap extends BootstrapClientEditEventMap { + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "customHighlighting": ListEditCustomHighlightingEventArgs; + "endCallback": EndCallbackEventArgs; + "itemDoubleClick": EventArgs; + "itemFiltering": ListEditItemFilteringEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "selectedIndexChanged": ProcessingModeEventArgs; + } + + class BootstrapListBoxItem { + protected readonly instance: any; + protected constructor(instance: any); + readonly iconCssClass: string; + readonly imageUrl: string; + readonly index: number; + readonly listEditBase: BootstrapListBox | null; + readonly text: string; + readonly value: any; + getColumnText(columnIndex: number): string; + getColumnText(columnName: string): string; // tslint:disable-line:unified-signatures + getFieldText(fieldIndex: number): string; + getFieldText(fieldName: string): string; // tslint:disable-line:unified-signatures + } + + class BootstrapCheckBoxList extends BootstrapListBox { + getItem(index: number): BootstrapListBoxItem | null; + getItemCount(): number; + getSelectedIndices(): number[]; + getSelectedItems(): BootstrapListBoxItem[]; + getSelectedValues(): any[]; + selectAll(): void; + selectIndices(indices: number[]): void; + selectItems(items: BootstrapListBoxItem[]): void; + selectValues(values: any[]): void; + unselectAll(): void; + unselectIndices(indices: number[]): void; + unselectItems(items: BootstrapListBoxItem[]): void; + unselectValues(values: any[]): void; + on(eventName: K, callback: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; + } + interface BootstrapCheckBoxListEventMap extends BootstrapListBoxEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapRadioButtonList extends BootstrapListBox { + getItem(index: number): BootstrapListBoxItem | null; + getItemCount(): number; + on(eventName: K, callback: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; + } + interface BootstrapRadioButtonListEventMap extends BootstrapListBoxEventMap { // tslint:disable-line:no-empty-interface + } + + interface MenuItemEventArgs extends EventArgs { + readonly item: BootstrapMenuItem; + } + + interface MenuItemMouseEventArgs extends MenuItemEventArgs { // tslint:disable-line:no-empty-interface + } + + interface MenuItemClickEventArgs extends ProcessingModeEventArgs { + readonly htmlElement: object; + readonly htmlEvent: object; + readonly item: BootstrapMenuItem; + } + + class BootstrapMenu extends Control { + getItem(index: number): BootstrapMenuItem | null; + getItemByName(name: string): BootstrapMenuItem | null; + getItemCount(): number; + getOrientation(): string; + getRootItem(): BootstrapMenuItem | null; + getSelectedItem(): BootstrapMenuItem | null; + setOrientation(orientation: string): void; + setSelectedItem(item: BootstrapMenuItem): void; + on(eventName: K, callback: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; + } + interface BootstrapMenuEventMap extends ControlEventMap { + "closeUp": MenuItemEventArgs; + "itemClick": MenuItemClickEventArgs; + "itemMouseOut": MenuItemMouseEventArgs; + "itemMouseOver": MenuItemMouseEventArgs; + "popUp": MenuItemEventArgs; + } + + class BootstrapMenuItem { + protected readonly instance: any; + protected constructor(instance: any); + readonly index: number; + readonly indexPath: string; + readonly menu: BootstrapMenu | null; + readonly name: string; + readonly parent: BootstrapMenuItem | null; + getBadgeIconCssClass(): string; + getBadgeText(): string; + getChecked(): boolean; + getEnabled(): boolean; + getIconCssClass(): string; + getImageUrl(): string; + getItem(index: number): BootstrapMenuItem | null; + getItemByName(name: string): BootstrapMenuItem | null; + getItemCount(): number; + getNavigateUrl(): string; + getText(): string; + getVisible(): boolean; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setChecked(value: boolean): void; + setEnabled(value: boolean): void; + setIconCssClass(cssClass: string): void; + setImageUrl(value: string): void; + setNavigateUrl(value: string): void; + setText(value: string): void; + setVisible(value: boolean): void; + } + + interface PopupWindowEventArgs extends EventArgs { + readonly window: BootstrapPopupWindow; + } + + interface PopupWindowCloseUpEventArgs extends PopupWindowEventArgs { + readonly closeReason: BootstrapPopupControlCloseReason; + } + + interface PopupWindowCancelEventArgs extends CancelEventArgs { + readonly closeReason: BootstrapPopupControlCloseReason; + readonly window: BootstrapPopupWindow; + } + + interface PopupWindowPinnedChangedEventArgs extends PopupWindowEventArgs { + readonly pinned: boolean; + } + + interface PopupWindowResizeEventArgs extends PopupWindowEventArgs { + readonly resizeState: number; + } + + class BootstrapPopupControl extends Control { + adjustSize(): void; + bringToFront(): void; + bringWindowToFront(window: BootstrapPopupWindow): void; + getCollapsed(): boolean; + getContentHeight(): number; + getContentHtml(): string; + getContentIFrame(): any; + getContentIFrameWindow(): any; + getContentUrl(): string; + getContentWidth(): number; + getCurrentPopupElement(): any; + getCurrentPopupElementIndex(): number; + getFooterImageUrl(): string; + getFooterNavigateUrl(): string; + getFooterText(): string; + getHeaderImageUrl(): string; + getHeaderNavigateUrl(): string; + getHeaderText(): string; + getMainElement(): any; + getMaximized(): boolean; + getPinned(): boolean; + getPopUpReasonMouseEvent(): any; + getWindow(index: number): BootstrapPopupWindow | null; + getWindowByName(name: string): BootstrapPopupWindow | null; + getWindowCollapsed(window: BootstrapPopupWindow): boolean; + getWindowContentHeight(window: BootstrapPopupWindow): number; + getWindowContentHtml(window: BootstrapPopupWindow): string; + getWindowContentIFrame(window: BootstrapPopupWindow): any; + getWindowContentUrl(window: BootstrapPopupWindow): string; + getWindowContentWidth(window: BootstrapPopupWindow): number; + getWindowCount(): number; + getWindowCurrentPopupElement(window: BootstrapPopupWindow): any; + getWindowCurrentPopupElementIndex(window: BootstrapPopupWindow): number; + getWindowHeight(window: BootstrapPopupWindow): number; + getWindowMaximized(window: BootstrapPopupWindow): boolean; + getWindowPinned(window: BootstrapPopupWindow): boolean; + getWindowPopUpReasonMouseEvent(window: BootstrapPopupWindow): any; + getWindowWidth(window: BootstrapPopupWindow): number; + hide(): void; + hideWindow(window: BootstrapPopupWindow): void; + isVisible(): boolean; + isWindowVisible(window: BootstrapPopupWindow): boolean; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + refreshContentUrl(): void; + refreshPopupElementConnection(): void; + refreshWindowContentUrl(window: BootstrapPopupWindow): void; + setAdaptiveMaxHeight(maxHeight: number): void; + setAdaptiveMaxHeight(maxHeight: string): void; // tslint:disable-line:unified-signatures + setAdaptiveMaxWidth(maxWidth: number): void; + setAdaptiveMaxWidth(maxWidth: string): void; // tslint:disable-line:unified-signatures + setAdaptiveMinHeight(minHeight: number): void; + setAdaptiveMinHeight(minHeight: string): void; // tslint:disable-line:unified-signatures + setAdaptiveMinWidth(minWidth: number): void; + setAdaptiveMinWidth(minWidth: string): void; // tslint:disable-line:unified-signatures + setCollapsed(value: boolean): void; + setContentHtml(html: string): void; + setContentUrl(url: string): void; + setFooterImageUrl(value: string): void; + setFooterNavigateUrl(value: string): void; + setFooterText(value: string): void; + setHeaderImageUrl(value: string): void; + setHeaderNavigateUrl(value: string): void; + setHeaderText(value: string): void; + setMaximized(value: boolean): void; + setPinned(value: boolean): void; + setPopupElementCssSelector(selector: string): void; + setPopupElementID(popupElementId: string): void; + setSize(width: number, height: number): void; + setWindowAdaptiveMaxHeight(window: BootstrapPopupWindow, maxHeight: number): void; + setWindowAdaptiveMaxHeight(window: BootstrapPopupWindow, maxHeight: string): void; // tslint:disable-line:unified-signatures + setWindowAdaptiveMaxWidth(window: BootstrapPopupWindow, maxWidth: number): void; + setWindowAdaptiveMaxWidth(window: BootstrapPopupWindow, maxWidth: string): void; // tslint:disable-line:unified-signatures + setWindowAdaptiveMinHeight(window: BootstrapPopupWindow, minHeight: number): void; + setWindowAdaptiveMinHeight(window: BootstrapPopupWindow, minHeight: string): void; // tslint:disable-line:unified-signatures + setWindowAdaptiveMinWidth(window: BootstrapPopupWindow, minWidth: number): void; + setWindowAdaptiveMinWidth(window: BootstrapPopupWindow, minWidth: string): void; // tslint:disable-line:unified-signatures + setWindowCollapsed(window: BootstrapPopupWindow, value: boolean): void; + setWindowContentHtml(window: BootstrapPopupWindow, html: string): void; + setWindowContentUrl(window: BootstrapPopupWindow, url: string): void; + setWindowMaximized(window: BootstrapPopupWindow, value: boolean): void; + setWindowPinned(window: BootstrapPopupWindow, value: boolean): void; + setWindowPopupElementID(window: BootstrapPopupWindow, popupElementId: string): void; + setWindowSize(window: BootstrapPopupWindow, width: number, height: number): void; + show(): void; + showAtElement(htmlElement: any): void; + showAtElementByID(id: string): void; + showAtPos(x: number, y: number): void; + showWindow(window: BootstrapPopupWindow): void; + showWindow(window: BootstrapPopupWindow, popupElementIndex: number): void; // tslint:disable-line:unified-signatures + showWindowAtElement(window: BootstrapPopupWindow, htmlElement: any): void; + showWindowAtElementByID(window: BootstrapPopupWindow, id: string): void; + showWindowAtPos(window: BootstrapPopupWindow, x: number, y: number): void; + stretchVertically(): void; + updatePosition(): void; + updatePositionAtElement(htmlElement: any): void; + updateWindowPosition(window: BootstrapPopupWindow): void; + updateWindowPositionAtElement(window: BootstrapPopupWindow, htmlElement: any): void; + windowStretchVertically(window: BootstrapPopupWindow): void; + on(eventName: K, callback: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; + } + interface BootstrapPopupControlEventMap extends ControlEventMap { + "afterResizing": PopupWindowEventArgs; + "beforeResizing": PopupWindowEventArgs; + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "closeUp": PopupWindowCloseUpEventArgs; + "closing": PopupWindowCancelEventArgs; + "endCallback": EndCallbackEventArgs; + "pinnedChanged": PopupWindowPinnedChangedEventArgs; + "popUp": PopupWindowEventArgs; + "resize": PopupWindowResizeEventArgs; + "shown": PopupWindowEventArgs; + } + + class BootstrapPopupWindow { + protected readonly instance: any; + protected constructor(instance: any); + readonly index: number; + readonly name: string; + readonly popupControl: BootstrapPopupControl | null; + getFooterImageUrl(): string; + getFooterNavigateUrl(): string; + getFooterText(): string; + getHeaderImageUrl(): string; + getHeaderNavigateUrl(): string; + getHeaderText(): string; + setFooterImageUrl(value: string): void; + setFooterNavigateUrl(value: string): void; + setFooterText(value: string): void; + setHeaderImageUrl(value: string): void; + setHeaderNavigateUrl(value: string): void; + setHeaderText(value: string): void; + } + + class BootstrapPopupMenu extends BootstrapMenu { + getCurrentPopupElement(): any; + getCurrentPopupElementIndex(): number; + getItem(index: number): BootstrapMenuItem | null; + getItemByName(name: string): BootstrapMenuItem | null; + getRootItem(): BootstrapMenuItem | null; + getSelectedItem(): BootstrapMenuItem | null; + hide(): void; + refreshPopupElementConnection(): void; + setPopupElementCssSelector(selector: string): void; + setPopupElementID(popupElementId: string): void; + setSelectedItem(item: BootstrapMenuItem): void; + show(): void; + showAtElement(htmlElement: any): void; + showAtElementByID(id: string): void; + showAtPos(x: number, y: number): void; + on(eventName: K, callback: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; + } + interface BootstrapPopupMenuEventMap extends BootstrapMenuEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapProgressBar extends Control { + getCaption(): string; + getDisplayText(): string; + getEnabled(): boolean; + getMaximum(): number; + getMinimum(): number; + getPercent(): number; + getPosition(): number; + getValue(): any; + setCaption(caption: string): void; + setCustomDisplayFormat(text: string): void; + setEnabled(value: boolean): void; + setMaximum(max: number): void; + setMinMaxValues(minValue: number, maxValue: number): void; + setMinimum(min: number): void; + setPosition(position: number): void; + setValue(value: any): void; + on(eventName: K, callback: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; + } + interface BootstrapProgressBarEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } + + interface ActiveViewChangingEventArgs extends EventArgs { + cancel: boolean; + readonly newView: BootstrapSchedulerViewType; + readonly oldView: BootstrapSchedulerViewType; + } + + interface AppointmentClickEventArgs extends EventArgs { + readonly appointmentId: string; + readonly handled: boolean; + readonly htmlElement: object; + } + + interface AppointmentDeletingEventArgs extends CancelEventArgs { + readonly appointmentIds: object[]; + } + + interface AppointmentDragEventArgs extends EventArgs { + allow: boolean; + readonly dragInformation: BootstrapSchedulerAppointmentDragInfo[]; + readonly mouseEvent: any; + } + + interface AppointmentDropEventArgs extends EventArgs { + readonly dragInformation: BootstrapSchedulerAppointmentDragInfo[]; + handled: boolean; + readonly operation: BootstrapSchedulerAppointmentOperation; + } + + interface AppointmentResizeEventArgs extends EventArgs { + readonly appointmentId: string; + handled: boolean; + readonly newInterval: BootstrapTimeInterval; + readonly oldInterval: BootstrapTimeInterval; + readonly operation: BootstrapSchedulerAppointmentOperation; + } + + interface AppointmentResizingEventArgs extends EventArgs { + allow: boolean; + readonly appointmentId: string; + readonly mouseEvent: any; + readonly newInterval: BootstrapTimeInterval; + readonly oldInterval: BootstrapTimeInterval; + } + + interface AppointmentToolTipShowingEventArgs extends CancelEventArgs { + readonly appointment: BootstrapSchedulerAppointment; + } + + interface AppointmentsSelectionEventArgs extends EventArgs { + readonly appointmentIds: string[]; + } + + interface CellClickEventArgs extends EventArgs { + readonly htmlElement: object; + readonly interval: BootstrapTimeInterval; + readonly resource: string; + } + + interface MenuItemClickedEventArgs extends EventArgs { + handled: boolean; + readonly itemName: string; + } + + interface MoreButtonClickedEventArgs extends ProcessingModeEventArgs { + handled: boolean; + readonly interval: BootstrapTimeInterval; + readonly resource: string; + readonly targetDateTime: Date; + } + + interface ShortcutEventArgs extends EventArgs { + readonly commandName: string; + readonly handled: boolean; + readonly htmlEvent: object; + } + + class BootstrapScheduler extends Control { + appointmentFormCancel(): void; + appointmentFormDelete(): void; + appointmentFormSave(): void; + changeFormContainer(container: any): void; + changePopupMenuContainer(container: any): void; + changeTimeZoneId(timeZoneId: string): void; + changeToolTipContainer(container: any): void; + deleteAppointment(apt: BootstrapSchedulerAppointment): void; + deselectAppointmentById(aptId: any): void; + getActiveViewType(): BootstrapSchedulerViewType; + getAllDayAreaHeight(): number; + getAppointmentById(id: any): BootstrapSchedulerAppointment | null; + getAppointmentProperties(aptId: number, propertyNames: string[], onCallBack: any): string[]; + getGroupType(): BootstrapSchedulerGroupType; + getResourceNavigatorVisible(): boolean; + getScrollAreaHeight(): number; + getSelectedAppointmentIds(): string[]; + getSelectedInterval(): BootstrapTimeInterval | null; + getSelectedResource(): string; + getToolbarVisible(): boolean; + getTopRowTime(viewType: BootstrapSchedulerViewType): number; + getVisibleAppointments(): BootstrapSchedulerAppointment[]; + getVisibleIntervals(): BootstrapTimeInterval[]; + goToDateFormApply(): void; + goToDateFormCancel(): void; + gotoDate(date: Date): void; + gotoToday(): void; + hideLoadingPanel(): void; + inplaceEditFormCancel(): void; + inplaceEditFormSave(): void; + inplaceEditFormShowMore(): void; + insertAppointment(apt: BootstrapSchedulerAppointment): void; + navigateBackward(): void; + navigateForward(): void; + performCallback(parameter: string): void; + refresh(): void; + refreshClientAppointmentProperties(clientAppointment: BootstrapSchedulerAppointment, propertyNames: string[], onCallBack: any): void; + reminderFormCancel(): void; + reminderFormDismiss(): void; + reminderFormDismissAll(): void; + reminderFormSnooze(): void; + selectAppointmentById(aptId: any): void; + selectAppointmentById(aptId: any, scrollToSelection: boolean): void; // tslint:disable-line:unified-signatures + setActiveViewType(value: BootstrapSchedulerViewType): void; + setAllDayAreaHeight(height: number): void; + setGroupType(value: BootstrapSchedulerGroupType): void; + setHeight(height: number): void; + setResourceNavigatorVisible(visible: boolean): void; + setSelection(interval: BootstrapTimeInterval): void; + setSelection(interval: BootstrapTimeInterval, resourceId: string): void; // tslint:disable-line:unified-signatures + setSelection(interval: BootstrapTimeInterval, resourceId: string, scrollToSelection: boolean): void; // tslint:disable-line:unified-signatures + setToolbarVisible(visible: boolean): void; + setTopRowTime(duration: number): void; + setTopRowTime(duration: number, viewType: BootstrapSchedulerViewType): void; // tslint:disable-line:unified-signatures + setVisibleResources(resourceIds: string[]): void; + showAppointmentFormByClientId(aptClientId: string): void; + showAppointmentFormByServerId(aptServerId: string): void; + showInplaceEditor(start: Date, end: Date): void; + showInplaceEditor(start: Date, end: Date, resourceId: string): void; // tslint:disable-line:unified-signatures + showLoadingPanel(): void; + showSelectionToolTip(x: number, y: number): void; + updateAppointment(apt: BootstrapSchedulerAppointment): void; + on(eventName: K, callback: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; + } + interface BootstrapSchedulerEventMap extends ControlEventMap { + "activeViewChanged": EventArgs; + "activeViewChanging": ActiveViewChangingEventArgs; + "appointmentClick": AppointmentClickEventArgs; + "appointmentDeleting": AppointmentDeletingEventArgs; + "appointmentDoubleClick": AppointmentClickEventArgs; + "appointmentDrag": AppointmentDragEventArgs; + "appointmentDrop": AppointmentDropEventArgs; + "appointmentResize": AppointmentResizeEventArgs; + "appointmentResizing": AppointmentResizingEventArgs; + "appointmentToolTipShowing": AppointmentToolTipShowingEventArgs; + "appointmentsSelectionChanged": AppointmentsSelectionEventArgs; + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "cellClick": CellClickEventArgs; + "cellDoubleClick": CellClickEventArgs; + "endCallback": EndCallbackEventArgs; + "menuItemClicked": MenuItemClickedEventArgs; + "moreButtonClicked": MoreButtonClickedEventArgs; + "selectionChanged": EventArgs; + "selectionChanging": EventArgs; + "shortcut": ShortcutEventArgs; + "visibleIntervalChanged": EventArgs; + } + + class BootstrapTimeInterval { + protected readonly instance: any; + protected constructor(instance: any); + contains(interval: BootstrapTimeInterval): boolean; + equals(interval: BootstrapTimeInterval): boolean; + getAllDay(): boolean; + getDuration(): number; + getEnd(): Date; + getStart(): Date; + intersectsWith(interval: BootstrapTimeInterval): boolean; + intersectsWithExcludingBounds(interval: BootstrapTimeInterval): boolean; + setAllDay(allDayValue: boolean): void; + setDuration(value: number): void; + setEnd(value: Date): void; + setStart(value: Date): void; + } + + class BootstrapSchedulerAppointment { + protected readonly instance: any; + protected constructor(instance: any); + readonly appointmentId: string; + readonly appointmentType: BootstrapSchedulerAppointmentType; + readonly interval: BootstrapTimeInterval | null; + readonly labelIndex: number; + readonly resources: string[]; + readonly statusIndex: number; + addResource(resourceId: object): void; + getAllDay(): boolean; + getAppointmentType(): BootstrapSchedulerAppointmentType; + getDescription(): string; + getDuration(): number; + getEnd(): Date; + getId(): any; + getLabelId(): number; + getLocation(): string; + getRecurrenceInfo(): BootstrapSchedulerRecurrenceInfo | null; + getRecurrencePattern(): BootstrapSchedulerAppointment | null; + getResource(index: number): any; + getStart(): Date; + getStatusId(): number; + getSubject(): string; + setAllDay(allDay: boolean): void; + setAppointmentType(type: BootstrapSchedulerAppointmentType): void; + setDescription(description: string): void; + setDuration(duration: number): void; + setEnd(end: Date): void; + setId(id: any): void; + setLabelId(statusId: number): void; + setLocation(location: string): void; + setRecurrenceInfo(recurrenceInfo: BootstrapSchedulerRecurrenceInfo): void; + setStart(start: Date): void; + setStatusId(statusId: number): void; + setSubject(subject: string): void; + } + + class BootstrapSchedulerAppointmentDragInfo { + protected readonly instance: any; + protected constructor(instance: any); + readonly appointmentId: string; + readonly newInterval: BootstrapTimeInterval | null; + readonly oldInterval: BootstrapTimeInterval | null; + } + + class BootstrapSchedulerAppointmentOperation { + protected readonly instance: any; + protected constructor(instance: any); + apply(): void; + cancel(): void; + } + + class BootstrapSchedulerRecurrenceInfo { + protected readonly instance: any; + protected constructor(instance: any); + getDayNumber(): number; + getDuration(): number; + getEnd(): Date; + getMonth(): number; + getOccurrenceCount(): number; + getPeriodicity(): number; + getRange(): BootstrapSchedulerRecurrenceRange; + getRecurrenceType(): BootstrapSchedulerRecurrenceType; + getStart(): Date; + getWeekDays(): WeekDays; + getWeekOfMonth(): WeekOfMonth; + setDayNumber(dayNumber: number): void; + setDuration(duration: number): void; + setEnd(end: Date): void; + setMonth(month: number): void; + setOccurrenceCount(occurrenceCount: number): void; + setPeriodicity(periodicity: number): void; + setRange(range: BootstrapSchedulerRecurrenceRange): void; + setRecurrenceType(type: BootstrapSchedulerRecurrenceType): void; + setStart(start: Date): void; + setWeekDays(weekDays: WeekDays): void; + setWeekOfMonth(weekOfMonth: WeekOfMonth): void; + } + + class BootstrapSparkline extends Control { + exportTo(fileName: string, format: string): void; + getDataSource(): any; + getInstance(): any; + print(): void; + setDataSource(dataSource: any): void; + setOptions(options: any): void; + on(eventName: K, callback: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; + } + interface BootstrapSparklineEventMap extends ControlEventMap { + "disposing": BootstrapChartEventArgsBase; + "drawn": BootstrapChartEventArgsBase; + "exported": BootstrapChartEventArgsBase; + "exporting": BootstrapChartExportEventArgs; + "fileSaving": BootstrapChartExportEventArgs; + "incidentOccurred": BootstrapChartErrorEventArgs; + "init": BootstrapChartEventArgsBase; + "optionChanged": BootstrapChartOptionChangedEventArgs; + "tooltipHidden": BootstrapChartEventArgsBase; + "tooltipShown": BootstrapChartEventArgsBase; + } + + class BootstrapTimeEdit extends BootstrapClientEdit { + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getDate(): Date; + getText(): string; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setDate(date: Date): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; + } + interface BootstrapTimeEditEventMap extends BootstrapClientEditEventMap { + "buttonClick": ButtonEditClickEventArgs; + "dateChanged": ProcessingModeEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapSpinEdit extends BootstrapClientEdit { + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getMaxValue(): number; + getMinValue(): number; + getNumber(): number; + getText(): string; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setMaxValue(value: number): void; + setMinValue(value: number): void; + setNumber(number: number): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + setValue(number: number): void; + on(eventName: K, callback: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; + } + interface BootstrapSpinEditEventMap extends BootstrapClientEditEventMap { + "buttonClick": ButtonEditClickEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "numberChanged": ProcessingModeEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + interface TabControlTabEventArgs extends EventArgs { + readonly tab: BootstrapTab; + } + + interface TabControlTabCancelEventArgs extends ProcessingModeCancelEventArgs { + reloadContentOnCallback: boolean; + readonly tab: BootstrapTab; + } + + interface TabControlTabClickEventArgs extends TabControlTabCancelEventArgs { + readonly htmlElement: object; + readonly htmlEvent: object; + } + + class BootstrapTabControl extends Control { + adjustSize(): void; + getActiveTab(): BootstrapTab | null; + getActiveTabIndex(): number; + getTab(index: number): BootstrapTab | null; + getTabByName(name: string): BootstrapTab | null; + getTabCount(): number; + setActiveTab(tab: BootstrapTab): void; + setActiveTabIndex(index: number): void; + on(eventName: K, callback: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; + } + interface BootstrapTabControlEventMap extends ControlEventMap { + "activeTabChanged": TabControlTabEventArgs; + "activeTabChanging": TabControlTabCancelEventArgs; + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "endCallback": EndCallbackEventArgs; + "tabClick": TabControlTabClickEventArgs; + } + + class BootstrapTab { + protected readonly instance: any; + protected constructor(instance: any); + readonly index: number; + readonly name: string; + readonly tabControl: BootstrapTabControl | null; + getActiveIconCssClass(): string; + getActiveImageUrl(): string; + getBadgeIconCssClass(): string; + getBadgeText(): string; + getEnabled(): boolean; + getIconCssClass(): string; + getImageUrl(): string; + getNavigateUrl(): string; + getText(): string; + getVisible(): boolean; + setActiveIconCssClass(cssClass: string): void; + setActiveImageUrl(value: string): void; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setEnabled(value: boolean): void; + setIconCssClass(cssClass: string): void; + setImageUrl(value: string): void; + setNavigateUrl(value: string): void; + setText(value: string): void; + setVisible(value: boolean): void; + } + + class BootstrapPageControl extends BootstrapTabControl { + getActiveTab(): BootstrapTab | null; + getTab(index: number): BootstrapTab | null; + getTabByName(name: string): BootstrapTab | null; + getTabContentHTML(tab: BootstrapTab): string; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + setActiveTab(tab: BootstrapTab): void; + setTabContentHTML(tab: BootstrapTab, html: string): void; + on(eventName: K, callback: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; + } + interface BootstrapPageControlEventMap extends BootstrapTabControlEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapTagBox extends BootstrapClientEdit { + addItem(texts: string[]): number; + addItem(text: string): number; // tslint:disable-line:unified-signatures + addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures + addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures + addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures + addItemCssClass(index: number, className: string): void; + addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + addTag(text: string): void; + adjustDropDownWindow(): void; + beginUpdate(): void; + clearItems(): void; + clearTagCollection(): void; + endUpdate(): void; + ensureDropDownLoaded(callbackFunction: any): void; + findItemByText(text: string): BootstrapListBoxItem | null; + findItemByValue(value: any): BootstrapListBoxItem | null; + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getItem(index: number): BootstrapListBoxItem | null; + getItemBadgeIconCssClass(index: number): string; + getItemBadgeText(index: number): string; + getItemCount(): number; + getSelectedIndex(): number; + getSelectedItem(): BootstrapListBoxItem | null; + getTagCollection(): string[]; + getTagHtmlElement(index: number): any; + getTagIndexByText(text: string): number; + getTagRemoveButtonHtmlElement(index: number): any; + getTagTextHtmlElement(index: number): any; + getText(): string; + getValue(): string; + hideDropDown(): void; + insertItem(index: number, texts: string[]): void; + insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures + insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures + insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures + isCustomTag(text: string, caseSensitive: boolean): boolean; + makeItemVisible(index: number): void; + performCallback(data: any): Promise; + performCallback(data: any, onSuccess: () => void): void; + removeItem(index: number): void; + removeItemCssClass(index: number, className: string): void; + removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; + removeTag(index: number): void; + removeTagByText(text: string): void; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setItemBadgeIconCssClass(index: number, cssClass: string): void; + setItemBadgeText(index: number, text: string): void; + setItemHtml(index: number, html: string): void; + setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; + setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; + setItemTooltip(index: number, tooltip: string): void; + setSelectedIndex(index: number): void; + setSelectedItem(item: BootstrapListBoxItem): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setTagCollection(collection: string[]): void; + setText(text: string): void; + setValue(value: string): void; + showDropDown(): void; + on(eventName: K, callback: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; + } + interface BootstrapTagBoxEventMap extends BootstrapClientEditEventMap { + "beginCallback": BeginCallbackEventArgs; + "buttonClick": ButtonEditClickEventArgs; + "callbackError": CallbackErrorEventArgs; + "closeUp": EventArgs; + "customHighlighting": ListEditCustomHighlightingEventArgs; + "dropDown": EventArgs; + "endCallback": EndCallbackEventArgs; + "itemFiltering": ListEditItemFilteringEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "queryCloseUp": CancelEventArgs; + "selectedIndexChanged": ProcessingModeEventArgs; + "tagsChanged": EventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + interface ButtonEditClickEventArgs extends ProcessingModeEventArgs { + readonly buttonIndex: number; + } + + class BootstrapButtonEdit extends BootstrapClientEdit { + getButtonVisible(number: number): boolean; + getCaretPosition(): number; + getText(): string; + selectAll(): void; + setButtonVisible(number: number, value: boolean): void; + setCaretPosition(position: number): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; + } + interface BootstrapButtonEditEventMap extends BootstrapClientEditEventMap { + "buttonClick": ButtonEditClickEventArgs; + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapMemo extends BootstrapClientEdit { + getCaretPosition(): number; + getText(): string; + selectAll(): void; + setCaretPosition(position: number): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; + } + interface BootstrapMemoEventMap extends BootstrapClientEditEventMap { + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapTextBox extends BootstrapClientEdit { + getCaretPosition(): number; + getText(): string; + selectAll(): void; + setCaretPosition(position: number): void; + setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; + setText(text: string): void; + on(eventName: K, callback: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; + } + interface BootstrapTextBoxEventMap extends BootstrapClientEditEventMap { + "keyDown": EditKeyEventArgs; + "keyPress": EditKeyEventArgs; + "keyUp": EditKeyEventArgs; + "textChanged": ProcessingModeEventArgs; + "userInput": EventArgs; + } + + class BootstrapToolbar extends BootstrapMenu { + on(eventName: K, callback: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; + } + interface BootstrapToolbarEventMap extends BootstrapMenuEventMap { // tslint:disable-line:no-empty-interface + } + + interface TreeViewNodeProcessingModeEventArgs extends ProcessingModeEventArgs { + readonly node: BootstrapTreeViewNode; + } + + interface TreeViewNodeClickEventArgs extends TreeViewNodeProcessingModeEventArgs { + readonly htmlElement: any; + readonly htmlEvent: any; + } + + interface TreeViewNodeEventArgs extends EventArgs { + readonly node: BootstrapTreeViewNode; + } + + interface TreeViewNodeCancelEventArgs extends ProcessingModeCancelEventArgs { + readonly node: BootstrapTreeViewNode; + } + + class BootstrapTreeView extends Control { + collapseAll(): void; + expandAll(): void; + getNode(index: number): BootstrapTreeViewNode | null; + getNodeByName(name: string): BootstrapTreeViewNode | null; + getNodeByText(text: string): BootstrapTreeViewNode | null; + getNodeCount(): number; + getRootNode(): BootstrapTreeViewNode | null; + getSelectedNode(): BootstrapTreeViewNode | null; + setSelectedNode(node: BootstrapTreeViewNode): void; + on(eventName: K, callback: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; + } + interface BootstrapTreeViewEventMap extends ControlEventMap { + "beginCallback": BeginCallbackEventArgs; + "callbackError": CallbackErrorEventArgs; + "checkedChanged": TreeViewNodeProcessingModeEventArgs; + "endCallback": EndCallbackEventArgs; + "expandedChanged": TreeViewNodeEventArgs; + "expandedChanging": TreeViewNodeCancelEventArgs; + "nodeClick": TreeViewNodeClickEventArgs; + } + + class BootstrapTreeViewNode extends Control { + readonly index: number; + readonly name: string; + readonly parent: BootstrapTreeViewNode | null; + readonly treeView: BootstrapTreeView | null; + getBadgeIconCssClass(): string; + getBadgeText(): string; + getCheckState(): string; + getChecked(): boolean; + getEnabled(): boolean; + getExpanded(): boolean; + getHtmlElement(): any; + getIconCssClass(): string; + getImageUrl(): string; + getNavigateUrl(): string; + getNode(index: number): BootstrapTreeViewNode | null; + getNodeByName(name: string): BootstrapTreeViewNode | null; + getNodeByText(text: string): BootstrapTreeViewNode | null; + getNodeCount(): number; + getText(): string; + getVisible(): boolean; + setBadgeIconCssClass(cssClass: string): void; + setBadgeText(text: string): void; + setChecked(value: boolean): void; + setEnabled(value: boolean): void; + setExpanded(value: boolean): void; + setIconCssClass(cssClass: string): void; + setImageUrl(value: string): void; + setNavigateUrl(value: string): void; + setText(value: string): void; + setVisible(value: boolean): void; + on(eventName: K, callback: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; + } + interface BootstrapTreeViewNodeEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } + + interface UploadControlFilesUploadStartEventArgs extends EventArgs { + readonly cancel: boolean; + } + + interface UploadControlFileUploadCompleteEventArgs extends EventArgs { + readonly callbackData: string; + readonly errorText: string; + readonly inputIndex: number; + readonly isValid: boolean; + } + + interface UploadControlFilesUploadCompleteEventArgs extends EventArgs { + readonly callbackData: string; + readonly errorText: string; + } + + interface UploadControlTextChangedEventArgs extends EventArgs { + readonly inputIndex: number; + } + + interface UploadControlUploadingProgressChangedEventArgs extends EventArgs { + readonly currentFileContentLength: number; + readonly currentFileName: string; + readonly currentFileProgress: number; + readonly currentFileUploadedContentLength: number; + readonly fileCount: number; + readonly progress: number; + readonly totalContentLength: number; + readonly uploadedContentLength: number; + } + + interface UploadControlValidationErrorOccurredEventArgs extends EventArgs { + errorText: string; + readonly invalidFiles: BootstrapUploadControlInvalidFileInfo[]; + showAlert: boolean; + readonly validationSettings: BootstrapUploadControlValidationSettings; + } + + interface UploadControlDropZoneEnterEventArgs extends EventArgs { + readonly dropZone: any; + } + + interface UploadControlDropZoneLeaveEventArgs extends EventArgs { + readonly dropZone: any; + } + + class BootstrapUploadControl extends Control { + addFileInput(): void; + cancel(): void; + clearText(): void; + getAddButtonText(): string; + getEnabled(): boolean; + getFileInputCount(): number; + getSelectedFiles(inputIndex: number): BootstrapUploadControlFile[]; + getText(index: number): string; + getUploadButtonText(): string; + removeFileFromSelection(fileIndex: number): void; + removeFileFromSelection(file: BootstrapUploadControlFile): void; // tslint:disable-line:unified-signatures + removeFileInput(index: number): void; + setAddButtonText(text: string): void; + setDialogTriggerID(ids: string): void; + setEnabled(enabled: boolean): void; + setFileInputCount(count: number): void; + setUploadButtonText(text: string): void; + upload(): void; + on(eventName: K, callback: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; + } + interface BootstrapUploadControlEventMap extends ControlEventMap { + "dropZoneEnter": UploadControlDropZoneEnterEventArgs; + "dropZoneLeave": UploadControlDropZoneLeaveEventArgs; + "fileInputCountChanged": EventArgs; + "fileUploadComplete": UploadControlFileUploadCompleteEventArgs; + "filesUploadComplete": UploadControlFilesUploadCompleteEventArgs; + "filesUploadStart": UploadControlFilesUploadStartEventArgs; + "textChanged": UploadControlTextChangedEventArgs; + "uploadingProgressChanged": UploadControlUploadingProgressChangedEventArgs; + "validationErrorOccurred": UploadControlValidationErrorOccurredEventArgs; + } + + class BootstrapUploadControlFile extends Control { + readonly name: string; + readonly size: number; + readonly sourceFileObject: any; + on(eventName: K, callback: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; + } + interface BootstrapUploadControlFileEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapUploadControlInvalidFileInfo extends Control { + readonly fileName: string; + readonly fileSize: number; + on(eventName: K, callback: (this: BootstrapUploadControlInvalidFileInfo, args?: + BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; + once(eventName: K, callback: (this: BootstrapUploadControlInvalidFileInfo, + args?: BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: BootstrapUploadControlInvalidFileInfo, + args?: BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; + } + interface BootstrapUploadControlInvalidFileInfoEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } + + class BootstrapUploadControlValidationSettings extends Control { + readonly allowedFileExtensions: string[]; + readonly invalidFileNameCharacters: string[]; + readonly maxFileCount: number; + readonly maxFileSize: number; + on(eventName: K, callback: (this: BootstrapUploadControlValidationSettings, + args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; + once(eventName: K, callback: (this: + BootstrapUploadControlValidationSettings, args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; + off(eventName?: K, callback?: (this: + BootstrapUploadControlValidationSettings, args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; + } + interface BootstrapUploadControlValidationSettingsEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface + } +} diff --git a/types/devexpress-aspnetcore-bootstrap/tsconfig.json b/types/devexpress-aspnetcore-bootstrap/tsconfig.json new file mode 100644 index 0000000000..1131d37582 --- /dev/null +++ b/types/devexpress-aspnetcore-bootstrap/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "devexpress-aspnetcore-bootstrap-tests.ts" + ] +} \ No newline at end of file diff --git a/types/devexpress-aspnetcore-bootstrap/tslint.json b/types/devexpress-aspnetcore-bootstrap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/devexpress-aspnetcore-bootstrap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index 4a4a9f0492..1e075d7ba9 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -21,6 +21,11 @@ declare namespace dygraphs { * A per-series color definition. Used in conjunction with, and overrides, the colors option. */ color?: string; + + /** + * A function which plot data for this series on the chart. + */ + plotter?: any; /** * Draw a small dot at each point, in addition to a line going through the point. This makes diff --git a/types/ember-mocha/ember-mocha-tests.ts b/types/ember-mocha/ember-mocha-tests.ts index 3516932eec..75d1154a87 100644 --- a/types/ember-mocha/ember-mocha-tests.ts +++ b/types/ember-mocha/ember-mocha-tests.ts @@ -3,7 +3,7 @@ import { setResolver, setupAcceptanceTest, setupComponentTest, setupModelTest, setupTest } from 'ember-mocha'; -import { context, describe, it, beforeEach, afterEach, before, after } from 'mocha'; +import { describe, it, beforeEach, afterEach, before, after } from 'mocha'; import chai = require('chai'); import Ember from "ember"; import hbs from 'htmlbars-inline-precompile'; diff --git a/types/ember-mocha/index.d.ts b/types/ember-mocha/index.d.ts index 1d24564e31..84510eee38 100644 --- a/types/ember-mocha/index.d.ts +++ b/types/ember-mocha/index.d.ts @@ -60,6 +60,5 @@ declare module 'ember-mocha' { declare module 'mocha' { // augment test callback context - interface ITestCallbackContext extends TestContext {} - interface IHookCallbackContext extends TestContext {} + interface Context extends TestContext {} } diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 91c45b94e7..2c9c3c8b7e 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1173,7 +1173,7 @@ declare module 'ember' { * key. You can pass an optional second argument with the target value. Otherwise * this will match any property that evaluates to false. */ - rejectBy(key: string, value?: string): NativeArray; + rejectBy(key: string, value?: any): NativeArray; /** * Returns the first item in the array for which the callback returns true. * This method works similar to the `filter()` method defined in JavaScript 1.6 @@ -2368,7 +2368,7 @@ declare module 'ember' { function Exception(message: string): void; class SafeString { constructor(str: string); - static toString(): string; + toString(): string; } function parse(string: string): any; function print(ast: any): void; diff --git a/types/ember/tslint.json b/types/ember/tslint.json index 7069614893..f77f8d2ed8 100755 --- a/types/ember/tslint.json +++ b/types/ember/tslint.json @@ -24,8 +24,6 @@ "only-arrow-functions": false, "no-submodule-imports": false, - "no-unnecessary-class": false, - // false positives "unified-signatures": false } diff --git a/types/ethereumjs-util/index.d.ts b/types/ethereumjs-util/index.d.ts index eb47d3a6a9..c5ae356f5b 100644 --- a/types/ethereumjs-util/index.d.ts +++ b/types/ethereumjs-util/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for ethereumjs-util 5.1 +// Type definitions for ethereumjs-util 5.2 // Project: https://github.com/ethereumjs/ethereumjs-util#readme // Definitions by: Juan J. Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -// TODO: import types for [`BN`](https://github.com/indutny/bn.js) -// TODO: MAX_INTEGER as type of BN // TODO: import types for [`rlp`](https://github.com/ethereumjs/rlp) // TODO: import types for [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) +import BN = require("bn.js"); + export const SHA3_NULL_S: string; export const SHA3_RLP_ARRAY_S: string; @@ -18,13 +18,11 @@ export const SHA3_RLP_S: string; export function addHexPrefix(str: string): string; -export function arrayContainsArray(superset: any, subset: any, some: any): any; - -export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[]; +export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[] | null; export function bufferToHex(buf: Buffer | Uint8Array): string; -export function bufferToInt(buf: Buffer | Uint8Array): string; +export function bufferToInt(buf: Buffer | Uint8Array): number; export function defineProperties(self: {[k: string]: any}, fields: string[], data: {[k: string]: any}): {[k: string]: any}; @@ -34,14 +32,16 @@ export function ecsign(msgHash: Buffer | Uint8Array, privateKey: Buffer | Uint8A export function fromRpcSig(sig: string): {[k: string]: any}; -export function fromSigned(num: Buffer | Uint8Array): any; +export function fromSigned(num: Buffer | Uint8Array): BN; export function generateAddress(from: Buffer | Uint8Array, nonce: Buffer | Uint8Array): Buffer | Uint8Array; -export function hashPersonalMessage(message: string): Buffer | Uint8Array; +export function hashPersonalMessage(message: Buffer | Uint8Array | any[]): Buffer | Uint8Array; export function importPublic(publicKey: Buffer | Uint8Array): Buffer | Uint8Array; +export function isPrecompiled(address: Buffer | Uint8Array): boolean; + export function isValidAddress(address: string): boolean; export function isValidChecksumAddress(address: Buffer | Uint8Array): boolean; @@ -52,11 +52,17 @@ export function isValidPublic(publicKey: Buffer | Uint8Array, sanitize?: boolean export function isValidSignature(v: Buffer | Uint8Array, r: Buffer | Uint8Array, s: Buffer | Uint8Array, homestead?: boolean): boolean; +export function isZeroAddress(address: string): boolean; + +export function keccak(a: Buffer | Uint8Array | any[] | string | number, bits?: number): Buffer | Uint8Array; + +export function keccak256(a: Buffer | Uint8Array | any[] | string | number): Buffer | Uint8Array; + export function privateToAddress(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; export function privateToPublic(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; -export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize: boolean): Buffer | Uint8Array; +export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize?: boolean): Buffer | Uint8Array; export function ripemd160(a: Buffer | Uint8Array | any[] | string | number, padded: boolean): Buffer | Uint8Array; @@ -76,8 +82,10 @@ export function toChecksumAddress(address: string): string; export function toRpcSig(v: number, r: Buffer | Uint8Array, s: Buffer | Uint8Array): string; -export function toUnsigned(num: any): Buffer | Uint8Array; +export function toUnsigned(num: BN): Buffer | Uint8Array; export function unpad(a: T): T; export function zeros(bytes: number): Buffer | Uint8Array; + +export function zeroAddress(): string; diff --git a/types/eventsource/eventsource-tests.ts b/types/eventsource/eventsource-tests.ts index 62f867926f..c1b53030cd 100644 --- a/types/eventsource/eventsource-tests.ts +++ b/types/eventsource/eventsource-tests.ts @@ -1,17 +1,39 @@ import EventSource = require("eventsource"); const eventSource = new EventSource("http://foobar"); -eventSource.onmessage = (x: any) => {}; -eventSource.onerror = (x: any) => {}; -eventSource.onopen = (x: any) => {}; -eventSource.addEventListener = (type: string, x: any) => {}; +let readyState: number = eventSource.readyState; +let closedState: number = eventSource.CLOSED; +closedState = EventSource.CLOSED; +let connectingState: number = eventSource.CONNECTING; +connectingState = EventSource.CONNECTING; +let openState: number = eventSource.OPEN; +openState = EventSource.OPEN; +let url: string = eventSource.url; +let withCredentials: boolean = eventSource.withCredentials; +eventSource.onmessage = (event: Event) => {}; +eventSource.onerror = (event: Event) => {}; +eventSource.onopen = (event: Event) => {}; +eventSource.addEventListener = (type: string, listener: (e: Event) => void) => {}; +eventSource.dispatchEvent = (event: Event) => true; +eventSource.removeEventListener = (type: string, listener: (e: Event) => void) => {}; eventSource.close(); import EventSourcePolyfill = require("eventsource/lib/eventsource-polyfill"); const eventSourcePolyfill = new EventSourcePolyfill("http://foobar"); -eventSourcePolyfill.onmessage = (x: any) => {}; -eventSourcePolyfill.onerror = (x: any) => {}; -eventSourcePolyfill.onopen = (x: any) => {}; -eventSourcePolyfill.addEventListener = (type: string, x: any) => {}; +readyState = eventSourcePolyfill.readyState; +closedState = eventSource.CLOSED; +closedState = EventSource.CLOSED; +connectingState = eventSource.CONNECTING; +connectingState = EventSource.CONNECTING; +openState = eventSource.OPEN; +openState = EventSource.OPEN; +url = eventSourcePolyfill.url; +withCredentials = eventSource.withCredentials; +eventSourcePolyfill.onmessage = (event: Event) => {}; +eventSourcePolyfill.onerror = (event: Event) => {}; +eventSourcePolyfill.onopen = (event: Event) => {}; +eventSourcePolyfill.addEventListener = (type: string, listener: (e: Event) => void) => {}; +eventSourcePolyfill.dispatchEvent = (event: Event) => true; +eventSourcePolyfill.removeEventListener = (type: string, listener: (e: Event) => void) => {}; eventSourcePolyfill.close(); diff --git a/types/eventsource/index.d.ts b/types/eventsource/index.d.ts index 62859d037b..1308515917 100644 --- a/types/eventsource/index.d.ts +++ b/types/eventsource/index.d.ts @@ -1,22 +1,29 @@ // Type definitions for eventsource 1.0 // Project: http://github.com/EventSource/eventsource // Definitions by: Scott Lee Davis +// Ali Afroozeh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.8 declare class EventSource { + static readonly CLOSED: number; + static readonly CONNECTING: number; + static readonly OPEN: number; + constructor(url: string, eventSourceInitDict?: EventSource.EventSourceInitDict); - static CLOSED: EventSource.ReadyState; - static CONNECTING: EventSource.ReadyState; - static OPEN: EventSource.ReadyState; - - url: string; - readyState: EventSource.ReadyState; + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + readonly url: string; + readonly readyState: number; + readonly withCredentials: boolean; onopen: EventListener; onmessage: EventListener; onerror: EventListener; addEventListener(type: string, listener: EventListener): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListener): void; close(): void; } diff --git a/types/eventsource/lib/eventsource-polyfill/index.d.ts b/types/eventsource/lib/eventsource-polyfill/index.d.ts index 3e4ad378e4..86b82105cc 100644 --- a/types/eventsource/lib/eventsource-polyfill/index.d.ts +++ b/types/eventsource/lib/eventsource-polyfill/index.d.ts @@ -1,16 +1,22 @@ declare class EventSource { + static readonly CLOSED: number; + static readonly CONNECTING: number; + static readonly OPEN: number; + constructor(url: string, eventSourceInitDict?: EventSource.EventSourceInitDict); - static CLOSED: EventSource.ReadyState; - static CONNECTING: EventSource.ReadyState; - static OPEN: EventSource.ReadyState; - - url: string; - readyState: EventSource.ReadyState; + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + readonly url: string; + readonly readyState: number; + readonly withCredentials: boolean; onopen: EventListener; onmessage: EventListener; onerror: EventListener; addEventListener(type: string, listener: EventListener): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListener): void; close(): void; } diff --git a/types/ex-react-native-i18n/ex-react-native-i18n-tests.ts b/types/ex-react-native-i18n/ex-react-native-i18n-tests.ts new file mode 100644 index 0000000000..c83c4b60d3 --- /dev/null +++ b/types/ex-react-native-i18n/ex-react-native-i18n-tests.ts @@ -0,0 +1,8 @@ +import I18n from 'ex-react-native-i18n'; + +I18n.defaultLocale = 'en'; +I18n.fallbacks = true; +I18n.translations = {}; +I18n.locale = 'zh'; + +const deviceLocale: string = I18n.locale; diff --git a/types/ex-react-native-i18n/index.d.ts b/types/ex-react-native-i18n/index.d.ts new file mode 100644 index 0000000000..0b83b06a68 --- /dev/null +++ b/types/ex-react-native-i18n/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for ex-react-native-i18n 0.0 +// Project: https://github.com/xcarpentier/ex-react-native-i18n/ +// Definitions by: LikKee Richie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// Actual version for ex-react-native-i18n is 0.0.4 but 'npm run lint' doesn't allow patch version to pass +import I18n = require("i18n-js"); +// import I18n from 'ex-react-native-i18n'; + +export default I18n; diff --git a/types/ex-react-native-i18n/tsconfig.json b/types/ex-react-native-i18n/tsconfig.json new file mode 100644 index 0000000000..8e6dd691bf --- /dev/null +++ b/types/ex-react-native-i18n/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ex-react-native-i18n-tests.ts" + ] +} diff --git a/types/ex-react-native-i18n/tslint.json b/types/ex-react-native-i18n/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ex-react-native-i18n/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e556e5255a..dadfa06f86 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -7,6 +7,8 @@ // Fernando Helwanger // Umidbek Karimov // Moshe Feuchtwanger +// Michael Prokopchuk +// Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -788,11 +790,31 @@ export interface CameraProps extends ViewProps { } export interface CameraConstants { - readonly Type: string; - readonly FlashMode: string; - readonly AutoFocus: string; - readonly WhiteBalance: string; - readonly VideoQuality: string; + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; readonly BarCodeType: { aztec: string; codabar: string; @@ -878,7 +900,7 @@ export namespace Constants { }; appKey?: string; androidStatusBar?: { - barStyle?: 'lignt-content' | 'dark-content', + barStyle?: 'light-content' | 'dark-content', backgroundColor?: string }; androidShowExponentNotificationInShellApp?: boolean; @@ -1390,12 +1412,24 @@ export namespace Font { } // #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + /** - * GLView + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. */ export interface GLViewProps extends ViewProps { - onContextCreate(): void; - msaaSamples: number; + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; } export class GLView extends Component { } @@ -2188,6 +2222,7 @@ export interface VideoProps { translateY?: number; rotation?: number; ref?: Ref; + style?: StyleProp; } export interface VideoState { diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 4e7a0ebdb3..9b65002305 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -6,6 +6,7 @@ // Sergio Sánchez // Fernando Helwanger // Umidbek Karimov +// Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -787,11 +788,31 @@ export interface CameraProps extends ViewProps { } export interface CameraConstants { - readonly Type: string; - readonly FlashMode: string; - readonly AutoFocus: string; - readonly WhiteBalance: string; - readonly VideoQuality: string; + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; readonly BarCodeType: { aztec: string; codabar: string; @@ -877,7 +898,7 @@ export namespace Constants { }; appKey?: string; androidStatusBar?: { - barStyle?: 'lignt-content' | 'dark-content', + barStyle?: 'light-content' | 'dark-content', backgroundColor?: string }; androidShowExponentNotificationInShellApp?: boolean; @@ -2181,6 +2202,7 @@ export interface VideoProps { translateY?: number; rotation?: number; ref?: Ref; + style?: StyleProp; } export interface VideoState { diff --git a/types/expo__status-bar-height/expo__status-bar-height-tests.ts b/types/expo__status-bar-height/expo__status-bar-height-tests.ts new file mode 100644 index 0000000000..84dd284d12 --- /dev/null +++ b/types/expo__status-bar-height/expo__status-bar-height-tests.ts @@ -0,0 +1,11 @@ +import StatusBarHeight from '@expo/status-bar-height'; + +const onChangeHeight = (height: number) => console.log(`New height: ${height}`); + +StatusBarHeight.addEventListener(onChangeHeight); + +StatusBarHeight.getAsync() + .then((height: number) => console.log(`Current height: ${height}`)) + .catch((error: Error) => console.error('Threw an error in StatusBarHeight.getAsync():', error)); + +StatusBarHeight.removeEventListener(onChangeHeight); diff --git a/types/expo__status-bar-height/index.d.ts b/types/expo__status-bar-height/index.d.ts new file mode 100644 index 0000000000..24331721da --- /dev/null +++ b/types/expo__status-bar-height/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for @expo/status-bar-height 0.0 +// Project: https://github.com/expo/status-bar-height +// Definitions by: Janeene Beeforth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type StatusBarHeightHandler = (height: number) => void; + +export class StatusBarHeight { + /** + * Get the current status bar height + */ + getAsync(): Promise; + /** + * Add 'willChange' event listener + */ + addEventListener(handler: StatusBarHeightHandler): void; + /** + * Remove 'willChange' event listener + */ + removeEventListener(handler: StatusBarHeightHandler): void; +} + +declare const StatusBarHeightStatic: StatusBarHeight; +export default StatusBarHeightStatic; diff --git a/types/expo__status-bar-height/tsconfig.json b/types/expo__status-bar-height/tsconfig.json new file mode 100644 index 0000000000..88649150a0 --- /dev/null +++ b/types/expo__status-bar-height/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@expo/status-bar-height": [ + "expo__status-bar-height" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo__status-bar-height-tests.ts" + ] +} diff --git a/types/expo__status-bar-height/tslint.json b/types/expo__status-bar-height/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo__status-bar-height/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-brute/index.d.ts b/types/express-brute/index.d.ts index b7961ea597..8f1b6fbf11 100644 --- a/types/express-brute/index.d.ts +++ b/types/express-brute/index.d.ts @@ -67,19 +67,19 @@ declare namespace ExpressBrute { * @summary Allows you to override the value of failCallback for this middleware. * @type {Function} */ - failCallback: Function; + failCallback?: Function; /** * @summary Disregard IP address when matching requests if set to true. Defaults to false. * @type {boolean} */ - ignoreIP: boolean; + ignoreIP?: boolean; /** * @summary Key. * @type {any} */ - key: any; + key?: any; } /** @@ -156,5 +156,13 @@ declare namespace ExpressBrute { reset(key: string, callback: (error: any) => void): void; } } + +declare module "express-serve-static-core" { + export interface Request { + brute?: { + reset?: (callback?: () => void) => void + }; + } +} export = ExpressBrute; diff --git a/types/express-socket.io-session/express-socket.io-session-tests.ts b/types/express-socket.io-session/express-socket.io-session-tests.ts index 46dd000882..6937952dd6 100644 --- a/types/express-socket.io-session/express-socket.io-session-tests.ts +++ b/types/express-socket.io-session/express-socket.io-session-tests.ts @@ -26,3 +26,19 @@ io.use(sharedsession(session)); io.use(sharedsession(session, { autoSave: true, saveUninitialized: true })); io.use(sharedsession(session, cookieParser)); io.use(sharedsession(session, cookieParser, { autoSave: true, saveUninitialized: true })); + +io.on('connection', (socket) => { + const sessionID = [ + socket.handshake.sessionID, + socket.handshake.session!.id + ]; + const sessionData = [ + socket.handshake.session!['sessionEntry'], + socket.handshake.session!.anotherSessionEntry + ]; + socket.handshake.session!.touch(() => {}); + socket.handshake.session!.regenerate(() => {}); + socket.handshake.session!.save(() => {}); + socket.handshake.session!.reload(() => {}); + socket.handshake.session!.destroy(() => {}); +}); diff --git a/types/express-socket.io-session/index.d.ts b/types/express-socket.io-session/index.d.ts index 39a1fb4ff6..07acac556a 100644 --- a/types/express-socket.io-session/index.d.ts +++ b/types/express-socket.io-session/index.d.ts @@ -7,6 +7,13 @@ import socketio = require('socket.io'); import express = require('express'); +declare module "socket.io" { + interface Handshake { + session?: Express.Session; + sessionID?: string; + } +} + declare function sharedsession( expressSessionMiddleware: express.RequestHandler, cookieParserMiddleware: express.RequestHandler, diff --git a/types/fibjs/UNUSED_FILES.txt b/types/fibjs/UNUSED_FILES.txt new file mode 100644 index 0000000000..2a6c4b5a1c --- /dev/null +++ b/types/fibjs/UNUSED_FILES.txt @@ -0,0 +1 @@ +declare/_test_env.d.ts \ No newline at end of file diff --git a/types/fibjs/declare/Buffer.d.ts b/types/fibjs/declare/Buffer.d.ts new file mode 100644 index 0000000000..1d51d44ab6 --- /dev/null +++ b/types/fibjs/declare/Buffer.d.ts @@ -0,0 +1,1131 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 二进制数据缓存对象,用于 io 读写的数据处理 + * @detail Buffer 对象为全局基础类,在任何时候都可以直接以 new Buffer(...) 创建:,```JavaScript,var buf = new Buffer();,``` + */ + +declare class Class_Buffer extends Class__object { + + /** + * class prop + * + * + * @brief 获取缓存对象的尺寸 + * + * @readonly + * @type Integer + */ + + length: number + + + + /** + * + * @brief 缓存对象构造函数 + * @param datas 初始化数据数组 + * + * + * + */ + constructor(datas: any[]); + + /** + * + * @brief 缓存对象构造函数 + * @param datas 初始化数据数组 + * + * + * + */ + constructor(datas: ArrayBuffer); + + /** + * + * @brief 缓存对象构造函数 + * @param datas 初始化数据数组 + * + * + * + */ + constructor(datas: TypedArray); + + /** + * + * @brief 缓存对象构造函数 + * @param datas 初始化数据数组 + * + * + * + */ + constructor(datas: ArrayBufferView); + + /** + * + * @brief 缓存对象构造函数 + * @param buffer 初始化Buffer对象 + * + * + * + */ + constructor(buffer: Class_Buffer); + + /** + * + * @brief 缓存对象构造函数 + * @param str 初始化字符串,字符串将以 utf-8 格式写入,缺省则创建一个空对象 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * + * + * + */ + constructor(str: string, codec?: string/** = "utf8"*/); + + /** + * + * @brief 缓存对象构造函数 + * @param size 初始化缓冲区大小 + * + * + * + */ + constructor(size?: number/** = 0*/); + + /** + * + * @brief 检测给定的变量是否是 Buffer 对象 + * @param v 给定需要检测的变量 + * @return 传入对象是否 Buffer 对象 + * + * + * + */ + static isBuffer(v: any): boolean; + + /** + * + * @brief 通过其他 Buffer 创建 Buffer 对象 + * @param buffer 给定 Buffer 类型变量用于创建 Buffer 对象 + * @param byteOffset 指定数据起始位置,起始为 0 + * @param length 指定数据长度,起始位 -1,表示剩余所有数据 + * @return 返回 Buffer 实例 + * + * + * + */ + static from(buffer: Class_Buffer, byteOffset?: number/** = 0*/, length?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 通过字符串创建 Buffer 对象 + * @param str 初始化字符串,字符串将以 utf-8 格式写入 + * @param byteOffset 指定数据起始位置,起始为 0 + * @param length 指定数据长度,起始位 -1,表示剩余所有数据 + * @return 返回 Buffer 实例 + * + * + * + */ + static from(str: string, byteOffset?: number/** = 0*/, length?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 通过字符串创建 Buffer 对象 + * @param str 初始化字符串,字符串将以 utf-8 格式写入,缺省则创建一个空对象 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 返回 Buffer 实例 + * + * + * + */ + static from(str: string, codec?: string/** = "utf8"*/): Class_Buffer; + + /** + * + * @brief 拼接多个缓存区中的数据 + * @param buflist 待拼接的Buffer数组 + * @param cutLength 截取多少个Buffer对象 + * @return 拼接后产生的新 Buffer 对象 + * + * + * + */ + static concat(buflist: any[], cutLength?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 分配一个指定长度的新缓存区。如果大小为0,将创建一个零长度的缓存区。 + * @param size 缓冲区的所需长度 + * @param fill 预先填充新缓冲区的值,可使用 string/buffer/integer 值类型。 默认值:0 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 填充好的新 Buffer 对象 + * + * + * + */ + static alloc(size: number, fill?: number/** = 0*/, codec?: string/** = "utf8"*/): Class_Buffer; + + /** + * + * @brief 分配一个指定长度的新缓存区。如果大小为0,将创建一个零长度的缓存区。 + * @param size 缓冲区的所需长度 + * @param fill 预先填充新缓冲区的值,可使用 string/buffer/integer 值类型。 默认值:0 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 填充好的新 Buffer 对象 + * + * + * + */ + static alloc(size: number, fill?: string/** = ""*/, codec?: string/** = "utf8"*/): Class_Buffer; + + /** + * + * @brief 分配一个指定长度的新缓存区。如果大小为0,将创建一个零长度的缓存区。 + * @param size 缓冲区的所需长度 + * @param fill 预先填充新缓冲区的值,可使用 string/buffer/integer 值类型。 默认值:0 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 填充好的新 Buffer 对象 + * + * + * + */ + static alloc(size: number, fill: Class_Buffer, codec?: string/** = "utf8"*/): Class_Buffer; + + /** + * + * @brief 分配一个指定长度的新缓存区。如果大小为0,将创建一个零长度的缓存区。 + * @param size 缓冲区的所需长度 + * @return 指定尺寸的新 Buffer 对象 + * + * + * + */ + static allocUnsafe(size: number): Class_Buffer; + + /** + * + * @brief 分配一个指定长度的新缓存区。如果大小为0,将创建一个零长度的缓存区。 + * @param size 缓冲区的所需长度 + * @return 指定尺寸的新 Buffer 对象 + * + * + * + */ + static allocUnsafeSlow(size: number): Class_Buffer; + + /** + * + * @brief 返回字符串的实际字节长度 + * @param str 待取字节的字符串,如果str为 ArrayBuffer/TypedArray/DataView/Buffer 对象,则返回它们的实际长度 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 返回实际字节长度 + * + * + * + */ + static byteLength(str: string, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 返回字符串的实际字节长度 + * @param str 待取字节的字符串,如果str为 ArrayBuffer/TypedArray/DataView/Buffer 对象,则返回它们的实际长度 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 返回实际字节长度 + * + * + * + */ + static byteLength(str: ArrayBuffer, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 返回字符串的实际字节长度 + * @param str 待取字节的字符串,如果 str 为 ArrayBuffer/TypedArray/DataView/Buffer 对象,则返回它们的实际长度 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 返回实际字节长度 + * + * + * + */ + static byteLength(str: ArrayBufferView, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 返回字符串的实际字节长度 + * @param str 待取字节的字符串,如果str为 ArrayBuffer/TypedArray/DataView/Buffer 对象,则返回它们的实际长度 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 返回实际字节长度 + * + * + * + */ + static byteLength(str: Class_Buffer, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 检测编码格式是否被支持 + * @param codec 待检测的编码格式 + * @return 是否支持 + * + * + * + */ + static isEncoding(codec: string): boolean; + + /** + * + * @brief 修改缓存对象尺寸 + * @param sz 指定新尺寸 + * + * + * + */ + resize(sz: number): void; + + /** + * + * @brief 在缓存对象尾部写入一组二进制数据 + * @param data 初始化二进制数据 + * + * + * + */ + append(data: Class_Buffer): void; + + /** + * + * @brief 在缓存对象尾部写入字符串,字符串将以 utf-8 格式写入 + * @param str 要写入的字符串 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * + * + * + */ + append(str: string, codec?: string/** = "utf8"*/): void; + + /** + * + * @brief 向缓存对象写入指定字符串,字符串默认为utf-8,越界时只写入部分数据 + * @param str 待写入的字符串 + * @param offset 写入起始位置 + * @param length 写入长度(单位字节,默认值-1),未指定时为待写入字符串的长度 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 写入的数据字节长度 + * + * + * + */ + write(str: string, offset?: number/** = 0*/, length?: number/** = -1*/, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 向缓存对象写入指定字符串,字符串默认为utf-8,越界时只写入部分数据 + * @param str 待写入的字符串 + * @param offset 写入起始位置 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 写入的数据字节长度 + * + * + * + */ + write(str: string, offset?: number/** = 0*/, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 向缓存对象写入指定字符串,字符串默认为utf-8,越界时只写入部分数据 + * @param str 待写入的字符串 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @return 写入的数据字节长度 + * + * + * + */ + write(str: string, codec?: string/** = "utf8"*/): number; + + /** + * + * @brief 为 Buffer 对象填充指定内容数据 + * @param v 需要填充的数据,如果未指定 offset 和 end,将填充满整个 buffer + * @param offset 填充起始位置 + * @param end 填充终止位置 + * @return 返回当前 Buffer 对象 + * + * + * + */ + fill(v: number, offset?: number/** = 0*/, end?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 为 Buffer 对象填充指定内容数据 + * @param v 需要填充的数据,如果未指定 offset 和 end,将填充满整个 buffer + * @param offset 填充起始位置 + * @param end 填充终止位置 + * @return 返回当前 Buffer 对象 + * + * + * + */ + fill(v: Class_Buffer, offset?: number/** = 0*/, end?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 为 Buffer 对象填充指定内容数据 + * @param v 需要填充的数据,如果未指定 offset 和 end,将填充满整个 buffer + * @param offset 填充起始位置 + * @param end 填充终止位置 + * @return 返回当前 Buffer 对象 + * + * + * + */ + fill(v: string, offset?: number/** = 0*/, end?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 返回某个指定数据在 Buffer 中首次出现的位置 + * @param v 待查找数据,如果未指定 offset,默认从起始位开始 + * @param offset 起始查找位置 + * @return 返回查找到的位置,未找到返回 -1 + * + * + * + */ + indexOf(v: number, offset?: number/** = 0*/): number; + + /** + * + * @brief 返回某个指定数据在 Buffer 中首次出现的位置 + * @param v 待查找数据,如果未指定 offset,默认从起始位开始 + * @param offset 起始查找位置 + * @return 返回查找到的位置,未找到返回 -1 + * + * + * + */ + indexOf(v: Class_Buffer, offset?: number/** = 0*/): number; + + /** + * + * @brief 返回某个指定数据在 Buffer 中首次出现的位置 + * @param v 待查找数据,如果未指定 offset,默认从起始位开始 + * @param offset 起始查找位置 + * @return 返回查找到的位置,未找到返回 -1 + * + * + * + */ + indexOf(v: string, offset?: number/** = 0*/): number; + + /** + * + * @brief 比较缓存区的内容 + * @param buf 待比较缓存对象 + * @return 内容比较结果 + * + * + * + */ + compare(buf: Class_Buffer): number; + + /** + * + * @brief 从源缓存对象区域拷贝数据到目标缓存对象区域 + * @param targetBuffer 目标缓存对象 + * @param targetStart 目标缓存对象开始拷贝字节位置,缺省为 0 + * @param sourceStart 源缓存对象开始字节位置, 缺省为 0 + * @param sourceEnd 源缓存对象结束字节位置, 缺省为 -1,表示源数据长度 + * @return 拷贝的数据字节长度 + * + * + * + */ + copy(targetBuffer: Class_Buffer, targetStart?: number/** = 0*/, sourceStart?: number/** = 0*/, sourceEnd?: number/** = -1*/): number; + + /** + * + * @brief 从缓存对象读取一个 8 位无符号整型数值 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUInt8(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 16 位无符号整型数值,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUInt16LE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 16 位无符号整型数值,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUInt16BE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 32 位无符号整型数值,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUInt32LE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 32 位无符号整型数值,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUInt32BE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个无符号整型数值,最大支持 48 位,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUIntLE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个无符号整型数值,最大支持 48 位,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readUIntBE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 8 位整型数值 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt8(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 16 位整型数值,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt16LE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 16 位整型数值,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt16BE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 32 位整型数值,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt32LE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 32 位整型数值,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt32BE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个整型数值,最大支持 48 位,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readIntLE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个整型数值,最大支持 48 位,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readIntBE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个 64 位整型数值,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt64LE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): Class_Int64; + + /** + * + * @brief 从缓存对象读取一个 64 位整型数值,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的整型数值 + * + * + * + */ + readInt64BE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): Class_Int64; + + /** + * + * @brief 从缓存对象读取一个浮点数,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的浮点数 + * + * + * + */ + readFloatLE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个浮点数,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的浮点数 + * + * + * + */ + readFloatBE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个双精度浮点数,以低字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的双精度浮点数 + * + * + * + */ + readDoubleLE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 从缓存对象读取一个双精度浮点数,以高字节序的存储方式 + * @param offset 指定读取的起始位置,缺省为 0 + * @param noAssert 指定读取越界时不抛出错误,缺省为 flase,抛出 + * @return 返回读取的双精度浮点数 + * + * + * + */ + readDoubleBE(offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 8 位无符号整型数值 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUInt8(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 16 位无符号整型数值,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUInt16LE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 16 位无符号整型数值,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUInt16BE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 32 位无符号整型数值,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUInt32LE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 32 位无符号整型数值,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUInt32BE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个无符号整型数值,最大支持 48 位,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUIntLE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个无符号整型数值,最大支持 48 位,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeUIntBE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 8 位整型数值 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt8(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 16 位整型数值,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt16LE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 16 位整型数值,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt16BE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 32 位整型数值,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt32LE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 32 位整型数值,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt32BE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个整型数值,最大支持 48 位,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeIntLE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个整型数值,最大支持 48 位,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeIntBE(value: number, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 64 位整型数值,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt64LE(value: Class_Int64, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个 64 位整型数值,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeInt64BE(value: Class_Int64, offset?: number/** = 0*/, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个浮点数,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeFloatLE(value: number, offset: number, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个浮点数,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeFloatBE(value: number, offset: number, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个双精度浮点数,以低字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeDoubleLE(value: number, offset: number, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 向缓存对象写入一个双精度浮点数,以高字节序的存储方式 + * @param value 指定写入的数值 + * @param offset 指定写入的起始位置 + * @param noAssert 指定写入越界时不抛出错误,缺省为 flase,抛出 + * @return offset 加上写入的字节数 + * + * + * + */ + writeDoubleBE(value: number, offset: number, noAssert?: boolean/** = false*/): number; + + /** + * + * @brief 返回一个新缓存对象,包含指定起始到缓存结尾的数据 + * @param start 指定范围的起始,缺省从头开始 + * @return 返回新的缓存对象 + * + * + * + */ + slice(start?: number/** = 0*/): Class_Buffer; + + /** + * + * @brief 返回一个新缓存对象,包含指定范围的数据,若范围超出缓存,则只返回有效部分数据 + * @param start 指定范围的起始 + * @param end 指定范围的结束 + * @return 返回新的缓存对象 + * + * + * + */ + slice(start: number, end: number): Class_Buffer; + + /** + * + * @brief 把当前对象中的所有元素放入一个字符串 + * @param separator 分割字符,缺省为 "," + * @return 返回生成的字符串 + * + * + * + */ + join(separator?: string/** = ","*/): string; + + /** + * + * @brief 返回一个新缓存对象,包含当前对象数据的倒序 + * @return 返回新的缓存对象 + * + * + * + */ + reverse(): Class_Buffer; + + /** + * + * @brief 比较当前对象与给定的对象是否相等 + * @param expected 制定比较的目标对象 + * @return 返回对象比较的结果 + * + * + * + */ + equals(expected: Class__object): boolean; + + /** + * + * @brief 使用 16 进制编码缓存对象内容 + * @return 返回编码字符串 + * + * + * + */ + hex(): string; + + /** + * + * @brief 使用 base64 编码缓存对象内容 + * @return 返回编码字符串 + * + * + * + */ + base64(): string; + + /** + * + * @brief 返回全部二进制数据的数组 + * @return 返回包含对象数据索引的迭代器 + * + * + * + */ + keys(): Object; + + /** + * + * @brief 返回全部二进制数据的数组 + * @return 返回包含对象数据值的迭代器 + * + * + * + */ + values(): Object; + + /** + * + * @brief 返回包含对象数据 [index, byte] 对的迭代器 + * @return [index, byte] 对的迭代器 + * ```JavaScript + * const buf = Buffer.from('buffer'); + * + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * ``` + * + * + * + */ + entries(): Object; + + /** + * + * @brief 返回全部二进制数据的数组 + * @return 返回包含对象数据的数组 + * + * + * + */ + toArray(): any[]; + + /** + * + * @brief 返回二进制数据的编码字符串 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @param offset 读取起始位置 + * @param end 读取终止位置 + * @return 返回对象的字符串表示 + * + * + * + */ + toString(codec: string, offset?: number/** = 0*/, end?: number): string; + + /** + * + * @brief 返回二进制数据的编码字符串 + * @param codec 指定编码格式,允许值为:"hex", "base64", "utf8", 或者系统支持的字符集 + * @param offset 读取起始位置 + * @return 返回对象的字符串表示 + * + * + * + */ + toString(codec: string, offset?: number/** = 0*/): string; + + /** + * + * @brief 返回二进制数据的 utf8 编码字符串 + * @return 返回对象的字符串表示 + * + * + * + */ + toString(): string; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/BufferedStream.d.ts b/types/fibjs/declare/BufferedStream.d.ts new file mode 100644 index 0000000000..f0f1ef74ba --- /dev/null +++ b/types/fibjs/declare/BufferedStream.d.ts @@ -0,0 +1,144 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 缓存读取对象 + * @detail BufferedReader 对象用于对二进制流对象数据进行缓存,并提供文本读取能力,仅支持 utf-8 格式转换。创建方法:,```JavaScript,var reader = new io.BufferedStream(stream);,``` + */ +/// +declare class Class_BufferedStream extends Class_Stream { + + /** + * class prop + * + * + * @brief 查询创建缓存对象时的流对象 + * + * @readonly + * @type Stream + */ + + stream: Class_Stream + + /** + * class prop + * + * + * @brief 查询和设置当前对象处理文本时的字符集,缺省为 utf-8 + * + * + * @type String + */ + + charset: string + + /** + * class prop + * + * + * @brief 查询和设置行结尾标识,缺省时,posix:\"\\n\";windows:\"\\r\\n\" + * + * + * @type String + */ + + EOL: string + + + + /** + * + * @brief BufferedStream 构造函数 + * @param stm BufferedStream 的二进制基础流对象 + * + * + * + */ + constructor(stm: Class_Stream); + + /** + * + * @brief 读取指定字符的文本 + * @param size 指定读取的文本字符个数,以 utf8 或者指定的编码字节数为准 + * @return 返回读取的文本字符串,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + readText(size: number): string; + + /** + * + * @brief 读取一行文本,行结尾标识基于 EOL 属性的设置,缺省时,posix:\"\\n\";windows:\"\\r\\n\" + * @param maxlen 指定此次读取的最大字符串,以 utf8 编码字节数为准,缺省不限制字符数 + * @return 返回读取的文本字符串,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + readLine(maxlen?: number/** = -1*/): string; + + /** + * + * @brief 以数组方式读取一组文本行,行结尾标识基于 EOL 属性的设置,缺省时,posix:\"\\n\";windows:\"\\r\\n\" + * @param maxlines 指定此次读取的最大行数,缺省读取全部文本行 + * @return 返回读取的文本行数组,若无数据可读,或者连接中断,空数组 + * + * + * + */ + readLines(maxlines?: number/** = -1*/): any[]; + + /** + * + * @brief 读取一个文本字符串,以指定的字节为结尾 + * @param mk 指定结尾的字符串 + * @param maxlen 指定此次读取的最大字符串,以 utf8 编码字节数为准,缺省不限制字符数 + * @return 返回读取的文本字符串,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + readUntil(mk: string, maxlen?: number/** = -1*/): string; + + /** + * + * @brief 写入一个字符串 + * @param txt 指定写入的字符串 + * + * + * @async + */ + writeText(txt: string): void; + + /** + * + * @brief 写入一个字符串,并写入换行符 + * @param txt 指定写入的字符串 + * + * + * @async + */ + writeLine(txt: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Chain.d.ts b/types/fibjs/declare/Chain.d.ts new file mode 100644 index 0000000000..9d980757af --- /dev/null +++ b/types/fibjs/declare/Chain.d.ts @@ -0,0 +1,63 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 消息处理器链处理对象 + * @detail 消息处理器链处理对象用于链接一系列消息处理器,按照指定的顺序链式处理。创建方法:,```JavaScript,var chain = new mq.Chain([, func1, func2,]);,``` + */ +/// +declare class Class_Chain extends Class_Handler { + + + + /** + * + * @brief 构造一个消息处理器链处理对象 + * @param hdlrs 处理器数组 + * + * + * + */ + constructor(hdlrs: any[]); + + /** + * + * @brief 添加处理器数组 + * @param hdlrs 处理器数组 + * + * + * + */ + append(hdlrs: any[]): void; + + /** + * + * @brief 添加处理器 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + append(hdlr: Class_Handler): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Cipher.d.ts b/types/fibjs/declare/Cipher.d.ts new file mode 100644 index 0000000000..cbae22fc3f --- /dev/null +++ b/types/fibjs/declare/Cipher.d.ts @@ -0,0 +1,149 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 对称加密算法对象 + * @detail Cipher 对象属于 crypto 模块,创建:,```JavaScript,var c = new crypto.Cipher(crypto.AES, crypto.ECB, ...);,``` + */ + +declare class Class_Cipher extends Class__object { + + /** + * class prop + * + * + * @brief 返回当前算法名称 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 返回当前算法密码长度,以位为单位 + * + * @readonly + * @type Integer + */ + + keySize: number + + /** + * class prop + * + * + * @brief 返回当前算法初始向量长度,以字节为单位 + * + * @readonly + * @type Integer + */ + + ivSize: number + + /** + * class prop + * + * + * @brief 返回当前算法数据块长度,以字节为单位 + * + * @readonly + * @type Integer + */ + + blockSize: number + + + + /** + * + * @brief Cipher 构造函数,仅用于 ARC4 初始化 + * @param provider 指定加密算法 + * @param key 指定加密解密密码 + * + * + * + */ + constructor(provider: number, key: Class_Buffer); + + /** + * + * @brief Cipher 构造函数 + * @param provider 指定加密算法 + * @param mode 指定分组密码工作模式 + * @param key 指定加密解密密码 + * + * + * + */ + constructor(provider: number, mode: number, key: Class_Buffer); + + /** + * + * @brief Cipher 构造函数 + * @param provider 指定加密算法 + * @param mode 指定分组密码工作模式 + * @param key 指定加密解密密码 + * @param iv 指定初始向量 + * + * + * + */ + constructor(provider: number, mode: number, key: Class_Buffer, iv: Class_Buffer); + + /** + * + * @brief 使用填充模式 + * @param mode 指定填充模式,缺省为 PADDING_PKCS7 + * + * + * + */ + paddingMode(mode: number): void; + + /** + * + * @brief 使用当前算法密码加密数据 + * @param data 指定要加密的数据 + * @return 返回加密后的数据 + * + * + * @async + */ + encrypt(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 使用当前算法密码解密数据 + * @param data 指定要解密的数据 + * @return 返回解密后的数据 + * + * + * @async + */ + decrypt(data: Class_Buffer): Class_Buffer; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Condition.d.ts b/types/fibjs/declare/Condition.d.ts new file mode 100644 index 0000000000..47b5e086fa --- /dev/null +++ b/types/fibjs/declare/Condition.d.ts @@ -0,0 +1,75 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 条件变量对象 + * @detail 条件变量是利用纤程间共享的全局变量来进行同步的一种机制,主要包括两个动作:,1)一个线程等待某个条件成立,而将自己挂起;,2)另一个线程使条件成立,并通知等待的纤程向下执行。,,为了防止竞争,每个条件变量都需要一个Lock的配合(Lock可自行显式创建并传递进来,也可交由fibjs为您创建),,通过使用条件变量,可以利用一个条件变量控制一批纤程的开关;,,以下是两个纤程调度的实例:,```JavaScript,var coroutine = require("coroutine");,var cond = new coroutine.Condition();,var ready = false;,var state = "ready";,,function funcwait() {, cond.acquire();, while (!ready), cond.wait();, state = "go", cond.release();,},,coroutine.start(funcwait);,,cond.acquire();,console.log(state),ready = true;,cond.notify();,coroutine.sleep();,console.log(state);,```,will output:,```sh,ready,go,``` + */ +/// +declare class Class_Condition extends Class_Lock { + + + + /** + * + * @brief 条件变量构造函数(条件变量所需的锁由fibjs内部构造) + * + * + */ + constructor(); + + /** + * + * @brief 条件变量构造函数 + * @param lock 使用自行构造的锁 + * + * + * + */ + constructor(lock: Class_Lock); + + /** + * + * @brief 使纤程进入阻塞状态 + * + * + */ + wait(): void; + + /** + * + * @brief 通知一个被阻塞的纤程(最后加入纤程池的)向下继续执行 + * + * + */ + notify(): void; + + /** + * + * @brief 通知所有被阻塞的纤程向下继续执行 + * + * + */ + notifyAll(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/DbConnection.d.ts b/types/fibjs/declare/DbConnection.d.ts new file mode 100644 index 0000000000..221db6a185 --- /dev/null +++ b/types/fibjs/declare/DbConnection.d.ts @@ -0,0 +1,119 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 数据库连接对象,用于建立和维护一个数据库连接会话。 + * @detail + */ + +declare class Class_DbConnection extends Class__object { + + /** + * class prop + * + * + * @brief 查询当前连接数据库类型 + * + * @readonly + * @type String + */ + + type: string + + + + /** + * + * @brief 关闭当前数据库连接 + * + * @async + */ + close(): void; + + /** + * + * @brief 在当前数据库连接上启动一个事务 + * + * @async + */ + begin(): void; + + /** + * + * @brief 提交当前数据库连接上的事务 + * + * @async + */ + commit(): void; + + /** + * + * @brief 回滚当前数据库连接上的事务 + * + * @async + */ + rollback(): void; + + /** + * + * @brief 进入事务执行一个函数,并根据函数执行情况提交或者回滚 + * func 执行有三种结果: + * * 函数正常返回,包括运行结束和主动 return,此时事务将自动提交 + * * 函数返回 false,此时事务将回滚 + * * 函数运行错误,事务自动回滚 + * + * @param func 以事务方式执行的函数 + * @return 返回事务是否提交,正常 commit 时返回 true, rollback 时返回 false,如果事务出错则抛出错误 + * + * + * + */ + trans(func: Function): boolean; + + /** + * + * @brief 执行一个 sql 命令,并返回执行结果,可根据参数格式化字符串 + * + * @param sql 格式化字符串,可选参数用 ? 指定。例如:'SELECT FROM TEST WHERE [id]=?' + * @param args 可选参数列表 + * @return 返回包含结果记录的数组,如果请求是 UPDATE 或者 INSERT,返回结果还会包含 affected 和 insertId,mssql 不支持 insertId。 + * + * + * @async + */ + execute(sql: string, ...args: any[]): any[]; + + /** + * + * @brief 格式化一个 sql 命令,并返回格式化结果 + * + * @param sql 格式化字符串,可选参数用 ? 指定。例如:'SELECT FROM TEST WHERE [id]=?' + * @param args 可选参数列表 + * @return 返回格式化之后的 sql 命令 + * + * + * + */ + format(sql: string, ...args: any[]): string; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/DgramSocket.d.ts b/types/fibjs/declare/DgramSocket.d.ts new file mode 100644 index 0000000000..58ec61209f --- /dev/null +++ b/types/fibjs/declare/DgramSocket.d.ts @@ -0,0 +1,180 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief dgram.Socket 对象是一个封装了数据包函数功能的 EventEmitter。 + * @detail DgramSocket 实例是由 dgram.createSocket() 创建的。创建 dgram.Socket 实例不需要使用 new 关键字。,,创建方法:,```JavaScript,var dgram = require('dgram');,var sock = dgram.createSocket('udp4');,```,,## 事件,DgramSocket 继承于 EventEmitter,对象的状态变化,以及数据接受,都是以事件的方式实现。,,### close 事件,** `close` 事件将在使用 `close()` 关闭一个 `socket` 之后触发。该事件一旦触发,这个 `socket` 上将不会触发新的 `message` 事件。**,,### error 事件,** 当有任何错误发生时,`error` 事件将被触发。 **,,### listening 事件,** 当一个 `socket` 开始监听数据包信息时,`listening` 事件将被触发。该事件会在创建 UDP socket 之后被立即触发。 **,,### message 事件,** 当有新的数据包被 `socket` 接收时,`message` 事件会被触发。`msg` 和 `rinfo` 会作为参数传递到该事件的处理函数中。 **,- msg: Buffer,消息,- rinfo: Object,远程地址信息, - address: string,发送方地址, - family: string,地址类型 ('IPv4' or 'IPv6'), - port: number,发送者端口, - size: number,消息大小 + */ +/// +declare class Class_DgramSocket extends Class_EventEmitter { + + + + /** + * + * @brief 该方法会令 dgram.Socket 在指定的 `port` 和 `addr` 上监听数据包信息。绑定完成时会触发一个 `listening` 事件。 + * @param port 指定绑定端口,若 `port` 未指定或为 0,操作系统会尝试绑定一个随机的端口 + * @param addr 指定绑定地址,若 address 未指定,操作系统会尝试在所有地址上监听。 + * + * + * @async + */ + bind(port?: number/** = 0*/, addr?: string/** = ""*/): void; + + /** + * + * @brief 该方法会令 dgram.Socket 在 `opts` 指定的 `port` 和 `address` 上监听数据包信息。绑定完成时会触发一个 `listening` 事件。 + * @param opts 指定绑定参数 + * + * + * @async + */ + bind(opts: Object): void; + + /** + * + * @brief 在 socket 上发送一个数据包 + * @param msg 指定发送的数据 + * @param port 指定发送的目的端口 + * @param address 指定发送的目的地址 + * @return 返回发送尺寸 + * + * + * @async + */ + send(msg: Class_Buffer, port: number, address?: string/** = ""*/): number; + + /** + * + * @brief 在 socket 上发送一个数据包 + * @param msg 指定发送的数据 + * @param offset 从指定偏移开始发送 + * @param length 之发送指定长度 + * @param port 指定发送的目的端口 + * @param address 指定发送的目的地址 + * @return 返回发送尺寸 + * + * + * @async + */ + send(msg: Class_Buffer, offset: number, length: number, port: number, address?: string/** = ""*/): number; + + /** + * + * @brief 返回一个包含 socket 地址信息的对象。对于 UDP socket,该对象将包含 address、family 和 port 属性。 + * @return 返回对象绑定地址 + * + * + * + */ + address(): any; + + /** + * + * @brief 关闭当前 socket + * + * + */ + close(): void; + + /** + * + * @brief 关闭当前 socket + * @param callback 关闭完成后的回调函数,它相当于为 `close` 事件添加了一个监听器 + * + * + * + */ + close(callback: Function): void; + + /** + * + * @brief 查询 socket 接收缓冲区大小 + * @return 返回查询结果 + * + * + * + */ + getRecvBufferSize(): number; + + /** + * + * @brief 查询 socket 发送缓冲区大小 + * @return 返回查询结果 + * + * + * + */ + getSendBufferSize(): number; + + /** + * + * @brief 设置 socket 接收缓冲区大小 + * @param size 指定要设置的尺寸 + * + * + * + */ + setRecvBufferSize(size: number): void; + + /** + * + * @brief 设置 socket 发送缓冲区大小 + * @param size 指定要设置的尺寸 + * + * + * + */ + setSendBufferSize(size: number): void; + + /** + * + * @brief 设置或清除 SO_BROADCAST socket 选项 + * @param flag 当设置为 true, UDP包会被发送到一个本地接口的广播地址 + * + * + * + */ + setBroadcast(flag: boolean): void; + + /** + * + * @brief 维持 fibjs 进程不退出,在对象绑定期间阻止 fibjs 进程退出 + * @return 返回当前对象 + * + * + * + */ + ref(): Class_DgramSocket; + + /** + * + * @brief 允许 fibjs 进程退出,在对象绑定期间允许 fibjs 进程退出 + * @return 返回当前对象 + * + * + * + */ + unref(): Class_DgramSocket; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Digest.d.ts b/types/fibjs/declare/Digest.d.ts new file mode 100644 index 0000000000..5486759cf1 --- /dev/null +++ b/types/fibjs/declare/Digest.d.ts @@ -0,0 +1,77 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 信息摘要对象 + * @detail + */ + +declare class Class_Digest extends Class__object { + + /** + * class prop + * + * + * @brief 查询当前信息摘要算法的摘要字节数 + * + * @readonly + * @type Integer + */ + + size: number + + + + /** + * + * @brief 更新二进制摘要信息 + * @param data 二进制数据块 + * @return 返回信息摘要对象本身 + * + * + * + */ + update(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 计算并返回摘要 + * @param data 二进制数据块,此数据块将在计算前更新进摘要 + * @return 返回摘要的二进制数据 + * + * + * + */ + digest(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 计算并返回摘要 + * @return 返回摘要的二进制数据 + * + * + * + */ + digest(): Class_Buffer; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Event.d.ts b/types/fibjs/declare/Event.d.ts new file mode 100644 index 0000000000..00c6daa247 --- /dev/null +++ b/types/fibjs/declare/Event.d.ts @@ -0,0 +1,85 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 事件对象 + * @detail 通过一个事件达到对一组纤程进行控制的目的(事件对象的状态为bool类型) + */ +/// +declare class Class_Event extends Class_Lock { + + + + /** + * + * @brief 事件对象构造函数 + * @param value 指定是否等待,为 true 时等待,缺省为 false + * + * + * + */ + constructor(value?: boolean/** = false*/); + + /** + * + * @brief 判断事件对象是否为真 + * @return 如果事件为真,返回 true + * + * + * + */ + isSet(): boolean; + + /** + * + * @brief 激活事件(将事件状态改为true),并调用pulse() + * + * + */ + set(): void; + + /** + * + * @brief 激活等待该事件的所有纤程 + * + * + */ + pulse(): void; + + /** + * + * @brief 重置事件(将事件状态改为false) + * + * + */ + clear(): void; + + /** + * + * @brief 等待一个事件 + * + * + */ + wait(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/EventEmitter.d.ts b/types/fibjs/declare/EventEmitter.d.ts new file mode 100644 index 0000000000..afa0b3f4ac --- /dev/null +++ b/types/fibjs/declare/EventEmitter.d.ts @@ -0,0 +1,311 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 事件触发对象,可用于建立观察者模式,支持事件触发的对象均继承于此,同一事件的同一函数只会产生一次回调 + * @detail Event 对象可独立创建,以用于组建自定义的事件系统:,```JavaScript,var EventEmitter = require('events');,,var e = new EventEmitter();,``` + */ + +declare class Class_EventEmitter extends Class__object { + + /** + * class prop + * + * + * @brief 默认全局最大监听器数 + * @static + * + * @type Integer + */ + + defaultMaxListeners: number + + + + /** + * + * @brief 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 绑定一个事件处理函数到对象 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回成功绑定的数量,如果函数已绑定则返回 0 + * + * + * + */ + on(ev: string, func: Function): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象 + * @param map 指定事件映射关系,对象属性名称将作为事件名称,属性的值将作为事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + on(map: Object): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + addListener(ev: string, func: Function): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象 + * @param map 指定事件映射关系,对象属性名称将作为事件名称,属性的值将作为事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + addListener(map: Object): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象起始 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回成功绑定的数量,如果函数已绑定则返回 0 + * + * + * + */ + prependListener(ev: string, func: Function): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象起始 + * @param map 指定事件映射关系,对象属性名称将作为事件名称,属性的值将作为事件处理函数 + * @return 返回成功绑定的数量,如果函数已绑定则返回 0 + * + * + * + */ + prependListener(map: Object): Object; + + /** + * + * @brief 绑定一个一次性事件处理函数到对象,一次性处理函数只会触发一次 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + once(ev: string, func: Function): Object; + + /** + * + * @brief 绑定一个一次性事件处理函数到对象,一次性处理函数只会触发一次 + * @param map 指定事件映射关系,对象属性名称将作为事件名称,属性的值将作为事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + once(map: Object): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象起始 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回成功绑定的数量,如果函数已绑定则返回 0 + * + * + * + */ + prependOnceListener(ev: string, func: Function): Object; + + /** + * + * @brief 绑定一个事件处理函数到对象起始 + * @param map 指定事件映射关系,对象属性名称将作为事件名称,属性的值将作为事件处理函数 + * @return 返回成功绑定的数量,如果函数已绑定则返回 0 + * + * + * + */ + prependOnceListener(map: Object): Object; + + /** + * + * @brief 从对象处理队列中取消指定函数 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + off(ev: string, func: Function): Object; + + /** + * + * @brief 取消对象处理队列中的全部函数 + * @param ev 指定事件的名称 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + off(ev: string): Object; + + /** + * + * @brief 从对象处理队列中取消指定函数 + * @param map 指定事件映射关系,对象属性名称作为事件名称,属性的值作为事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + off(map: Object): Object; + + /** + * + * @brief 从对象处理队列中取消指定函数 + * @param ev 指定事件的名称 + * @param func 指定事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + removeListener(ev: string, func: Function): Object; + + /** + * + * @brief 取消对象处理队列中的全部函数 + * @param ev 指定事件的名称 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + removeListener(ev: string): Object; + + /** + * + * @brief 从对象处理队列中取消指定函数 + * @param map 指定事件映射关系,对象属性名称作为事件名称,属性的值作为事件处理函数 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + removeListener(map: Object): Object; + + /** + * + * @brief 从对象处理队列中取消所有事件的所有监听器, 如果指定事件,则移除指定事件的所有监听器。 + * @param evs 指定事件的名称 + * @return 返回事件对象本身,便于链式调用 + * + * + * + */ + removeAllListeners(evs?: any[]/** = v8::Array::New(isolate)*/): Object; + + /** + * + * 监听器的默认限制的数量,仅用于兼容 + * @param n 指定事件的数量 + * + * + * + */ + setMaxListeners(n: number): void; + + /** + * + * 获取监听器的默认限制的数量,仅用于兼容 + * @return 返回默认限制数量 + * + * + * + */ + getMaxListeners(): number; + + /** + * + * @brief 查询对象指定事件的监听器数组 + * @param ev 指定事件的名称 + * @return 返回指定事件的监听器数组 + * + * + * + */ + listeners(ev: string): any[]; + + /** + * + * @brief 查询对象指定事件的监听器数量 + * @param ev 指定事件的名称 + * @return 返回指定事件的监听器数量 + * + * + * + */ + listenerCount(ev: string): number; + + /** + * + * @brief 查询监听器事件名称 + * @return 返回事件名称数组 + * + * + * + */ + eventNames(): any[]; + + /** + * + * @brief 主动触发一个事件 + * @param ev 事件名称 + * @param args 事件参数,将会传递给事件处理函数 + * @return 返回事件触发状态,有响应事件返回 true,否则返回 false + * + * + * + */ + emit(ev: string, ...args: any[]): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/EventInfo.d.ts b/types/fibjs/declare/EventInfo.d.ts new file mode 100644 index 0000000000..f108f8e7bd --- /dev/null +++ b/types/fibjs/declare/EventInfo.d.ts @@ -0,0 +1,81 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 事件信息对象,用于在事件中传递信息 + * @detail + */ + +declare class Class_EventInfo extends Class__object { + + /** + * class prop + * + * + * 查询事件错误编码 + * + * @readonly + * @type Integer + */ + + code: number + + /** + * class prop + * + * + * 查询事件错误信息 + * + * @readonly + * @type String + */ + + reason: string + + /** + * class prop + * + * + * 查询事件类型 + * + * @readonly + * @type String + */ + + type: string + + /** + * class prop + * + * + * 查询触发事件的对象 + * + * @readonly + * @type Object + */ + + target: Object + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Fiber.d.ts b/types/fibjs/declare/Fiber.d.ts new file mode 100644 index 0000000000..546e099e5d --- /dev/null +++ b/types/fibjs/declare/Fiber.d.ts @@ -0,0 +1,77 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 纤程操作对象,此对象不可直接创建 + * @detail 使用 coroutine.start 创建纤程后,将返回此对象,用于纤程处理和纤程间通信。,纤程主函数可以通过 this 访问本纤程对象,也可通过 coroutine.current 获取当前纤程。,```JavaScript,function func(v1),{, console.log(v1 + this.v);,},,var fb = coroutine.start(func,100);,,fb.v = 123;,,fb.join();,```,,纤程局部存储通过共享的 Fiber 对象完成,通过 coroutine.current 获取当前纤程,通过修改和查询其变量达到共享数据的目的。,,```JavaScript,function func(),{, console.log(coroutine.current().v);,},,coroutine.current().v = 100;,,func();,```,,纤程在创建时,会自动复制当前纤程的局部变量到新的纤程,之后,各自的局部变量的修改不会相互影响,除非变量本身为对象引用。,,```JavaScript,function func(),{, console.log(coroutine.current().v);,},,coroutine.current().v = 100;,,var fb = coroutine.start(func);,,coroutine.current().v = 200;,,fb.join();,``` + */ + +declare class Class_Fiber extends Class__object { + + /** + * class prop + * + * + * @brief 查询纤程的唯一 id + * + * @readonly + * @type Long + */ + + id: number + + /** + * class prop + * + * + * @brief 查询纤程的调用纤程 + * + * @readonly + * @type Fiber + */ + + caller: Class_Fiber + + /** + * class prop + * + * + * @brief 查询纤程的调用堆栈 + * + * @readonly + * @type String + */ + + stack: string + + + + /** + * + * @brief 等待纤程结束 + * + * + */ + join(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/File.d.ts b/types/fibjs/declare/File.d.ts new file mode 100644 index 0000000000..bf42f7f8b0 --- /dev/null +++ b/types/fibjs/declare/File.d.ts @@ -0,0 +1,67 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 文件操作对象,用于二进制文件读写 + * @detail 文件操作对象用于对二进制文件进行操作,可使用 fs 模块打开和创建文件:,```JavaScript,var f = fs.openFile('test.txt');,``` + */ +/// +declare class Class_File extends Class_SeekableStream { + + /** + * class prop + * + * + * @brief 查询当前文件名 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 查询当前文件描述符 + * + * @readonly + * @type Integer + */ + + fd: number + + + + /** + * + * @brief 查询当前文件的访问权限,Windows 不支持此方法 + * @param mode 指定设定的访问权限 + * + * + * @async + */ + chmod(mode: number): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Handler.d.ts b/types/fibjs/declare/Handler.d.ts new file mode 100644 index 0000000000..1dcae285f5 --- /dev/null +++ b/types/fibjs/declare/Handler.d.ts @@ -0,0 +1,74 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 消息处理器接口 + * @detail + */ + +declare class Class_Handler extends Class__object { + + + + /** + * + * @brief 构造一个消息处理器链处理对象 + * @param hdlrs 处理器数组 + * + * + * + */ + constructor(hdlrs: any[]); + + /** + * + * @brief 创建一个消息处理器路由对象 + * @param map 初始化路由参数 + * + * + * + */ + constructor(map: Object); + + /** + * + * @brief 创建一个 JavaSvript 消息处理器 + * @param hdlr JavaScript 处理器函数 + * + * + * + */ + constructor(hdlr: Function); + + /** + * + * @brief 处理一个消息或对象 + * @param v 指定处理的消息或对象 + * @return 返回下一步的处理器 + * + * + * @async + */ + invoke(v: Class__object): Class_Handler; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HandlerEx.d.ts b/types/fibjs/declare/HandlerEx.d.ts new file mode 100644 index 0000000000..1e95e65335 --- /dev/null +++ b/types/fibjs/declare/HandlerEx.d.ts @@ -0,0 +1,90 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 扩展消息处理器接口 + * @detail + */ +/// +declare class Class_HandlerEx extends Class_Handler { + + /** + * class prop + * + * + * @brief WebSocket 协议转换处理器当前事件处理接口对象 + * + * + * @type Handler + */ + + handler: Class_Handler + + /** + * class prop + * + * + * @brief 查询 WebSocket 包协议转换处理器的工作状态 + * + * 返回的结果为一个 Stats 对象,结构如下: + * ```JavaScript + * { + * total : 1000, // 总计处理的请求 + * pendding : 100, // 当前正在处理的请求 + * request : 10, // 新建的请求 + * response : 10, // 发送的响应 + * error : 100 // 发生的错误 + * } + * ``` + * + * + * @readonly + * @type Stats + */ + + stats: Class_Stats + + + + /** + * + * @brief 设置错误处理器 + * + * 使用方式: + * ```JavaScript + * hdlr.onerror({ + * "404": function(v) + * { + * ... + * }, + * "500": new mq.Routing(...) + * }) + * ``` + * @param hdlrs 指定不同的错误的处理器,key 是错误号,value 是处理器,可以是内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + onerror(hdlrs: Object): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HeapGraphEdge.d.ts b/types/fibjs/declare/HeapGraphEdge.d.ts new file mode 100644 index 0000000000..55f301ba0d --- /dev/null +++ b/types/fibjs/declare/HeapGraphEdge.d.ts @@ -0,0 +1,97 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief HeapGraphEdge表示两个HeapGraphNode节点间的关联,从上游节点到下游节点 + * @detail + */ + +declare class Class_HeapGraphEdge extends Class__object { + + /** + * class prop + * + * + * @brief 下游节点的链接方式,可能的值: + * - profiler.Edge_ContextVariable, 函数中的变量 + * - profiler.Edge_Element, 数组中的元素 + * - profiler.Edge_Property, 有名对象的属性 + * - profiler.Edge_Internal, JS无法进入的链接 + * - profiler.Edge_Hidden, 指向需要事先计算出空间大小的节点 + * - profiler.Edge_Shortcut, 指向无法事先计算出空间大小的节点 + * - profiler.Edge_Weak, 一个弱引用(被GC忽视) + * + * + * @readonly + * @type Integer + */ + + type: number + + /** + * class prop + * + * + * @brief 链接名称 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 链接的描述 + * + * @readonly + * @type String + */ + + description: string + + + + /** + * + * @brief 获取HeapGraphEdge的上游HeapGraphNode节点 + * @return 返回源HeapGraphNode节点 + * + * + * + */ + getFromNode(): Class_HeapGraphNode; + + /** + * + * @brief 获取HeapGraphEdge的下游HeapGraphNode节点 + * @return 返回目的HeapGraphNode节点 + * + * + * + */ + getToNode(): Class_HeapGraphNode; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HeapGraphNode.d.ts b/types/fibjs/declare/HeapGraphNode.d.ts new file mode 100644 index 0000000000..bdecf5b967 --- /dev/null +++ b/types/fibjs/declare/HeapGraphNode.d.ts @@ -0,0 +1,120 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief HeapGraphNode表示堆视图中的一个节点 + * @detail + */ + +declare class Class_HeapGraphNode extends Class__object { + + /** + * class prop + * + * + * @brief 节点类型,可能的值: + * - profiler.Node_Hidden, 隐藏节点,当显示给用户时可以被过滤掉 + * - profiler.Node_Array, 数组 + * - profiler.Node_String, 字符串 + * - profiler.Node_Object, JS对象(字符串和数组除外) + * - profiler.Node_Code, 编译后的代码 + * - profiler.Node_Closure, 函数闭包 + * - profiler.Node_RegExp, 正则表达式 + * - profiler.Node_HeapNumber, 堆中排好序的数字 + * - profiler.Node_Native, Native对象(非v8堆上的) + * - profiler.Node_Synthetic, Synthetic对象 + * - profiler.Node_ConsString, 拼接的字符串 + * - profiler.Node_SlicedString, 分割的字符串 + * - profiler.Node_Symbol, 符号(ES6) + * - profiler.Node_SimdValue, 堆中排好序的SIMD值(ES7) + * + * + * @readonly + * @type Integer + */ + + type: number + + /** + * class prop + * + * + * @brief 节点名称 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 节点的描述 + * + * @readonly + * @type String + */ + + description: string + + /** + * class prop + * + * + * @brief 节点ID + * + * @readonly + * @type Integer + */ + + id: number + + /** + * class prop + * + * + * @brief 节点大小,单位为字节 + * + * @readonly + * @type Integer + */ + + shallowSize: number + + /** + * class prop + * + * + * @brief 子节点列表,由HeapGraphEdge类型对象组成 + * + * @readonly + * @type NArray + */ + + childs: any[] + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HeapSnapshot.d.ts b/types/fibjs/declare/HeapSnapshot.d.ts new file mode 100644 index 0000000000..8b2e797206 --- /dev/null +++ b/types/fibjs/declare/HeapSnapshot.d.ts @@ -0,0 +1,101 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief HeapSnapshots记录JS堆在某个时刻的状态 + * @detail + */ + +declare class Class_HeapSnapshot extends Class__object { + + /** + * class prop + * + * + * @brief 时间信息 + * + * @readonly + * @type Date + */ + + time: Date + + /** + * class prop + * + * + * @brief 堆视图的根节点 + * + * @readonly + * @type HeapGraphNode + */ + + root: Class_HeapGraphNode + + /** + * class prop + * + * + * @brief 堆视图节点组成的列表 + * + * @readonly + * @type NArray + */ + + nodes: any[] + + + + /** + * + * @brief 和指定的堆快照进行比较 + * @param before 待比较的堆快照 + * @return 返回堆快照的比较结果 + * + * + * + */ + diff(before: Class_HeapSnapshot): Object; + + /** + * + * @brief 根据ID获取堆视图节点 + * @param id 数字类型的节点ID + * @return 返回获取到的堆视图节点 + * + * + * + */ + getNodeById(id: number): Class_HeapGraphNode; + + /** + * + * @brief 根据指定名称保存HeapSnapshot + * @param fname 快照名称 + * + * + * @async + */ + save(fname: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpClient.d.ts b/types/fibjs/declare/HttpClient.d.ts new file mode 100644 index 0000000000..17520b37f0 --- /dev/null +++ b/types/fibjs/declare/HttpClient.d.ts @@ -0,0 +1,258 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http客户端对象 + * @detail http客户端对象模拟浏览器环境缓存cookie,并在访问url的时候携带对应的cookie,不同的http客户端对象是相互隔离的,提供http的request、get、post等方法。,用法如下:,,```JavaScript,var http = require('http');,var httpClient = new http.Client();,httpClient.request('GET', 'http://fibjs.org');,``` + */ + +declare class Class_HttpClient extends Class__object { + + /** + * class prop + * + * + * @brief 返回http客户端的 HttpCookie 对象列表 + * + * @readonly + * @type NArray + */ + + cookies: any[] + + /** + * class prop + * + * + * @brief 查询和设置超时时间 单位毫秒 + * + * + * @type Integer + */ + + timeout: number + + /** + * class prop + * + * + * @brief 查询和设置 body 最大尺寸,以 MB 为单位,缺省为 -1,不限制尺寸 + * + * + * @type Integer + */ + + maxBodySize: number + + /** + * class prop + * + * + * @brief cookie功能开关,默认开启 + * + * + * @type Boolean + */ + + enableCookie: boolean + + /** + * class prop + * + * + * @brief 自动redirect功能开关,默认开启 + * + * + * @type Boolean + */ + + autoRedirect: boolean + + /** + * class prop + * + * + * @brief 查询和设置 http 请求中的浏览器标识 + * + * + * @type String + */ + + userAgent: string + + + + /** + * + * @brief HttpClient 构造函数,创建一个新的HttpClient对象 + * + * + */ + constructor(); + + /** + * + * @brief 发送 http 请求到指定的流对象,并返回结果 + * @param conn 指定处理请求的流对象 + * @param req 要发送的 HttpRequest 对象 + * @return 返回服务器响应 + * + * + * @async + */ + request(conn: Class_Stream, req: Class_HttpRequest): Class_HttpResponse; + + /** + * + * @brief 请求指定的 url,并返回结果 + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param method 指定 http 请求方法:GET, POST 等 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + request(method: string, url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 GET 方法请求指定的 url,并返回结果,等同于 request("GET", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + get(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 POST 方法请求指定的 url,并返回结果,等同于 request("POST", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + post(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 DELETE 方法请求指定的 url,并返回结果,等同于 request("DELETE", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + del(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 PUT 方法请求指定的 url,并返回结果,等同于 request("PUT", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + put(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 PATCH 方法请求指定的 url,并返回结果,等同于 request("PATCH", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + patch(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpCollection.d.ts b/types/fibjs/declare/HttpCollection.d.ts new file mode 100644 index 0000000000..631e9a3717 --- /dev/null +++ b/types/fibjs/declare/HttpCollection.d.ts @@ -0,0 +1,126 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 容器对象,用于 http header,cookie,query,form,等数据的存储与组织 + * @detail + */ + +declare class Class_HttpCollection extends Class__object { + + + + /** + * + * @brief 清除容器数据 + * + * + */ + clear(): void; + + /** + * + * @brief 检查容器内是否存在指定键值的数据 + * @param name 指定要检查的键值 + * @return 返回键值是否存在 + * + * + * + */ + has(name: string): boolean; + + /** + * + * @brief 查询指定键值的第一个值 + * @param name 指定要查询的键值 + * @return 返回键值所对应的值,若不存在,则返回 undefined + * + * + * + */ + first(name: string): any; + + /** + * + * @brief 查询指定键值的全部值 + * @param name 指定要查询的键值 + * @return 返回键值所对应全部值的数组,若数据不存在,则返回 null + * + * + * + */ + all(name: string): any[]; + + /** + * + * @brief 添加一个键值数据,添加数据并不修改已存在的键值的数据 + * @param map 指定要添加的键值数据字典 + * + * + * + */ + add(map: Object): void; + + /** + * + * @brief 添加一个键值数据,添加数据并不修改已存在的键值的数据 + * @param name 指定要添加的键值 + * @param value 指定要添加的数据 + * + * + * + */ + add(name: string, value: any): void; + + /** + * + * @brief 设定一个键值数据,设定数据将修改键值所对应的第一个数值,并清除相同键值的其余数据 + * @param map 指定要设定的键值数据字典 + * + * + * + */ + set(map: Object): void; + + /** + * + * @brief 设定一个键值数据,设定数据将修改键值所对应的第一个数值,并清除相同键值的其余数据 + * @param name 指定要设定的键值 + * @param value 指定要设定的数据 + * + * + * + */ + set(name: string, value: any): void; + + /** + * + * @brief 删除指定键值的全部值 + * @param name 指定要删除的键值 + * + * + * + */ + remove(name: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpCookie.d.ts b/types/fibjs/declare/HttpCookie.d.ts new file mode 100644 index 0000000000..7c3827de68 --- /dev/null +++ b/types/fibjs/declare/HttpCookie.d.ts @@ -0,0 +1,160 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http Cookie 对象,用于添加和处理 cookie + * @detail + */ + +declare class Class_HttpCookie extends Class__object { + + /** + * class prop + * + * + * @brief 查询和设置 cookie 名称 + * + * + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 查询和设置 cookie 的值 + * + * + * @type String + */ + + value: string + + /** + * class prop + * + * + * @brief 查询和设置 cookie 的域名范围 + * + * + * @type String + */ + + domain: string + + /** + * class prop + * + * + * @brief 查询和设置 cookie 的路径范围 + * + * + * @type String + */ + + path: string + + /** + * class prop + * + * + * @brief 查询和设置 cookie 的过期时间 + * + * + * @type Date + */ + + expires: Date + + /** + * class prop + * + * + * @brief 查询和设置 cookie 是否仅允许 http 请求,缺省 false + * + * + * @type Boolean + */ + + httpOnly: boolean + + /** + * class prop + * + * + * @brief 查询和设置 cookie 是否仅通过 https 传递,缺省 false + * + * + * @type Boolean + */ + + secure: boolean + + + + /** + * + * @brief HttpCookie 构造函数,创建一个新的 HttpCookie 对象 + * @param opts 指定创建的 cookie 的属性 + * + * + * + */ + constructor(opts?: Object/** = v8::Object::New(isolate)*/); + + /** + * + * @brief HttpCookie 构造函数,创建一个新的 HttpCookie 对象 + * @param name 指定创建的 cookie 名称 + * @param value 指定创建的 cookie 值 + * @param opts 指定创建的 cookie 的其它属性 + * + * + * + */ + constructor(name: string, value: string, opts?: Object/** = v8::Object::New(isolate)*/); + + /** + * + * @brief 解析给定的字符串,填充 cookie 对象 + * @param header 指定需要解析的 header 字符串 + * + * + * + */ + parse(header: string): void; + + /** + * + * @brief 检测给定的 url 是否匹配当前设置 + * @param url 指定测试的 url + * @return 匹配成功返回 true + * + * + * + */ + match(url: string): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpHandler.d.ts b/types/fibjs/declare/HttpHandler.d.ts new file mode 100644 index 0000000000..6ab5067b29 --- /dev/null +++ b/types/fibjs/declare/HttpHandler.d.ts @@ -0,0 +1,101 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 协议转换处理器 + * @detail 用以将数据流转换为 http 协议消息,创建方式:,```JavaScript,var hdlr = new mq.HttpHandler(...);,```,或者:,```JavaScript,var hdlr = new http.Handler(...);,``` + */ +/// +declare class Class_HttpHandler extends Class_HandlerEx { + + /** + * class prop + * + * + * @brief 查询和设置是否允强制使用 gzip 压缩输出,缺省为 false + * + * + * @type Boolean + */ + + forceGZIP: boolean + + /** + * class prop + * + * + * @brief 查询和设置最大请求头个数,缺省为 128 + * + * + * @type Integer + */ + + maxHeadersCount: number + + /** + * class prop + * + * + * @brief 查询和设置 body 最大尺寸,以 MB 为单位,缺省为 64 + * + * + * @type Integer + */ + + maxBodySize: number + + /** + * class prop + * + * + * @brief 查询和设置服务器名称,缺省为:fibjs/0.x.0 + * + * + * @type String + */ + + serverName: string + + + + /** + * + * @brief 创建一个 http 协议处理器对象,将流对象的数据转变为 http 消息对象 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(hdlr: Class_Handler); + + /** + * + * @brief 允许跨域请求 + * @param allowHeaders 指定接受的 http 头字段 + * + * + * + */ + enableCrossOrigin(allowHeaders?: string/** = "Content-Type"*/): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpMessage.d.ts b/types/fibjs/declare/HttpMessage.d.ts new file mode 100644 index 0000000000..1e745b0529 --- /dev/null +++ b/types/fibjs/declare/HttpMessage.d.ts @@ -0,0 +1,202 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 基础消息对象 + * @detail + */ +/// +declare class Class_HttpMessage extends Class_Message { + + /** + * class prop + * + * + * @brief 协议版本信息,允许的格式为:HTTP/#.# + * + * + * @type String + */ + + protocol: string + + /** + * class prop + * + * + * @brief 包含消息中 http 消息头的容器,只读属性 + * + * @readonly + * @type HttpCollection + */ + + headers: Class_HttpCollection + + /** + * class prop + * + * + * @brief 查询和设定是否保持连接 + * + * + * @type Boolean + */ + + keepAlive: boolean + + /** + * class prop + * + * + * @brief 查询和设定是否是升级协议 + * + * + * @type Boolean + */ + + upgrade: boolean + + /** + * class prop + * + * + * @brief 查询和设置最大请求头个数,缺省为 128 + * + * + * @type Integer + */ + + maxHeadersCount: number + + /** + * class prop + * + * + * @brief 查询和设置 body 最大尺寸,以 MB 为单位,缺省为 64 + * + * + * @type Integer + */ + + maxBodySize: number + + /** + * class prop + * + * + * @brief 查询当前对象的来源 socket + * + * @readonly + * @type Stream + */ + + socket: Class_Stream + + + + /** + * + * @brief 检查是否存在指定键值的消息头 + * @param name 指定要检查的键值 + * @return 返回键值是否存在 + * + * + * + */ + hasHeader(name: string): boolean; + + /** + * + * @brief 查询指定键值的第一个消息头 + * @param name 指定要查询的键值 + * @return 返回键值所对应的值,若不存在,则返回 undefined + * + * + * + */ + firstHeader(name: string): any; + + /** + * + * @brief 查询指定键值的全部消息头 + * @param name 指定要查询的键值 + * @return 返回键值所对应全部值的数组,若数据不存在,则返回 null + * + * + * + */ + allHeader(name: string): any[]; + + /** + * + * @brief 添加一个消息头,添加数据并不修改已存在的键值的消息头 + * @param map 指定要添加的键值数据字典 + * + * + * + */ + addHeader(map: Object): void; + + /** + * + * @brief 添加一个消息头,添加数据并不修改已存在的键值的消息头 + * @param name 指定要添加的键值 + * @param value 指定要添加的数据 + * + * + * + */ + addHeader(name: string, value: any): void; + + /** + * + * @brief 设定一个消息头,设定数据将修改键值所对应的第一个数值,并清除相同键值的其余消息头 + * @param map 指定要设定的键值数据字典 + * + * + * + */ + setHeader(map: Object): void; + + /** + * + * @brief 设定一个消息头,设定数据将修改键值所对应的第一个数值,并清除相同键值的其余消息头 + * @param name 指定要设定的键值 + * @param value 指定要设定的数据 + * + * + * + */ + setHeader(name: string, value: any): void; + + /** + * + * @brief 删除指定键值的全部消息头 + * @param name 指定要删除的键值 + * + * + * + */ + removeHeader(name: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpRequest.d.ts b/types/fibjs/declare/HttpRequest.d.ts new file mode 100644 index 0000000000..20a129129e --- /dev/null +++ b/types/fibjs/declare/HttpRequest.d.ts @@ -0,0 +1,125 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 请求消息对象 + * @detail + */ +/// +declare class Class_HttpRequest extends Class_HttpMessage { + + /** + * class prop + * + * + * @brief 获取响应消息对象 + * + * @readonly + * @type HttpResponse + */ + + response: Class_HttpResponse + + /** + * class prop + * + * + * @brief 查询和设置请求方法 + * + * + * @type String + */ + + method: string + + /** + * class prop + * + * + * @brief 查询和设置请求地址 + * + * + * @type String + */ + + address: string + + /** + * class prop + * + * + * @brief 查询和设置请求查询字符串 + * + * + * @type String + */ + + queryString: string + + /** + * class prop + * + * + * @brief 获取包含消息 cookies 的容器 + * + * @readonly + * @type HttpCollection + */ + + cookies: Class_HttpCollection + + /** + * class prop + * + * + * @brief 获取包含消息 form 的容器 + * + * @readonly + * @type HttpCollection + */ + + form: Class_HttpCollection + + /** + * class prop + * + * + * @brief 获取包含消息 query 的容器 + * + * @readonly + * @type HttpCollection + */ + + query: Class_HttpCollection + + + + /** + * + * @brief HttpRequest 构造函数,创建一个新的 HttpRequest 对象 + * + * + */ + constructor(); + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpResponse.d.ts b/types/fibjs/declare/HttpResponse.d.ts new file mode 100644 index 0000000000..b7a3ac4aaa --- /dev/null +++ b/types/fibjs/declare/HttpResponse.d.ts @@ -0,0 +1,130 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 响应消息对象 + * @detail + */ +/// +declare class Class_HttpResponse extends Class_HttpMessage { + + /** + * class prop + * + * + * @brief 查询和设置响应消息的返回状态 + * + * + * @type Integer + */ + + statusCode: number + + /** + * class prop + * + * + * @brief 查询和设置响应消息的返回消息 + * + * + * @type String + */ + + statusMessage: string + + /** + * class prop + * + * + * @brief 返回当前消息的 HttpCookie 对象列表 + * + * @readonly + * @type NArray + */ + + cookies: any[] + + + + /** + * + * @brief HttpResponse 构造函数,创建一个新的 HttpResponse 对象 + * + * + */ + constructor(); + + /** + * + * @brief 设置响应消息的返回状态,返回消息,并添加响应头 + * @param statusCode 指定响应消息的返回状态 + * @param statusMessage 指定响应消息的返回消息 + * @param headers 指定响应消息添加的响应头 + * + * + * + */ + writeHead(statusCode: number, statusMessage: string, headers?: Object/** = v8::Object::New(isolate)*/): void; + + /** + * + * @brief 设置响应消息的返回状态,返回消息,并添加响应头 + * @param statusCode 指定响应消息的返回状态 + * @param headers 指定响应消息添加的响应头 + * + * + * + */ + writeHead(statusCode: number, headers?: Object/** = v8::Object::New(isolate)*/): void; + + /** + * + * @brief 向 cookies 添加一个 HttpCookie 对象 + * @param cookie 指定要添加的 HttpCookie 对象 + * + * + * + */ + addCookie(cookie: Class_HttpCookie): void; + + /** + * + * @brief 发送重定向到客户端 + * @param url 重定向的地址 + * + * + * + */ + redirect(url: string): void; + + /** + * + * @brief 仅发送格式化 http 头到给定的流对象 + * @param stm 指定接收格式化消息的流对象 + * + * + * @async + */ + sendHeader(stm: Class_Stream): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpServer.d.ts b/types/fibjs/declare/HttpServer.d.ts new file mode 100644 index 0000000000..1ef964bb09 --- /dev/null +++ b/types/fibjs/declare/HttpServer.d.ts @@ -0,0 +1,162 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief http 服务器对象 + * @detail http 服务器对象是将 TcpServer 和 HttpHandler 组合封装的对象,方便快速搭建服务器,逻辑上相当于:,```JavaScript,var svr = new net.TcpServer(addr, port, new http.Handler(function(req){, ...,}));,```,,创建方法:,```JavaScript,var http = require("http");,var svr = new http.Server(80, function(req){, ...,});,``` + */ +/// +declare class Class_HttpServer extends Class_TcpServer { + + /** + * class prop + * + * + * @brief 查询和设置是否允强制使用 gzip 压缩输出,缺省为 false + * + * + * @type Boolean + */ + + forceGZIP: boolean + + /** + * class prop + * + * + * @brief 查询和设置最大请求头个数,缺省为 128 + * + * + * @type Integer + */ + + maxHeadersCount: number + + /** + * class prop + * + * + * @brief 查询和设置 body 最大尺寸,以 MB 为单位,缺省为 64 + * + * + * @type Integer + */ + + maxBodySize: number + + /** + * class prop + * + * + * @brief 查询和设置服务器名称,缺省为:fibjs/0.x.0 + * + * + * @type String + */ + + serverName: string + + /** + * class prop + * + * + * @brief 查询 http 协议转换处理器的工作状态 + * + * 返回的结果为一个 Stats 对象,结构如下: + * ```JavaScript + * { + * total : 1000, // 总计处理的请求 + * pendding : 100, // 当前正在处理的请求 + * request : 10, // 新建的请求 + * response : 10, // 发送的响应 + * error : 100, // 发生的错误(不计入 404) + * error_400 : 10, // 发生的请求错误 + * error_404 : 12, // 文件未找到的数量 + * error_500 : 2 // 内部处理错误 + * } + * ``` + * + * + * @readonly + * @type Stats + */ + + httpStats: Class_Stats + + + + /** + * + * @brief HttpServer 构造函数,在所有本机地址侦听 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(port: number, hdlr: Class_Handler); + + /** + * + * @brief HttpServer 构造函数 + * @param addr 指定 http 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(addr: string, port: number, hdlr: Class_Handler); + + /** + * + * @brief 设置错误处理器 + * + * 使用方式: + * ```JavaScript + * hdlr.onerror({ + * "404": function(v) + * { + * ... + * }, + * "500": new mq.Routing(...) + * }) + * ``` + * @param hdlrs 指定不同的错误的处理器,key 是错误号,value 是处理器,可以是内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + onerror(hdlrs: Object): void; + + /** + * + * @brief 允许跨域请求 + * @param allowHeaders 指定接受的 http 头字段 + * + * + * + */ + enableCrossOrigin(allowHeaders?: string/** = "Content-Type"*/): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpUploadData.d.ts b/types/fibjs/declare/HttpUploadData.d.ts new file mode 100644 index 0000000000..8d88b2b125 --- /dev/null +++ b/types/fibjs/declare/HttpUploadData.d.ts @@ -0,0 +1,81 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 包含 multipart 的一个条目数据 + * @detail + */ + +declare class Class_HttpUploadData extends Class__object { + + /** + * class prop + * + * + * @brief 包含本条目数据的文件名 + * + * @readonly + * @type String + */ + + fileName: string + + /** + * class prop + * + * + * @brief 包含本条目数据的类型 + * + * @readonly + * @type String + */ + + contentType: string + + /** + * class prop + * + * + * @brief 包含本条目数据的传输编码类型 + * + * @readonly + * @type String + */ + + contentTransferEncoding: string + + /** + * class prop + * + * + * @brief 包含本条目数据部分的流对象 + * + * @readonly + * @type SeekableStream + */ + + body: Class_SeekableStream + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/HttpsServer.d.ts b/types/fibjs/declare/HttpsServer.d.ts new file mode 100644 index 0000000000..2213c7c4c6 --- /dev/null +++ b/types/fibjs/declare/HttpsServer.d.ts @@ -0,0 +1,137 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief https 服务器对象 + * @detail https 服务器对象是将 SslServer 和 HttpHandler 组合封装的对象,方便快速搭建服务器,逻辑上相当于:,```JavaScript,var svr = new net.SslServer(crt, key, addr, port, new http.Handler(function(req){, ...,}));,```,,创建方法:,```JavaScript,var http = require("http");,var svr = new http.HttpsServer(crt, key, 443, function(req){, ...,});,``` + */ +/// +declare class Class_HttpsServer extends Class_HttpServer { + + /** + * class prop + * + * + * @brief 设定证书验证模式,缺省为 VERIFY_NONE + * + * + * @type Integer + */ + + verification: number + + /** + * class prop + * + * + * @brief 客户端证书验证 ca + * + * @readonly + * @type X509Cert + */ + + ca: Class_X509Cert + + + + /** + * + * @brief HttpsServer 构造函数,在所有本机地址侦听 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 + * + * + * + */ + constructor(certs: any[], port: number, hdlr: Class_Handler); + + /** + * + * @brief HttpsServer 构造函数 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * @param addr 指定 http 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 + * + * + * + */ + constructor(certs: any[], addr: string, port: number, hdlr: Class_Handler); + + /** + * + * @brief HttpsServer 构造函数,在所有本机地址侦听 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey, port: number, hdlr: Class_Handler); + + /** + * + * @brief HttpsServer 构造函数 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * @param addr 指定 http 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 http 服务器侦听端口 + * @param hdlr http 内置消息处理器,处理函数,链式处理数组,路由对象,详见 + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey, addr: string, port: number, hdlr: Class_Handler); + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Image.d.ts b/types/fibjs/declare/Image.d.ts new file mode 100644 index 0000000000..ff88443b70 --- /dev/null +++ b/types/fibjs/declare/Image.d.ts @@ -0,0 +1,856 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + + + +/** module Or Internal Object */ +/** + * @brief 图像处理对象,用以对图像进行转换,绘制,存储等操作 + * @detail Image 对象属于 gd 模块,创建:,```JavaScript,var img = gd.create(640, 480);,var img1 = gd.load(data);,``` + */ + +declare class Class_Image extends Class__object { + + /** + * class prop + * + * + * @brief 查询图像宽度 + * + * @readonly + * @type Integer + */ + + width: number + + /** + * class prop + * + * + * @brief 查询图像高度 + * + * @readonly + * @type Integer + */ + + height: number + + /** + * class prop + * + * + * @brief 查询图像来源格式,结果为 gd.PNG, gd.JPEG, gd.GIF, gd.BMP, gd.WEBP + * + * @readonly + * @type Integer + */ + + format: number + + /** + * class prop + * + * + * @brief 查询图像类型,结果为 gd.TRUECOLOR, gd.PALETTE + * + * @readonly + * @type Integer + */ + + type: number + + /** + * class prop + * + * + * @brief 查询图像颜色表内的颜色总数 + * + * @readonly + * @type Integer + */ + + colorsTotal: number + + /** + * class prop + * + * + * @brief 查询和设定指定的颜色为透明色 + * + * + * @type Integer + */ + + transparent: number + + /** + * class prop + * + * + * @brief 查询和设定图像是否渐进式,仅支持 jpeg 格式时 + * + * + * @type Boolean + */ + + progressive: boolean + + /** + * class prop + * + * + * @brief查询和设定绘图时是否计算 alpha 层,缺省为 true + * + * + * @type Boolean + */ + + alphaBlending: boolean + + + + /** + * + * @brief 按照指定的格式返回图像数据 + * @param format 指定返回数据的格式,允许值为 gd.PNG, gd.JPEG, gd.GIF, gd.BMP, gd.WEBP, 缺省为 gd.PNG + * @param quality 当格式为 gd.JPEG 或 gd.WEBP 时用于指定压缩质量,缺省为 85,其他格式忽略此参数 + * @return 返回格式化的数据 + * + * + * @async + */ + getData(format?: number/** = undefined*/, quality?: number/** = 85*/): Class_Buffer; + + /** + * + * @brief 按照指定的格式将图像数据存入流对象 + * @param stm 指定要存入的流对象 + * @param format 指定返回数据的格式,允许值为 gd.PNG, gd.JPEG, gd.GIF, gd.BMP, gd.WEBP, 缺省为 gd.PNG + * @param quality 当格式为 gd.JPEG 或 gd.WEBP 时用于指定压缩质量,缺省为 85,其他格式忽略此参数 + * + * + * @async + */ + save(stm: Class_Stream, format?: number/** = undefined*/, quality?: number/** = 85*/): void; + + /** + * + * @brief 按照指定的格式将图像数据存入指定文件,文件将被强制覆盖 + * @param fname 指定文件名 + * @param format 指定返回数据的格式,允许值为 gd.PNG, gd.JPEG, gd.GIF, gd.BMP, gd.WEBP, 缺省为 gd.PNG + * @param quality 当格式为 gd.JPEG 时用于指定压缩质量,缺省为 85,其他格式忽略此参数 + * + * + * @async + */ + save(fname: string, format?: number/** = undefined*/, quality?: number/** = 85*/): void; + + /** + * + * @brief 为指定的颜色申请一个颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorAllocate(red: number, green: number, blue: number): number; + + /** + * + * @brief 为指定的颜色申请一个颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorAllocate(color: number): number; + + /** + * + * @brief 为指定的颜色及透明申请一个颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @param alpha 透明分量,范围为 0-1.0 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorAllocateAlpha(red: number, green: number, blue: number, alpha: number): number; + + /** + * + * @brief 为指定的颜色及透明申请一个颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorAllocateAlpha(color: number): number; + + /** + * + * @brief 为指定的颜色查找一个最接近的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosest(red: number, green: number, blue: number): number; + + /** + * + * @brief 为指定的颜色查找一个最接近的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosest(color: number): number; + + /** + * + * @brief 为指定的颜色查找一个最接近的颜色号,此方法使用 Hue/White/Black 计算查找最接近颜色,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosestHWB(red: number, green: number, blue: number): number; + + /** + * + * @brief 为指定的颜色查找一个最接近的颜色号,此方法使用 Hue/White/Black 计算查找最接近颜色,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosestHWB(color: number): number; + + /** + * + * @brief 为指定的颜色及透明查找一个最接近的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @param alpha 透明分量,范围为 0-1.0 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosestAlpha(red: number, green: number, blue: number, alpha: number): number; + + /** + * + * @brief 为指定的颜色及透明查找一个最接近的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorClosestAlpha(color: number): number; + + /** + * + * @brief 查找指定的颜色对应的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorExact(red: number, green: number, blue: number): number; + + /** + * + * @brief 查找指定的颜色对应的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorExact(color: number): number; + + /** + * + * @brief 查找指定的颜色及透明对应的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @param alpha 透明分量,范围为 0-1.0 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorExactAlpha(red: number, green: number, blue: number, alpha: number): number; + + /** + * + * @brief 查找指定的颜色及透明对应的颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorExactAlpha(color: number): number; + + /** + * + * @brief 查找指定的颜色对应的颜色号,如果颜色不存在,则为其申请一个新颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorResolve(red: number, green: number, blue: number): number; + + /** + * + * @brief 查找指定的颜色对应的颜色号,如果颜色不存在,则为其申请一个新颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgb 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorResolve(color: number): number; + + /** + * + * @brief 查找指定的颜色及透明对应的颜色号,如果颜色不存在,则为其申请一个新颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @param alpha 透明分量,范围为 0-1.0 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorResolveAlpha(red: number, green: number, blue: number, alpha: number): number; + + /** + * + * @brief 查找指定的颜色及透明对应的颜色号,如果颜色不存在,则为其申请一个新颜色号,对于 gd.PALETTE 图像,颜色号为调色板索引,对于 gd.TRUECOLOR 图像,颜色号为 rgba 编码数值 + * @param color 组合颜色值,可由 gd.color, gb.rgb, gd.rgba 等函数生成 + * @return 返回颜色号,不成功返回 -1 + * + * + * + */ + colorResolveAlpha(color: number): number; + + /** + * + * @brief 释放指定的颜色号,释放的颜色号将会被再次申请后替换 + * @param color 指定要释放的颜色号 + * + * + * + */ + colorDeallocate(color: number): void; + + /** + * + * @brief 设定绘图的剪切窗口,设定后,所有的绘制将被剪切在窗口内部 + * @param x1 剪切窗口的左上 x 坐标 + * @param y1 剪切窗口的左上 y 坐标 + * @param x2 剪切窗口的右下 x 坐标 + * @param y2 剪切窗口的右下 y 坐标 + * + * + * + */ + clip(x1: number, y1: number, x2: number, y2: number): void; + + /** + * + * @brief 查询指定位置点的颜色 + * @param x 指定查询的 x 坐标 + * @param y 指定查询的 y 坐标 + * @return 返回指定点的颜色号 + * + * + * + */ + getPixel(x: number, y: number): number; + + /** + * + * @brief 查询指定位置点的真彩色颜色 + * @param x 指定查询的 x 坐标 + * @param y 指定查询的 y 坐标 + * @return 返回指定点的颜色号 + * + * + * + */ + getTrueColorPixel(x: number, y: number): number; + + /** + * + * @brief 在指定位置画一个点 + * @param x 指定画点的 x 坐标 + * @param y 指定画点的 y 坐标 + * @param color 指定画点的颜色号 + * + * + * + */ + setPixel(x: number, y: number, color: number): void; + + /** + * + * @brief 设定画线的宽度,line, rectangle, arc 等方法画线时缺省宽度为一个像素,可使用此方法改变线的宽度 + * @param thickness 画线的宽度 + * + * + * + */ + setThickness(thickness: number): void; + + /** + * + * @brief 在指定的位置画一条线 + * @param x1 指定画线的起始 x 坐标 + * @param y1 指定画线的起始 y 坐标 + * @param x2 指定画线的结束 x 坐标 + * @param y2 指定画线的结束 y 坐标 + * @param color 指定画线的颜色号 + * + * + * + */ + line(x1: number, y1: number, x2: number, y2: number, color: number): void; + + /** + * + * @brief 在指定的位置画一个矩形 + * @param x1 指定左上角 x 坐标 + * @param y1 指定左上角 y 坐标 + * @param x2 指定右下角 x 坐标 + * @param y2 指定右下角 y 坐标 + * @param color 指定矩形的颜色号 + * + * + * + */ + rectangle(x1: number, y1: number, x2: number, y2: number, color: number): void; + + /** + * + * @brief 在指定的位置画一个填充的矩形 + * @param x1 指定左上角 x 坐标 + * @param y1 指定左上角 y 坐标 + * @param x2 指定右下角 x 坐标 + * @param y2 指定右下角 y 坐标 + * @param color 指定矩形的颜色号 + * + * + * + */ + filledRectangle(x1: number, y1: number, x2: number, y2: number, color: number): void; + + /** + * + * @brief 根据给定的点绘制一个多边形 + * @param points 包含多边形点的数组,如 [[1, 1], [1, 10], [10, 15], [10, 20]] + * @param color 指定矩形的颜色号 + * + * + * + */ + polygon(points: any[], color: number): void; + + /** + * + * @brief 根据给定的点绘制一个开放多边形 + * @param points 包含多边形点的数组,如 [[1, 1], [1, 10], [10, 15], [10, 20]] + * @param color 指定矩形的颜色号 + * + * + * + */ + openPolygon(points: any[], color: number): void; + + /** + * + * @brief 根据给定的点绘制一个填充多边形 + * @param points 包含多边形点的数组,如 [[1, 1], [1, 10], [10, 15], [10, 20]] + * @param color 指定矩形的颜色号 + * + * + * + */ + filledPolygon(points: any[], color: number): void; + + /** + * + * @brief 画一个椭圆 + * @param x 椭圆中心的 x 坐标 + * @param y 椭圆中心的 y 坐标 + * @param width 椭圆的宽度 + * @param height 椭圆的高度 + * @param color 指定矩形的颜色号 + * + * + * + */ + ellipse(x: number, y: number, width: number, height: number, color: number): void; + + /** + * + * @brief 画一个填充的椭圆 + * @param x 椭圆中心的 x 坐标 + * @param y 椭圆中心的 y 坐标 + * @param width 椭圆的宽度 + * @param height 椭圆的高度 + * @param color 指定矩形的颜色号 + * + * + * + */ + filledEllipse(x: number, y: number, width: number, height: number, color: number): void; + + /** + * + * @brief 画一个扇形 + * @param x 扇形中心的 x 坐标 + * @param y 扇形中心的 y 坐标 + * @param width 扇形所在椭圆的宽度 + * @param height 扇形所在椭圆的高度 + * @param start 扇形开始的角度,范围为 0-360 + * @param end 扇形结束的角度,范围为 0-360 + * @param color 指定矩形的颜色号 + * + * + * + */ + arc(x: number, y: number, width: number, height: number, start: number, end: number, color: number): void; + + /** + * + * @brief 画一个填充扇形 + * @param x 扇形中心的 x 坐标 + * @param y 扇形中心的 y 坐标 + * @param width 扇形所在椭圆的宽度 + * @param height 扇形所在椭圆的高度 + * @param start 扇形开始的角度,范围为 0-360 + * @param end 扇形结束的角度,范围为 0-360 + * @param color 指定矩形的颜色号 + * @param style 指定扇形的样式,允许的值有 gd.ARC, gd.CHORD, gd.NOFILL, gd.EDGED 及其组合 + * + * + * + */ + filledArc(x: number, y: number, width: number, height: number, start: number, end: number, color: number, style?: number/** = undefined*/): void; + + /** + * + * @brief 从指定的点开始填充封闭区域 + * @param x 开始填充的 x 坐标 + * @param y 开始填充的 y 坐标 + * @param color 指定填充的颜色号 + * + * + * + */ + fill(x: number, y: number, color: number): void; + + /** + * + * @brief 从指定的点开始在指定颜色的边框内填充封闭区域 + * @param x 开始填充的 x 坐标 + * @param y 开始填充的 y 坐标 + * @param borderColor 指定边框的颜色号 + * @param color 指定填充的颜色号 + * + * + * + */ + fillToBorder(x: number, y: number, borderColor: number, color: number): void; + + /** + * + * @brief 替换图像中指定的颜色为新颜色 + * @param src 指定要替换的颜色 + * @param dst 指定新颜色 + * + * + * @async + */ + colorReplace(src: number, dst: number): void; + + /** + * + * @brief 复制当前图像为一个新图像 + * @return 返回复制的新图像对象 + * + * + * @async + */ + clone(): Class_Image; + + /** + * + * @brief 根据图像拉伸生成一个新尺寸的图像 + * @param width 指定拉伸的宽度 + * @param height 指定拉伸的高度 + * @return 返回新图像对象 + * + * + * @async + */ + resample(width: number, height: number): Class_Image; + + /** + * + * @brief 剪切图像的一部分为一个新的图像 + * @param x 剪切窗口的左上 x 坐标 + * @param y 剪切窗口的左上 y 坐标 + * @param width 剪切窗口的宽度 + * @param height 剪切窗口的高度 + * @return 返回剪切出的图像 + * + * + * @async + */ + crop(x: number, y: number, width: number, height: number): Class_Image; + + /** + * + * @brief 镜像当前图像 + * @param dir 镜像方向,允许值为 gd.BOTH,gd.HORIZONTAL, gd.VERTICAL, 缺省为 gd.HORIZONTAL + * + * + * @async + */ + flip(dir?: number/** = undefined*/): void; + + /** + * + * @brief 旋转当前图像 + * @param dir 旋转方向,允许值为 gd.LEFT, gd.RIGHT + * + * + * @async + */ + rotate(dir: number): void; + + /** + * + * @brief 转换当前图像类型 + * @param color 指定图像类型,允许值为 gd.TRUECOLOR 或 gd.PALETTE + * + * + * @async + */ + convert(color?: number/** = undefined*/): void; + + /** + * + * @brief 从一个图像中复制一个区域到指定的位置 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param width 指定复制的宽度 + * @param height 指定复制的高度 + * + * + * @async + */ + copy(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, width: number, height: number): void; + + /** + * + * @brief 从一个图像中复制一个区域覆盖到指定的位置 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param width 指定复制的宽度 + * @param height 指定复制的高度 + * @param percent 指定覆盖的透明度 + * + * + * @async + */ + copyMerge(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, width: number, height: number, percent: number): void; + + /** + * + * @brief 从一个图像中复制一个区域的灰度覆盖到指定的位置 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param width 指定复制的宽度 + * @param height 指定复制的高度 + * @param percent 指定覆盖的透明度 + * + * + * @async + */ + copyMergeGray(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, width: number, height: number, percent: number): void; + + /** + * + * @brief 将一个图像中的一个区域拉伸后复制到指定的位置 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param dstW 指定复制的拉伸宽度 + * @param dstH 指定复制的拉伸高度 + * @param srcW 指定复制的源宽度 + * @param srcH 指定复制的源高度 + * + * + * @async + */ + copyResized(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, dstW: number, dstH: number, srcW: number, srcH: number): void; + + /** + * + * @brief 将一个图像中的一个区域拉伸后复制到指定的位置,不同与 copyResized,此方法拉伸时会对图像进行抖动 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param dstW 指定复制的拉伸宽度 + * @param dstH 指定复制的拉伸高度 + * @param srcW 指定复制的源宽度 + * @param srcH 指定复制的源高度 + * + * + * @async + */ + copyResampled(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, dstW: number, dstH: number, srcW: number, srcH: number): void; + + /** + * + * @brief 将一个图像中的一个区域旋转后复制到指定的位置 + * @param source 源图像对象 + * @param dstX 指定复制目标的 x 坐标 + * @param dstY 指定复制目标的 y 坐标 + * @param srcX 指定复制源左上角的 x 坐标 + * @param srcY 指定复制源左上角的 y 坐标 + * @param width 指定复制的宽度 + * @param height 指定复制的高度 + * @param angle 指定旋转的角度 + * + * + * @async + */ + copyRotated(source: Class_Image, dstX: number, dstY: number, srcX: number, srcY: number, width: number, height: number, angle: number): void; + + /** + * + * @brief 把过滤器 filterType应用到图像上,根据过滤器类型传入所需参数 + * + * 参数 filterType 可以为以下数值: + * - MEAN_REMOVAL, 用平均移除法来达到轮廓效果 + * - EDGEDETECT, 用边缘检测来突出图像的边缘 + * - EMBOSS, 使图像浮雕化 + * - SELECTIVE_BLUR, 模糊图像 + * - GAUSSIAN_BLUR, 用高斯算法模糊图像 + * - NEGATE, 将图像中所有颜色反转 + * - GRAYSCALE, 将图像转换为灰度图 + * - SMOOTH, 使图像更柔滑,用arg1设定柔滑级别 + * - BRIGHTNESS, 改变图像的亮度,用arg1设定亮度级别,取值范围是-255~255 + * - CONTRAST, 改变图像的对比度,用arg1设定对比度级别,取值范围是0~100 + * - COLORIZE, 改变图像的色调,用arg1、arg2、arg3分别指定red、blue、green分值,每种颜色范围是0~255,arg4为透明度,取值返回是0~127 + * @param filterType 过滤器类型 + * @param arg1 过滤器所需参数: SMOOTH 的平滑级别、BRIGHTNESS 的亮度级别、CONTRAST 的对比度级别、COLORIZE 的 red 分值 + * @param arg2 过滤器所需参数: COLORIZE 的 green 分值 + * @param arg3 过滤器所需参数: COLORIZE 的 blue 分值 + * @param arg4 过滤器所需参数: COLORIZE 的透明度 alpha 分值 + * + * + * @async + */ + filter(filterType: number, arg1?: number/** = 0*/, arg2?: number/** = 0*/, arg3?: number/** = 0*/, arg4?: number/** = 0*/): void; + + /** + * + * @brief 根据给定的矩阵,对当前图像进行仿射 + * + * 参数 affine 是一个数组: + * ```JavaScript + * affine = [ a0, a1, b0, b1, a2, b2 ]; + * x' = a0x + a1y + a2; + * y' = b0x + b1y + b2; + * ``` + * @param affine 仿射矩阵,由 6 个 double 类型的数字组成 + * @param x 可选剪切区域的原点 x 坐标 + * @param y 可选剪切区域的原点 y 坐标 + * @param width 可选剪切区域的的宽度 + * @param height 可选剪切区域的的高度 + * @return 返回仿射后的图像 + * + * + * @async + */ + affine(affine: any[], x?: number/** = -1*/, y?: number/** = -1*/, width?: number/** = -1*/, height?: number/** = -1*/): Class_Image; + + /** + * + * @brief 对当前图像进行高斯模糊处理 + * @param radius 模糊半径 + * + * + * @async + */ + gaussianBlur(radius: number): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Int64.d.ts b/types/fibjs/declare/Int64.d.ts new file mode 100644 index 0000000000..3bba627aed --- /dev/null +++ b/types/fibjs/declare/Int64.d.ts @@ -0,0 +1,241 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 64位整数对象 + * @detail 创建方法:,```JavaScript,var n = new Int64(123);,``` + */ + +declare class Class_Int64 extends Class__object { + + /** + * class prop + * + * + * @brief 高 32 位数值 + * + * + * @type Long + */ + + hi: number + + /** + * class prop + * + * + * @brief 低 32 位数值 + * + * + * @type Long + */ + + lo: number + + + + /** + * + * @brief Int64 构造函数 + * @param num 初始化的值 + * + * + * + */ + constructor(num?: number/** = 0*/); + + /** + * + * @brief Int64 构造函数 + * @param hi 高32位数 + * @param lo 低32位数 + * + * + * + */ + constructor(hi: number, lo: number); + + /** + * + * @brief Int64 构造函数 + * @param num 初始化的值 + * + * + * + */ + constructor(num: Class_Int64); + + /** + * + * @brief Int64 构造函数 + * @param num 数字字符串 + * @param base 数字字符串的编码方式,可以接受 2-16, 32, 64,默认为 10,为 10 时自动识别 0x 编码 + * + * + * + */ + constructor(num: string, base?: number/** = 10*/); + + /** + * + * @brief 将 Int64 内的数值与给定数值比较大小 + * @param num 指定比较的数值 + * @return 返回 1 表示 Int64 内的数值比指定数值更大,0 表示相等,-1 表示更小 + * + * + * + */ + compare(num: Class_Int64): number; + + /** + * + * @brief 将 Int64 内的数值左移相应的位数,此操作不影响 Int64 原有数值 + * @param bits 指定移动的位数 + * @return 返回包含移位以后数值的对象 + * + * + * + */ + shiftLeft(bits: number): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值右移相应的位数,此操作不影响 Int64 原有数值 + * @param bits 指定移动的位数 + * @return 返回包含移位以后数值的对象 + * + * + * + */ + shiftRight(bits: number): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行按位 and 操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + and(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行按位 or 操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + or(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行按位 xor 操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + xor(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行加操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + add(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行减操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + sub(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行乘操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + multi(num: Class_Int64): Class_Int64; + + /** + * + * @brief 将 Int64 内的数值与给定的数值进行除操作,此操作不影响 Int64 原有数值 + * @param num 指定运算的数值 + * @return 返回包含预算以后数值的对象 + * + * + * + */ + div(num: Class_Int64): Class_Int64; + + /** + * + * @brief 比较当前对象与给定的对象是否相等 + * @param expected 制定比较的目标对象 + * @return 返回对象比较的结果 + * + * + * + */ + equals(expected: Class__object): boolean; + + /** + * + * @brief 转换成数字类型 + * @return 返回转换后的数字 + * + * + * + */ + toNumber(): number; + + /** + * + * @brief 转换成字符串类型 + * @param base 字符串进制数,可以接受 2-16, 32, 64,默认为 10 + * @return 返回转换后的字符串 + * + * + * + */ + toString(base?: number/** = 10*/): string; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/LevelDB.d.ts b/types/fibjs/declare/LevelDB.d.ts new file mode 100644 index 0000000000..67e4ced5c2 --- /dev/null +++ b/types/fibjs/declare/LevelDB.d.ts @@ -0,0 +1,176 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief LevelDB 数据库对象 + * @detail 用以创建和管理字典对象,创建方法:,```JavaScript,var db = require("db");,var test = new db.openLevelDB("test.db");,``` + */ + +declare class Class_LevelDB extends Class__object { + + + + /** + * + * @brief 检查数据库内是否存在指定键值的数据 + * @param key 指定要检查的键值 + * @return 返回键值是否存在 + * + * + * @async + */ + has(key: Class_Buffer): boolean; + + /** + * + * @brief 查询指定键值的值 + * @param key 指定要查询的键值 + * @return 返回键值所对应的值,若不存在,则返回 null + * + * + * @async + */ + get(key: Class_Buffer): Class_Buffer; + + /** + * + * @brief 查询一组指定键值的值 + * @param keys 指定要查询的键值数组 + * @return 返回包含键值得数组 + * + * + * + */ + mget(keys: any[]): any[]; + + /** + * + * @brief 设定一个键值数据,键值不存在则插入新数据 + * @param key 指定要设定的键值 + * @param value 指定要设定的数据 + * + * + * @async + */ + set(key: Class_Buffer, value: Class_Buffer): void; + + /** + * + * @brief 设定一组键值数据,键值不存在则插入新数据 + * @param map 指定要设定的键值数据字典 + * + * + * + */ + mset(map: Object): void; + + /** + * + * @brief 删除一组指定键值的值 + * @param keys 指定要删除的键值数组 + * + * + * + */ + mremove(keys: any[]): void; + + /** + * + * @brief 删除指定键值的全部值 + * @param key 指定要删除的键值 + * + * + * @async + */ + remove(key: Class_Buffer): void; + + /** + * + * @brief 枚举数据库中所有的键值对 + * + * 回调函数有两个参数,(value, key) + * + * ```JavaScript + * var db = require("db"); + * var test = new db.openLevelDB("test.db"); + * + * test.forEach(function(value, key){ + * ... + * }); + * ``` + * @param func 枚举回调函数 + * + * + * + */ + forEach(func: Function): void; + + /** + * + * @brief 枚举数据库中键值在 from 和 to 之间的键值对 + * + * 回调函数有两个参数,(value, key) + * + * ```JavaScript + * var db = require("db"); + * var test = new db.openLevelDB("test.db"); + * + * test.between("aaa", "bbb", function(value, key){ + * ... + * }); + * ``` + * @param from 枚举的最小键值,枚举时包含此键值 + * @param to 枚举的最大键值,枚举时不包含此键值 + * @param func 枚举回调函数 + * + * + * + */ + between(from: Class_Buffer, to: Class_Buffer, func: Function): void; + + /** + * + * @brief 在当前数据库上开启一个事务 + * @return 返回一个开启的事务对象 + * + * + */ + begin(): Class_LevelDB; + + /** + * + * @brief 提交当前事务 + * + * + */ + commit(): void; + + /** + * + * @brief 关闭当前数据库连接或事务 + * + * @async + */ + close(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Lock.d.ts b/types/fibjs/declare/Lock.d.ts new file mode 100644 index 0000000000..7f6f1ab13d --- /dev/null +++ b/types/fibjs/declare/Lock.d.ts @@ -0,0 +1,79 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 纤程锁对象 + * @detail 不同于操作系统的锁,纤程锁是纯逻辑实现,加锁与解锁负荷很小,```JavaScript,var l = new coroutine.Lock();,l.acquire();,.....,l.release();,``` + */ + +declare class Class_Lock extends Class__object { + + + + /** + * + * @brief 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 获取锁的拥有权 + * + * acquire 方法用于获取锁的拥有权,当锁处于可获取状态时,此方法立即返回 true。 + * + * 当锁不可获取,且 blocking 为 true,则当前纤程进入休眠,当其他纤程释放锁后,此方法返回 true。 + * + * 当锁不可获取,且 blocking 为 false,则方法返回 false。 + * @param blocking 指定是否等待,为 true 时等待,缺省为真 + * @return 返回是否成功获取锁,为 true 表示成功获取 + * + * + * + */ + acquire(blocking?: boolean/** = true*/): boolean; + + /** + * + * @brief 释放锁的拥有权 + * + * 此方法将释放对锁的拥有权,如果当前纤程未拥有锁,此方法将抛出错误。 + * + * + * + */ + release(): void; + + /** + * + * @brief 查询当前等待任务数 + * @return 返回任务数 + * + * + * + */ + count(): number; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/LruCache.d.ts b/types/fibjs/declare/LruCache.d.ts new file mode 100644 index 0000000000..2ca05b4d6c --- /dev/null +++ b/types/fibjs/declare/LruCache.d.ts @@ -0,0 +1,163 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief LRU(least recently used) 缓存对象 + * @detail LruCache 用以维护一个 LRU 缓存,创建方法:,```JavaScript,var util = require("util");,var c = new util.LruCache(10, 100);,``` + */ +/// +declare class Class_LruCache extends Class_EventEmitter { + + /** + * class prop + * + * + * @brief 查询容器内数值个数 + * + * @readonly + * @type Integer + */ + + size: number + + /** + * class prop + * + * + * @brief 查询和设置容器内元素失效时间,单位是 ms,小于等于 0 不失效 + * + * + * @type Integer + */ + + timeout: number + + /** + * class prop + * + * + * @brief 查询和绑定数据超时事件,相当于 on("expire", func); + * + * + * @type Function + */ + + onexpire: Function + + + + /** + * + * @brief LruCache 对象构造函数 + * @param size 缓存最大尺寸 + * @param timeout 元素失效时间,单位是 ms,小于等于 0 不失效,缺省为 0 + * + * + * + */ + constructor(size: number, timeout?: number/** = 0*/); + + /** + * + * @brief 清除容器数据 + * + * + */ + clear(): void; + + /** + * + * @brief 检查容器内是否存在指定键值的数据 + * @param name 指定要检查的键值 + * @return 返回键值是否存在 + * + * + * + */ + has(name: string): boolean; + + /** + * + * @brief 查询指定键值的值 + * @param name 指定要查询的键值 + * @return 返回键值所对应的值,若不存在,则返回 undefined + * + * + * + */ + get(name: string): any; + + /** + * + * @brief 查询指定键值的值,若不存在或过期,则调用回调函数更新数据 + * @param name 指定要查询的键值 + * @param updater 指定更新函数 + * @return 返回键值所对应的值 + * + * + * + */ + get(name: string, updater: Function): any; + + /** + * + * @brief 设定一个键值数据,键值不存在则插入一条新数据 + * @param name 指定要设定的键值 + * @param value 指定要设定的数据 + * + * + * + */ + set(name: string, value: any): void; + + /** + * + * @brief 设定一个键值数据,键值不存在则插入新数据 + * @param map 指定要设定的键值数据字典 + * + * + * + */ + set(map: Object): void; + + /** + * + * @brief 删除指定键值的全部值 + * @param name 指定要删除的键值 + * + * + * + */ + remove(name: string): void; + + /** + * + * @brief 检查容器是否为空 + * @return 容器内无数值则返回 true + * + * + * + */ + isEmpty(): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MSSQL.d.ts b/types/fibjs/declare/MSSQL.d.ts new file mode 100644 index 0000000000..c38cff27cb --- /dev/null +++ b/types/fibjs/declare/MSSQL.d.ts @@ -0,0 +1,43 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief SQL Server 数据库连接对象 + * @detail 使用 db.open 或 db.openMySQL 创建,创建方式:,```JavaScript,var sql = db.openMSSQL("mssql://user:pass@host/db");,``` + */ +/// +declare class Class_MSSQL extends Class_DbConnection { + + + + /** + * + * @brief 选择当前数据库连接的缺省数据库 + * @param dbName 指定数据库名 + * + * + * @async + */ + use(dbName: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MemoryStream.d.ts b/types/fibjs/declare/MemoryStream.d.ts new file mode 100644 index 0000000000..1c0b050134 --- /dev/null +++ b/types/fibjs/declare/MemoryStream.d.ts @@ -0,0 +1,69 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 内存流对象 + * @detail MemoryStream 对象创建一个基于内存的流对象,创建方法:,```JavaScript,var ms = new io.MemoryStream();,``` + */ +/// +declare class Class_MemoryStream extends Class_SeekableStream { + + + + /** + * + * @brief MemoryStream 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 强制设定内存流对象的最后更新时间 + * @param d 指定要设定的时间 + * + * + * + */ + setTime(d: Date): void; + + /** + * + * @brief 创建当前内存流的一个只读副本 + * @return 返回只读的内存流对象 + * + * + * + */ + clone(): Class_MemoryStream; + + /** + * + * @brief 清空内存文件数据,复位指针 + * + * + */ + clear(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Message.d.ts b/types/fibjs/declare/Message.d.ts new file mode 100644 index 0000000000..523c9c4ef5 --- /dev/null +++ b/types/fibjs/declare/Message.d.ts @@ -0,0 +1,235 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 基础消息对象 + * @detail Message 对象兼容于 mq 各个模块,可用于构建自定义消息处理系统,创建方法:,```JavaScript,var mq = require("mq");,var m = new mq.Message();,``` + */ + +declare class Class_Message extends Class__object { + + /** + * class prop + * + * + * @brief 消息的基本内容 + * + * + * @type String + */ + + value: string + + /** + * class prop + * + * + * @brief 消息的基本参数 + * + * @readonly + * @type NArray + */ + + params: any[] + + /** + * class prop + * + * + * @brief 消息类型 + * + * + * @type Integer + */ + + type: number + + /** + * class prop + * + * + * @brief 查询消息的数据 + * + * @readonly + * @type Value + */ + + data: any + + /** + * class prop + * + * + * @brief 包含消息数据部分的流对象 + * + * + * @type SeekableStream + */ + + body: Class_SeekableStream + + /** + * class prop + * + * + * @brief 消息数据部分的长度 + * + * @readonly + * @type Long + */ + + length: number + + /** + * class prop + * + * + * @brief 查询消息 readFrom 时的流对象 + * + * @readonly + * @type Stream + */ + + stream: Class_Stream + + /** + * class prop + * + * + * @brief 查询和设置消息处理的最后错误 + * + * + * @type String + */ + + lastError: string + + + + /** + * + * @brief 消息对象构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 从流内读取指定大小的数据,此方法为 body 相应方法的别名 + * @param bytes 指定要读取的数据量,缺省为读取随机大小的数据块,读出的数据尺寸取决于设备 + * @return 返回从流内读取的数据,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + read(bytes?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 从流内读取剩余的全部数据,此方法为 body 相应方法的别名 + * @return 返回从流内读取的数据,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + readAll(): Class_Buffer; + + /** + * + * @brief 写入给定的数据,此方法为 body 相应方法的别名 + * @param data 给定要写入的数据 + * + * + * @async + */ + write(data: Class_Buffer): void; + + /** + * + * @brief 以 JSON 编码写入给定的数据 + * @param data 给定要写入的数据 + * @return 此方法不会返回数据 + * + * + * + */ + json(data: any): any; + + /** + * + * @brief 以 JSON 编码解析消息中的数据 + * @return 返回解析的结果 + * + * + * + */ + json(): any; + + /** + * + * @brief 设置当前消息处理结束,Chain 处理器不再继续后面的事务 + * + * + */ + end(): void; + + /** + * + * @brief 查询当前消息是否结束 + * @return 结束则返回 true + * + * + * + */ + isEnded(): boolean; + + /** + * + * @brief 清除消息的内容 + * + * + */ + clear(): void; + + /** + * + * @brief 发送格式化消息到给定的流对象 + * @param stm 指定接收格式化消息的流对象 + * + * + * @async + */ + sendTo(stm: Class_Stream): void; + + /** + * + * @brief 从给定的缓存流对象中读取格式化消息,并解析填充对象 + * @param stm 指定读取格式化消息的流对象 + * + * + * @async + */ + readFrom(stm: Class_Stream): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MongoCollection.d.ts b/types/fibjs/declare/MongoCollection.d.ts new file mode 100644 index 0000000000..348ec36812 --- /dev/null +++ b/types/fibjs/declare/MongoCollection.d.ts @@ -0,0 +1,227 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief mongodb 数据库数据集对象 + * @detail 使用 MongoDB.getCollection 创建:,```JavaScript,var col1 = mdb.getCollection('test');,var col = mdb.test;,``` + */ + +declare class Class_MongoCollection extends Class__object { + + + + /** + * + * @brief 根据给定的查询条件和返回字段设定,建立游标对象 + * @param query 指定查询条件的对象 + * @param projection 指定返回字段的对象 + * @return 返回游标对象 + * + * + * + */ + find(query?: Object/** = v8::Object::New(isolate)*/, projection?: Object/** = v8::Object::New(isolate)*/): Class_MongoCursor; + + /** + * + * @brief 根据给定的查询条件和返回字段设定,查询一条结果 + * @param query 指定查询条件的对象 + * @param projection 指定返回字段的对象 + * @return 返回第一条结果 + * + * + * + */ + findOne(query?: Object/** = v8::Object::New(isolate)*/, projection?: Object/** = v8::Object::New(isolate)*/): Object; + + /** + * + * @brief 查询并修改 + * @param query 指定查询条件,修改数据 + * @return 返回修改前的结果及其他信息 + * + * + * + */ + findAndModify(query: Object): Object; + + /** + * + * @brief 插入一组数据 + * @param documents 指定要插入的数据数组 + * + * + * + */ + insert(documents: any[]): void; + + /** + * + * @brief 插入一条数据 + * @param document 指定要插入的数据 + * + * + * + */ + insert(document: Object): void; + + /** + * + * @brief 保存一条数据,若数据包含 _id 字段,则为更新,否则为插入 + * @param document 指定要保存的数据 + * + * + * + */ + save(document: Object): void; + + /** + * + * @brief 根据给定的查询条件更新数据 + * @param query 指定查询条件的对象 + * @param document 指定要更新的数据 + * @param upsert 数据不存在时,插入一条新数据,缺省为 false,不插入 + * @param multi 当符合条件的数据多于一条时,更新所有数据,缺省为 false,只更新第一条 + * + * + * + */ + update(query: Object, document: Object, upsert?: boolean/** = false*/, multi?: boolean/** = false*/): void; + + /** + * + * @brief 根据给定的查询条件更新数据 + * @param query 指定查询条件的对象 + * @param document 指定要更新的数据 + * @param options 以对象字段传递的 upsert 和 multi 选项 + * + * + * + */ + update(query: Object, document: Object, options: Object): void; + + /** + * + * @brief 根据给定的查询条件删除数据 + * @param query 指定查询条件的对象 + * + * + * + */ + remove(query: Object): void; + + /** + * + * @brief 执行数据库命令 + * @param cmd 给定命令对象 + * @return 返回命令返回结果 + * + * + * + */ + runCommand(cmd: Object): Object; + + /** + * + * @brief 执行数据库命令 + * @param cmd 给定命令名称 + * @param arg 给定命令参数选项 + * @return 返回命令返回结果 + * + * + * + */ + runCommand(cmd: string, arg?: Object/** = v8::Object::New(isolate)*/): Object; + + /** + * + * @brief 删除当前集合 + * + * + */ + drop(): void; + + /** + * + * @brief 在当前集合上创建索引 + * @param keys 给定索引字段、顺序和方向 + * @param options 给定索引的选项,唯一索引等 + * + * + * + */ + ensureIndex(keys: Object, options?: Object/** = v8::Object::New(isolate)*/): void; + + /** + * + * @brief 重建当前集合的索引 + * @return 返回命令执行结果 + * + * + * + */ + reIndex(): Object; + + /** + * + * @brief 删除当前集合指定名称的索引 + * @param name 给定要删除的索引名称 + * @return 返回命令执行结果 + * + * + * + */ + dropIndex(name: string): Object; + + /** + * + * @brief 删除当前集合全部索引 + * @return 返回命令执行结果 + * + * + * + */ + dropIndexes(): Object; + + /** + * + * @brief 查询当前集合全部索引 + * @return 返回包含索引的结果集 + * + * + * + */ + getIndexes(): Class_MongoCursor; + + /** + * + * @brief 获取当前集合子命名空间的集合对象 + * @param name 子命名空间名称 + * @return 返回新集合对象 + * + * + * + */ + getCollection(name: string): Class_MongoCollection; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MongoCursor.d.ts b/types/fibjs/declare/MongoCursor.d.ts new file mode 100644 index 0000000000..8b8e903f35 --- /dev/null +++ b/types/fibjs/declare/MongoCursor.d.ts @@ -0,0 +1,149 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief mongodb 数据库数据游标对象 + * @detail + */ + +declare class Class_MongoCursor extends Class__object { + + + + /** + * + * @brief 指定返回结果时跳过的记录数 + * @param num 记录数 + * @return 返回游标对象本身便于链式调用 + * + * + * @async + */ + skip(num: number): Class_MongoCursor; + + /** + * + * @brief 指定返回结果的最大记录数 + * @param size 记录数 + * @return 返回游标对象本身便于链式调用 + * + * + * @async + */ + limit(size: number): Class_MongoCursor; + + /** + * + * @brief 设定返回结果的排序 + * @param opts 指定排序条件 + * @return 返回游标对象本身便于链式调用 + * + * + * + */ + sort(opts: Object): Class_MongoCursor; + + /** + * + * @brief 查询当前游标是否有下一条记录 + * @return 有记录则返回 true + * + * + * + */ + hasNext(): boolean; + + /** + * + * @brief 返回当前游标的下一条记录 + * @return 记录对象,无记录则返回 null + * + * + * + */ + next(): Object; + + /** + * + * @brief 查询游标的记录总数 + * @param applySkipLimit 指定是否查询 skip 和 limit 后的记录数,缺省为 false,查询全部记录数 + * @return 返回记录总数 + * + * + * + */ + count(applySkipLimit?: boolean/** = false*/): number; + + /** + * + * @brief 查询游标的记录总数,相当于 count(true) + * @return 返回记录总数 + * + * + * + */ + size(): number; + + /** + * + * @brief 遍历全部记录并回调处理函数 + * @param func 指定处理函数 + * + * + * + */ + forEach(func: Function): void; + + /** + * + * @brief 遍历处理全部记录,并返回处理结果 + * @param func 指定处理函数 + * @return 返回处理结果数组 + * + * + * + */ + map(func: Function): any[]; + + /** + * + * @brief 返回当前游标全部记录的数组 + * @return 返回包含全部数据的 Javascript 数组 + * + * + * + */ + toArray(): any[]; + + /** + * + * @brief 修改 mongodb 服务器缺省索引策略,使用指定的索引进行查询 + * @param opts 指定强制使用的索引 + * @return 返回游标对象本身便于链式调用 + * + * + * + */ + hint(opts: Object): Class_MongoCursor; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MongoDB.d.ts b/types/fibjs/declare/MongoDB.d.ts new file mode 100644 index 0000000000..19dd8a7369 --- /dev/null +++ b/types/fibjs/declare/MongoDB.d.ts @@ -0,0 +1,86 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief mongodb 数据库连接对象 + * @detail 使用 db.open 或 db.openMongoDB 创建,创建方式:,```JavaScript,var mdb = db.openMongoDB("mongodb://host/db");,``` + */ + +declare class Class_MongoDB extends Class__object { + + + + /** + * + * @brief 获取指定集合访问对象 + * @param name 指定集合的名称 + * @return 返回指定的集合对象 + * + * + * + */ + getCollection(name: string): Class_MongoCollection; + + /** + * + * @brief 指定一个 MongoDB 数据库命令 + * @param cmd 指定命令和参数的字典对象 + * @return 返回命令执行结果 + * + * + * + */ + runCommand(cmd: Object): Object; + + /** + * + * @brief 指定一个简单的 MongoDB 数据库命令 + * @param cmd 指定命令名 + * @param arg 指定命令参数 + * @return 返回命令执行结果 + * + * + * + */ + runCommand(cmd: string, arg: any): Object; + + /** + * + * @brief 生成一个 mongodb _objectid 对象 + * @param hexStr 初始化 16 进制字符串,缺省生成新的 id + * @return 新 _objectid 对象 + * + * + * + */ + oid(hexStr?: string/** = ""*/): Class_MongoID; + + /** + * + * @brief 关闭当前数据库连接 + * + * @async + */ + close(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MongoID.d.ts b/types/fibjs/declare/MongoID.d.ts new file mode 100644 index 0000000000..8fd002b02f --- /dev/null +++ b/types/fibjs/declare/MongoID.d.ts @@ -0,0 +1,33 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief mongodb 数据库数据唯一标识对象,用于存储传递 oid + * @detail + */ + +declare class Class_MongoID extends Class__object { + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/MySQL.d.ts b/types/fibjs/declare/MySQL.d.ts new file mode 100644 index 0000000000..edc974a1d5 --- /dev/null +++ b/types/fibjs/declare/MySQL.d.ts @@ -0,0 +1,67 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief mysql 数据库连接对象 + * @detail 使用 db.open 或 db.openMySQL 创建,创建方式:,```JavaScript,var msql = db.openMySQL("mysql://user:pass@host/db");,``` + */ +/// +declare class Class_MySQL extends Class_DbConnection { + + /** + * class prop + * + * + * @brief 数据库连接接收缓存尺寸 + * + * + * @type Integer + */ + + rxBufferSize: number + + /** + * class prop + * + * + * @brief 数据库连接发送缓存尺寸 + * + * + * @type Integer + */ + + txBufferSize: number + + + + /** + * + * @brief 选择当前数据库连接的缺省数据库 + * @param dbName 指定数据库名 + * + * + * @async + */ + use(dbName: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/PKey.d.ts b/types/fibjs/declare/PKey.d.ts new file mode 100644 index 0000000000..3d25308696 --- /dev/null +++ b/types/fibjs/declare/PKey.d.ts @@ -0,0 +1,355 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 不对称加密算法对象 + * @detail PKey 对象属于 crypto 模块,创建:,```JavaScript,var k = new crypto.PKey();,``` + */ + +declare class Class_PKey extends Class__object { + + /** + * class prop + * + * + * @brief 返回当前算法名称 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 返回当前算法密码长度,以位为单位 + * + * @readonly + * @type Integer + */ + + keySize: number + + /** + * class prop + * + * + * @brief 返回当前密钥的公钥 + * @return 当前密钥的公钥 + * + * + * @readonly + * @type PKey + */ + + publicKey: Class_PKey + + + + /** + * + * @brief PKey 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 通过 DER 格式的密钥构造 PKey + * @param DerKey DER 格式的密钥 + * @param password 解密密码 + * + * + * + */ + constructor(DerKey: Class_Buffer, password?: string/** = ""*/); + + /** + * + * @brief 通过 PEM 格式的密钥构造 PKey + * @param pemKey PEM 格式的密钥 + * @param password 解密密码 + * + * + * + */ + constructor(pemKey: string, password?: string/** = ""*/); + + /** + * + * @brief 通过 JSON 格式的密钥构造 PKey + * + * jsonKey 的格式支持以下四种,RSA 私钥: + * ```JavaScript + * { + * "kty": "RSA", + * "n": "0m5lvKpWqy9JS7tV2HIPqHCYHLquSuxIC3F8strIQLJKO3rZmTT96KTnhsOfBO7Y1bI7mnT0PB3_vcHd9ekWMEoZJQw7MuB8KeM_Wn54-elJr5DNLk5bMppSGxX7ZnumiXGG51_X3Yp-_EbGtDG80GxXXix7Mucyo7K25uE0uW8=", + * "e": "AQAB", + * "d": "agN2O9NxMHL1MTMi75WfL9Pxvl-KWXKqZSF6mjzAsF9iKI8euyHIXYFepzU8kual1RsjDhCnzvWqFvZplW8lXqrHf_P-rS_9Y4gBUw6pjnI_DnFIRwWHRvrUHHSCfWOdTCIKdOTkgLZuGFuhEY3RMIW0WSYejjLtftwy0RVxAzk=", + * "p": "6a4G1qmfwWmn1biigN7IVFlkbLf9oVe6g7rOmHxI-hn1GRxKDSVuAUrmR1IhuAnca9M0y7SD-7TUs6wjOxWxaw==", + * "q": "5ofkxFKdPBD0CQHMb9q13AMHUVe0rJ-hSjqqIBrmqApUOneyAcMV76M0QyIQnI2p3POa4Qu_7XChDwRVl7LlDQ==", + * "dp": "2mXGiGwCHl8j-FBWuID-1C6z-BRB3MBEVoeKPOOzxOPruatB3mWEGXsqG7A8SWgV9URxTI2K6P3J6Z7RUpBkvw==", + * "dq": "oagn5vfb5NQqnOpS9xkSsD67cfIj821ZSFlNFYhnuOzNVda7z_qCtnHm4zDPH0lEFXoKYMfBhfqWJpaugttjPQ==", + * "qi": "dqEQgxNmOVFrF4s776hTqeC6oEDila8EvpVb2F2ZvwAOLjCQ66OiAZK1BiYGHqUy0NeqNmtlsLSuBEZQZvqZwg==" + * } + * ``` + * RSA 公钥: + * ```JavaScript + * { + * "kty": "RSA", + * "n": "0m5lvKpWqy9JS7tV2HIPqHCYHLquSuxIC3F8strIQLJKO3rZmTT96KTnhsOfBO7Y1bI7mnT0PB3_vcHd9ekWMEoZJQw7MuB8KeM_Wn54-elJr5DNLk5bMppSGxX7ZnumiXGG51_X3Yp-_EbGtDG80GxXXix7Mucyo7K25uE0uW8=", + * "e": "AQAB" + * } + * ``` + * EC 私钥: + * ```JavaScript + * { + * "kty": "EC", + * "crv": "P-521", + * "x": "ATfNNFuuvlGxrTGoXgyfSAGgRNNDnO3rN3k74urKJdVS14RYhdnSwm91Bm-F1l-T1XKlAY2yRnzG9w1Ukvo8c0wL", + * "y": "ASBHqrruB6kdkEUB3vlW3-UIkk4HtKdUeTwN-7m3j2rgZvYR1ffRAapDvWqKGiBjomqWafxokBkbDI0c95f6f4XU", + * "d": "AfkIbUHXfW41njdpoKuqqKludcoLJS8D_oMEwkj-GVaXFNKccIoF5iKGu2c69kNDjo83R_7wyGlfRczsklkik1ST" + * } + * ``` + * EC 公钥: + * ```JavaScript + * { + * "kty": "EC", + * "crv": "P-521", + * "x": "ATfNNFuuvlGxrTGoXgyfSAGgRNNDnO3rN3k74urKJdVS14RYhdnSwm91Bm-F1l-T1XKlAY2yRnzG9w1Ukvo8c0wL", + * "y": "ASBHqrruB6kdkEUB3vlW3-UIkk4HtKdUeTwN-7m3j2rgZvYR1ffRAapDvWqKGiBjomqWafxokBkbDI0c95f6f4XU" + * } + * ``` + * @param jsonKey JSON 格式的密钥 + * + * + * + */ + constructor(jsonKey: Object); + + /** + * + * @brief 生成一个 RSA 私钥 + * @param size 指定 RSA 密钥长度,bit 为单位 + * + * + * @async + */ + genRsaKey(size: number): void; + + /** + * + * @brief 生成一个 EC 私钥 + * @param curve 指定预置椭圆曲线,可选值为:"secp521r1", "brainpoolP512r1", "secp384r1", "brainpoolP384r1", "secp256r1", "secp256k1", "brainpoolP256r1", "secp224r1", "secp224k1", "secp192r1", "secp192k1" + * + * + * @async + */ + genEcKey(curve?: string/** = "secp521r1"*/): void; + + /** + * + * @brief 查询当前密钥是否为私钥 + * @return 为 True 表示为私钥 + * + * + * + */ + isPrivate(): boolean; + + /** + * + * @brief 复制当前密钥 + * @return 当前密钥的复制对象 + * + * + * + */ + clone(): Class_PKey; + + /** + * + * @brief 加载一个 DER 格式的密钥 + * @param DerKey DER 格式的密钥 + * @param password 解密密码 + * + * + * + */ + importKey(DerKey: Class_Buffer, password?: string/** = ""*/): void; + + /** + * + * @brief 加载一个 PEM 格式的密钥 + * @param pemKey PEM 格式的密钥 + * @param password 解密密码 + * + * + * + */ + importKey(pemKey: string, password?: string/** = ""*/): void; + + /** + * + * @brief 加载一个 JSON 格式的密钥 + * + * jsonKey 的格式支持以下四种,RSA 私钥: + * ```JavaScript + * { + * "kty": "RSA", + * "n": "0m5lvKpWqy9JS7tV2HIPqHCYHLquSuxIC3F8strIQLJKO3rZmTT96KTnhsOfBO7Y1bI7mnT0PB3_vcHd9ekWMEoZJQw7MuB8KeM_Wn54-elJr5DNLk5bMppSGxX7ZnumiXGG51_X3Yp-_EbGtDG80GxXXix7Mucyo7K25uE0uW8=", + * "e": "AQAB", + * "d": "agN2O9NxMHL1MTMi75WfL9Pxvl-KWXKqZSF6mjzAsF9iKI8euyHIXYFepzU8kual1RsjDhCnzvWqFvZplW8lXqrHf_P-rS_9Y4gBUw6pjnI_DnFIRwWHRvrUHHSCfWOdTCIKdOTkgLZuGFuhEY3RMIW0WSYejjLtftwy0RVxAzk=", + * "p": "6a4G1qmfwWmn1biigN7IVFlkbLf9oVe6g7rOmHxI-hn1GRxKDSVuAUrmR1IhuAnca9M0y7SD-7TUs6wjOxWxaw==", + * "q": "5ofkxFKdPBD0CQHMb9q13AMHUVe0rJ-hSjqqIBrmqApUOneyAcMV76M0QyIQnI2p3POa4Qu_7XChDwRVl7LlDQ==", + * "dp": "2mXGiGwCHl8j-FBWuID-1C6z-BRB3MBEVoeKPOOzxOPruatB3mWEGXsqG7A8SWgV9URxTI2K6P3J6Z7RUpBkvw==", + * "dq": "oagn5vfb5NQqnOpS9xkSsD67cfIj821ZSFlNFYhnuOzNVda7z_qCtnHm4zDPH0lEFXoKYMfBhfqWJpaugttjPQ==", + * "qi": "dqEQgxNmOVFrF4s776hTqeC6oEDila8EvpVb2F2ZvwAOLjCQ66OiAZK1BiYGHqUy0NeqNmtlsLSuBEZQZvqZwg==" + * } + * ``` + * RSA 公钥: + * ```JavaScript + * { + * "kty": "RSA", + * "n": "0m5lvKpWqy9JS7tV2HIPqHCYHLquSuxIC3F8strIQLJKO3rZmTT96KTnhsOfBO7Y1bI7mnT0PB3_vcHd9ekWMEoZJQw7MuB8KeM_Wn54-elJr5DNLk5bMppSGxX7ZnumiXGG51_X3Yp-_EbGtDG80GxXXix7Mucyo7K25uE0uW8=", + * "e": "AQAB" + * } + * ``` + * EC 私钥: + * ```JavaScript + * { + * "kty": "EC", + * "crv": "P-521", + * "x": "ATfNNFuuvlGxrTGoXgyfSAGgRNNDnO3rN3k74urKJdVS14RYhdnSwm91Bm-F1l-T1XKlAY2yRnzG9w1Ukvo8c0wL", + * "y": "ASBHqrruB6kdkEUB3vlW3-UIkk4HtKdUeTwN-7m3j2rgZvYR1ffRAapDvWqKGiBjomqWafxokBkbDI0c95f6f4XU", + * "d": "AfkIbUHXfW41njdpoKuqqKludcoLJS8D_oMEwkj-GVaXFNKccIoF5iKGu2c69kNDjo83R_7wyGlfRczsklkik1ST" + * } + * ``` + * EC 公钥: + * ```JavaScript + * { + * "kty": "EC", + * "crv": "P-521", + * "x": "ATfNNFuuvlGxrTGoXgyfSAGgRNNDnO3rN3k74urKJdVS14RYhdnSwm91Bm-F1l-T1XKlAY2yRnzG9w1Ukvo8c0wL", + * "y": "ASBHqrruB6kdkEUB3vlW3-UIkk4HtKdUeTwN-7m3j2rgZvYR1ffRAapDvWqKGiBjomqWafxokBkbDI0c95f6f4XU" + * } + * ``` + * @param jsonKey JSON 格式的密钥 + * + * + * + */ + importKey(jsonKey: Object): void; + + /** + * + * @brief 加载一个 PEM/DER 格式的密钥文件 + * @param filename 密钥文件名 + * @param password 解密密码 + * + * + * + */ + importFile(filename: string, password?: string/** = ""*/): void; + + /** + * + * @brief 返回当前 key 的 PEM 格式编码 + * @return 当前 key 的 PEM 格式编码 + * + * + * + */ + exportPem(): string; + + /** + * + * @brief 返回当前 key 的 DER 格式编码 + * @return 当前 key 的 DER 格式编码 + * + * + * + */ + exportDer(): Class_Buffer; + + /** + * + * @brief 返回当前 key 的 DER 格式编码 + * @return 当前 key 的 DER 格式编码 + * + * + * + */ + exportJson(): Object; + + /** + * + * @brief 使用当前算法密码公钥加密数据 + * @param data 指定要加密的数据 + * @return 返回加密后的数据 + * + * + * @async + */ + encrypt(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 使用当前算法密码私钥解密数据 + * @param data 指定要解密的数据 + * @return 返回解密后的数据 + * + * + * @async + */ + decrypt(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 使用当前算法密码私钥签名数据 + * @param data 指定要签名的数据 + * @param alg 指定要签名的算法, 默认0. 支持算法: 0=NONE,1=MD2,2=MD4,3=MD5,4=SHA1,5=SHA224,6=SHA256,7=SHA384,8=SHA512,9=RIPEMD160 + * @return 返回签名后的数据 + * + * + * @async + */ + sign(data: Class_Buffer, alg?: number/** = 0*/): Class_Buffer; + + /** + * + * @brief 使用当前算法密码公钥验证数据 + * @param data 指定要验证的数据 + * @param sign 指定要验证的签名 + * @param alg 指定要签名的算法, 默认0. 支持算法: 0=NONE,1=MD2,2=MD4,3=MD5,4=SHA1,5=SHA224,6=SHA256,7=SHA384,8=SHA512,9=RIPEMD160 + * @return 返回验证后的结果 + * + * + * @async + */ + verify(data: Class_Buffer, sign: Class_Buffer, alg?: number/** = 0*/): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Redis.d.ts b/types/fibjs/declare/Redis.d.ts new file mode 100644 index 0000000000..ed5d498a98 --- /dev/null +++ b/types/fibjs/declare/Redis.d.ts @@ -0,0 +1,576 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Redis 数据库客户端对象 + * @detail 用以创建和管理 Redis 数据库,创建方法:,```JavaScript,var db = require("db");,var test = new db.openRedis("redis-server");,``` + */ + +declare class Class_Redis extends Class__object { + + /** + * class prop + * + * + * @brief 查询和设置错误处理函数,当 sub 出现错误或者网络中断时回调,当回调发生后,本对象的一切 sub 都将中止 + * + * + * + * @type Function + */ + + onsuberror: Function + + + + /** + * + * @brief redis 基础命令方法 + * @param cmd 指定发送的命令 + * @param args 指定发送的参数 + * @return 返回服务器返回的结果 + * + * + */ + command(cmd: string, ...args: any[]): any; + + /** + * + * @brief 将字符串值 value 关联到 key,如果 key 已经持有其他值, SET 就覆写旧值,无视类型 + * @param key 指定要关联的 key + * @param value 指定要关联的数据 + * @param ttl 以毫秒为单位为 key 设置生存时间;如果 ttl 为 0 ,那么不设置生存时间 + * + * + */ + set(key: Class_Buffer, value: Class_Buffer, ttl?: number/** = 0*/): void; + + /** + * + * @brief 将 key 的值设为 value ,当且仅当 key 不存在。若给定的 key 已经存在,则 SETNX 不做任何动作。 + * @param key 指定要关联的 key + * @param value 指定要关联的数据 + * @param ttl 以毫秒为单位为 key 设置生存时间;如果 ttl 为 0 ,那么不设置生存时间 + * + * + */ + setNX(key: Class_Buffer, value: Class_Buffer, ttl?: number/** = 0*/): void; + + /** + * + * @brief 将 key 的值设为 value,只在键已经存在时,才对键进行设置操作。 + * @param key 指定要关联的 key + * @param value 指定要关联的数据 + * @param ttl 以毫秒为单位为 key 设置生存时间;如果 ttl 为 0 ,那么不设置生存时间 + * + * + */ + setXX(key: Class_Buffer, value: Class_Buffer, ttl?: number/** = 0*/): void; + + /** + * + * @brief 同时设置一个或多个 key-value 对。如果某个给定 key 已经存在,那么 MSET 会用新值覆盖原来的旧值 + * @param kvs 指定要设置的 key/value 对象 + * + * + */ + mset(kvs: Object): void; + + /** + * + * @brief 同时设置一个或多个 key-value 对。如果某个给定 key 已经存在,那么 MSET 会用新值覆盖原来的旧值 + * @param kvs 指定要设置的 key/value 列表 + * + * + */ + mset(...kvs: any[]): void; + + /** + * + * @brief 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 + * @param kvs 指定要设置的 key/value 对象 + * + * + */ + msetNX(kvs: Object): void; + + /** + * + * @brief 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 + * @param kvs 指定要设置的 key/value 列表 + * + * + */ + msetNX(...kvs: any[]): void; + + /** + * + * @brief 如果 key 已经存在并且是一个字符串,append 命令将 value 追加到 key 原来的值的末尾。如果 key 不存在,append 就简单地将给定 key 设为 value + * @param key 指定要追加的 key + * @param value 指定要追加的数据 + * @return 追加 value 之后, key 中字符串的长度 + * + * + */ + append(key: Class_Buffer, value: Class_Buffer): number; + + /** + * + * @brief 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始 + * @param key 指定要修改的 key + * @param offset 指定修改的字节偏移 + * @param value 指定要覆盖的数据 + * @return 被修改之后,字符串的长度 + * + * + */ + setRange(key: Class_Buffer, offset: number, value: Class_Buffer): number; + + /** + * + * @brief 返回 key 中字符串值的子字符串,字符串的截取范围由 start 和 end 两个偏移量决定(包括 start 和 end 在内) + * @param key 指定要查询的 key + * @param start 指定查询的起始字节偏移 + * @param end 指定查询的结束字节偏移 + * @return 截取得出的子字符串 + * + * + */ + getRange(key: Class_Buffer, start: number, end: number): Class_Buffer; + + /** + * + * @brief 返回 key 所储存的字符串值的长度。当 key 储存的不是字符串值时,返回一个错误 + * @param key 指定要计算的 key + * @return 字符串值的长度。当 key 不存在时,返回 0 + * + * + */ + strlen(key: Class_Buffer): number; + + /** + * + * @brief 计算给定字符串中,被设置为 1 的比特位的数量 + * @param key 指定要计算的 key + * @param start 指定要计算的起始字节,可以使用负数值,-1 表示最后一个字节,而 -2 表示倒数第二个字节,以此类推 + * @param end 指定要计算的结束字节,可以使用负数值,-1 表示最后一个字节,而 -2 表示倒数第二个字节,以此类推 + * @return 被设置为 1 的位的数量 + * + * + */ + bitcount(key: Class_Buffer, start?: number/** = 0*/, end?: number/** = -1*/): number; + + /** + * + * @brief 返回 key 所关联的字符串值,如果 key 不存在那么返回特殊值 Null + * @param key 指定要关联的 key + * @return 当 key 不存在时,返回 Null ,否则,返回 key 的值 + * + * + */ + get(key: Class_Buffer): Class_Buffer; + + /** + * + * @brief 返回所有(一个或多个)给定 key 的值。如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。 + * @param keys 指定要查询的 key 数组 + * @return 一个包含所有给定 key 的值的列表 + * + * + */ + mget(keys: any[]): any[]; + + /** + * + * @brief 返回所有(一个或多个)给定 key 的值。如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。 + * @param keys 指定要查询的 key 列表 + * @return 一个包含所有给定 key 的值的列表 + * + * + */ + mget(...keys: any[]): any[]; + + /** + * + * @brief 将给定 key 的值设为 value ,并返回 key 的旧值(old value) + * @param key 指定要查询修改的 key + * @param value 指定修改的数值 + * @return 返回给定 key 的旧值 + * + * + */ + getset(key: Class_Buffer, value: Class_Buffer): Class_Buffer; + + /** + * + * @brief 将 key 所储存的值减去减量 + * @param key 指定要修改的 key + * @param num 指定要减去的数值 + * @return 减去 num 之后,key 的值 + * + * + */ + decr(key: Class_Buffer, num?: number/** = 1*/): number; + + /** + * + * @brief 将 key 所储存的值加上增量 + * @param key 指定要修改的 key + * @param num 指定要加上的数值 + * @return 加上 num 之后,key 的值 + * + * + */ + incr(key: Class_Buffer, num?: number/** = 1*/): number; + + /** + * + * @brief 对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit) + * @param key 指定要修改的 key + * @param offset 指定修改的位偏移 + * @param value 指定设置或清除的参数,可以是 0 也可以是 1 + * @return 指定偏移量原来储存的位 + * + * + */ + setBit(key: Class_Buffer, offset: number, value: number): number; + + /** + * + * @brief 对 key 所储存的字符串值,获取指定偏移量上的位(bit) + * @param key 指定要查询的 key + * @param offset 指定查询的位偏移 + * @return 字符串值指定偏移量上的位(bit) + * + * + */ + getBit(key: Class_Buffer, offset: number): number; + + /** + * + * @brief 检查给定 key 是否存在 + * @param key 指定要关联的 key + * @return 若 key 存在,返回 True,否则返回 False + * + * + */ + exists(key: Class_Buffer): boolean; + + /** + * + * @brief 返回 key 所储存的值的类型 + * @param key 指定要查询的 key + * @return 返回 key 所储存的值的类型,可能的值为 none(key不存在) string(字符串) list(列表) set(集合) zset(有序集) hash(哈希表) + * + * + */ + type(key: Class_Buffer): string; + + /** + * + * @brief 查找所有符合给定模式 pattern 的 key + * @param pattern 指定查询模式 + * @return 符合给定模式的 key 列表 + * + * + */ + keys(pattern: string): any[]; + + /** + * + * @brief 删除给定的一个或多个 key,不存在的 key 会被忽略 + * @param keys 指定要删除的 key 数组 + * @return 被删除 key 的数量 + * + * + */ + del(keys: any[]): number; + + /** + * + * @brief 删除给定的一个或多个 key,不存在的 key 会被忽略 + * @param keys 指定要删除的 key 列表 + * @return 被删除 key 的数量 + * + * + */ + del(...keys: any[]): number; + + /** + * + * @brief 为给定 key 设置生存时间,当 key 过期时,它会被自动删除 + * @param key 指定要设定的 key + * @param ttl 以毫秒为单位为 key 设置生存时间 + * @return 若 key 存在,返回 True,否则返回 False + * + * + */ + expire(key: Class_Buffer, ttl: number): boolean; + + /** + * + * @brief 返回给定 key 的剩余生存时间 + * @param key 指定要查询的 key + * @return 以毫秒为单位,返回 key 的剩余生存时间,当 key 不存在时,返回 -2,当 key 存在但没有设置剩余生存时间时,返回 -1 + * + * + */ + ttl(key: Class_Buffer): number; + + /** + * + * @brief 移除给定 key 的生存时间,将这个 key 从『易失的』(带生存时间 key )转换成『持久的』(一个不带生存时间、永不过期的 key) + * @param key 指定要设定的 key + * @return 若 key 存在,返回 True,否则返回 False + * + * + */ + persist(key: Class_Buffer): boolean; + + /** + * + * @brief 将 key 改名为 newkey,当 key 和 newkey 相同,或者 key 不存在时,返回一个错误 + * @param key 指定要改名的 key + * @param newkey 指定要改名的目的 key + * + * + */ + rename(key: Class_Buffer, newkey: Class_Buffer): void; + + /** + * + * @brief 当且仅当 newkey 不存在时,将 key 改名为 newkey,当 key 不存在时,返回一个错误 + * @param key 指定要改名的 key + * @param newkey 指定要改名的目的 key + * @return 修改成功时,返回 True,如果 newkey 已经存在,返回 False + * + * + */ + renameNX(key: Class_Buffer, newkey: Class_Buffer): boolean; + + /** + * + * @brief 订阅给定的一个频道的信息,当消息发生时自动调用 func,func 包含两个参数,依次为 channel 和 message,同一频道同一函数只会回调一次 + * @param channel 指定订阅的频道名称 + * @param func 指定回调函数 + * + * + * + */ + sub(channel: Class_Buffer, func: Function): void; + + /** + * + * @brief 订阅给定的一组频道的信息,当消息发生时自动调用相应的回调函数,同一频道同一函数只会回调一次 + * @param map 指定频道映射关系,对象属性名称将作为频道名称,属性的值将作为回调函数 + * + * + * + */ + sub(map: Object): void; + + /** + * + * @brief 退订给定的频道的全部回调 + * @param channel 指定退订的频道名称 + * + * + * + */ + unsub(channel: Class_Buffer): void; + + /** + * + * @brief 退订给定的频道的指定回调函数 + * @param channel 指定退订的频道名称 + * @param func 指定退订的回调函数 + * + * + * + */ + unsub(channel: Class_Buffer, func: Function): void; + + /** + * + * @brief 退订一组给定的频道的全部回调 + * @param channels 指定退订的频道数组 + * + * + * + */ + unsub(channels: any[]): void; + + /** + * + * @brief 退订给定的一组频道的指定回调函数 + * @param map 指定频道映射关系,对象属性名称将作为频道名称,属性的值将作为回调函数 + * + * + * + */ + unsub(map: Object): void; + + /** + * + * @brief 按照模板订阅一组频道的信息,当消息发生时自动调用 func,func 包含三个参数,依次为 channel,message 和 pattern,同一模板同一函数只会回调一次 + * @param pattern 指定订阅的频道模板 + * @param func 指定回调函数 + * + * + * + */ + psub(pattern: string, func: Function): void; + + /** + * + * @brief 订阅给定的一组频道模板的信息,当消息发生时自动调用相应的 func,同一频道同一函数只会回调一次 + * @param map 指定频道映射关系,对象属性名称将作为频道模板,属性的值将作为回调函数 + * + * + * + */ + psub(map: Object): void; + + /** + * + * @brief 退订给定模板的频道的全部回调 + * @param pattern 指定退订的频道模板 + * + * + * + */ + unpsub(pattern: string): void; + + /** + * + * @brief 退订给定模板的频道的指定回调函数 + * @param pattern 指定退订的频道模板 + * @param func 指定退订的回调函数 + * + * + * + */ + unpsub(pattern: string, func: Function): void; + + /** + * + * @brief 退订一组给定模板的频道的全部回调 + * @param patterns 指定发布的频道模板数组 + * + * + * + */ + unpsub(patterns: any[]): void; + + /** + * + * @brief 退订一组模板的频道的指定回调函数 + * @param map 指定频道映射关系,对象属性名称将作为频道模板,属性的值将作为回调函数 + * + * + * + */ + unpsub(map: Object): void; + + /** + * + * @brief 将信息 message 发送到指定的频道 channel + * @param channel 指定发布的频道 + * @param message 指定发布的消息 + * @return 接收此消息的客户端数量 + * + * + * + */ + pub(channel: Class_Buffer, message: Class_Buffer): number; + + /** + * + * @brief 获取指定 key 的 Hash 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @param key 指定要获取的 key + * @return 返回包含指定 key 的 Hash 对象 + * + * + */ + getHash(key: Class_Buffer): Class_RedisHash; + + /** + * + * @brief 获取指定 key 的 List 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @param key 指定要获取的 key + * @return 返回包含指定 key 的 List 对象 + * + * + */ + getList(key: Class_Buffer): Class_RedisList; + + /** + * + * @brief 获取指定 key 的 Set 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @param key 指定要获取的 key + * @return 返回包含指定 key 的 Set 对象 + * + * + */ + getSet(key: Class_Buffer): Class_RedisSet; + + /** + * + * @brief 获取指定 key 的 SortedSet 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @param key 指定要获取的 key + * @return 返回包含指定 key 的 SortedSet 对象 + * + * + */ + getSortedSet(key: Class_Buffer): Class_RedisSortedSet; + + /** + * + * @brief 序列化给定 key ,并返回被序列化的值,使用 restore 命令可以将这个值反序列化为 Redis 键 + * @param key 指定要序列化的 key + * @return 返回序列化之后的值,如果 key 不存在,那么返回 null + * + * + */ + dump(key: Class_Buffer): Class_Buffer; + + /** + * + * @brief 反序列化给定的序列化值,并将它和给定的 key 关联 + * @param key 指定要反序列化的 key + * @param data 指定要反序列化的数据 + * @param ttl 以毫秒为单位为 key 设置生存时间;如果 ttl 为 0 ,那么不设置生存时间 + * + * + */ + restore(key: Class_Buffer, data: Class_Buffer, ttl?: number/** = 0*/): void; + + /** + * + * @brief 关闭当前数据库连接或事务 + * + * + */ + close(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/RedisHash.d.ts b/types/fibjs/declare/RedisHash.d.ts new file mode 100644 index 0000000000..9c2bc44ad7 --- /dev/null +++ b/types/fibjs/declare/RedisHash.d.ts @@ -0,0 +1,169 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Redis 数据库客户端 Hash 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @detail 用以操作 Redis 的 Hash 对象,创建方法:,```JavaScript,var db = require("db");,var rdb = new db.openRedis("redis-server");,var hash = rdb.getHash("test");,``` + */ + +declare class Class_RedisHash extends Class__object { + + + + /** + * + * @brief 将哈希表中的域 field 的值设为 value,如果域 field 已经存在于哈希表中,旧值将被覆盖 + * @param field 指定要修改的 field + * @param value 指定要修改的数据 + * + * + */ + set(field: Class_Buffer, value: Class_Buffer): void; + + /** + * + * @brief 将哈希表中的域 field 的值设置为 value ,当且仅当域 field 不存在。若域 field 已经存在,该操作无效 + * @param field 指定要修改的 field + * @param value 指定要修改的数据 + * + * + */ + setNX(field: Class_Buffer, value: Class_Buffer): void; + + /** + * + * @brief 同时将多个 field-value (域-值)对设置到哈希表中,此命令会覆盖哈希表中已存在的域 + * @param kvs 指定要设置的 field/value 对象 + * + * + */ + mset(kvs: Object): void; + + /** + * + * @brief 同时将多个 field-value (域-值)对设置到哈希表中,此命令会覆盖哈希表中已存在的域 + * @param kvs 指定要设置的 field/value 列表 + * + * + */ + mset(...kvs: any[]): void; + + /** + * + * @brief 返回哈希表中给定域 field 的值 + * @param field 指定要查询的 field + * @return 给定域的值,当给定域不存在或是给定 key 不存在时,返回 null + * + * + */ + get(field: Class_Buffer): Class_Buffer; + + /** + * + * @brief 返回哈希表中,一个或多个给定域的值 + * @param fields 指定要查询的域数组 + * @return 一个包含所有给定域的值的列表 + * + * + */ + mget(fields: any[]): any[]; + + /** + * + * @brief 返回哈希表中,一个或多个给定域的值 + * @param fields 指定要查询的域列表 + * @return 一个包含所有给定域的值的列表 + * + * + */ + mget(...fields: any[]): any[]; + + /** + * + * @brief 将域所储存的值加上增量 + * @param field 指定要修改的域 + * @param num 指定要加上的数值 + * @return 加上 num 之后,域的值 + * + * + */ + incr(field: Class_Buffer, num?: number/** = 1*/): number; + + /** + * + * @brief 返回哈希表中,所有的域和值 + * @return 返回一个包含哈希表中所有域的列表 + * + * + */ + getAll(): any[]; + + /** + * + * @brief 返回哈希表中的所有域 + * @return 返回值里,紧跟每个域名(field name)之后是域的值(value),所以返回值的长度是哈希表大小的两倍 + * + * + */ + keys(): any[]; + + /** + * + * @brief 返回哈希表中域的数量 + * @return 返回哈希表中域的数量 + * + * + */ + len(): number; + + /** + * + * @brief 查看哈希表中,给定域 field 是否存在 + * @param field 指定要查询的 field + * @return 如果哈希表含有给定域,返回 true,如果哈希表不含有给定域,或 key 不存在,返回 false + * + * + */ + exists(field: Class_Buffer): boolean; + + /** + * + * @brief 删除哈希表中的一个或多个指定域,不存在的域将被忽略 + * @param fields 指定要删除的域数组 + * @return 被删除域的数量 + * + * + */ + del(fields: any[]): number; + + /** + * + * @brief 删除哈希表中的一个或多个指定域,不存在的域将被忽略 + * @param fields 指定要删除的域列表 + * @return 被删除域的数量 + * + * + */ + del(...fields: any[]): number; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/RedisList.d.ts b/types/fibjs/declare/RedisList.d.ts new file mode 100644 index 0000000000..64d56a04f7 --- /dev/null +++ b/types/fibjs/declare/RedisList.d.ts @@ -0,0 +1,174 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Redis 数据库客户端 List 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @detail 用以操作 Redis 的 List 对象,创建方法:,```JavaScript,var db = require("db");,var rdb = new db.openRedis("redis-server");,var list = rdb.getList("test");,``` + */ + +declare class Class_RedisList extends Class__object { + + + + /** + * + * @brief 将一个或多个值 value 插入到列表的表头 + * @param values 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + push(values: any[]): number; + + /** + * + * @brief 将一个或多个值 value 插入到列表的表头 + * @param values 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + push(...values: any[]): number; + + /** + * + * @brief 移除并返回列表 key 的头元素 + * @return 列表的头元素,如果列表为空则返回 null + * + * + */ + pop(): Class_Buffer; + + /** + * + * @brief 将一个或多个值 value 插入到列表的表尾(最右边) + * @param values 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + rpush(values: any[]): number; + + /** + * + * @brief 将一个或多个值 value 插入到列表的表尾(最右边) + * @param values 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + rpush(...values: any[]): number; + + /** + * + * @brief 移除并返回列表 key 的表尾(最右边)元素 + * @return 列表的头元素,如果列表为空则返回 null + * + * + */ + rpop(): Class_Buffer; + + /** + * + * @brief 将列表下标为 index 的元素的值设置为 value + * @param index 指定要修改的下标 + * @param value 指定要修改的数据 + * + * + */ + set(index: number, value: Class_Buffer): void; + + /** + * + * @brief 返回列表中,下标为 index 的元素 + * @param index 指定要查询的下标 + * @return 列表中下标为 index 的元素 + * + * + */ + get(index: number): Class_Buffer; + + /** + * + * @brief 将值 value 插入到列表当中,位于值 pivot 之前 + * @param pivot 指定插入时查找的数据 + * @param value 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + insertBefore(pivot: Class_Buffer, value: Class_Buffer): number; + + /** + * + * @brief 将值 value 插入到列表当中,位于值 pivot 之后 + * @param pivot 指定插入时查找的数据 + * @param value 指定要插入的数据 + * @return 插入后,列表的长度 + * + * + */ + insertAfter(pivot: Class_Buffer, value: Class_Buffer): number; + + /** + * + * @brief 根据参数 count 的值,移除列表中与参数 value 相等的元素 + * @param count 指定删除的元素数量 + * @param value 指定要删除的数值 + * @return 被移除元素的数量 + * + * + */ + remove(count: number, value: Class_Buffer): number; + + /** + * + * @brief 对一个列表进行修剪(trim),就是说,让列表只保留指定区间内的元素,不在指定区间之内的元素都将被删除 + * @param start 指定修剪的起始下标,0 表示第一个元素,-1 表示最后一个元素 + * @param stop 指定修剪的结束下标,0 表示第一个元素,-1 表示最后一个元素 + * + * + */ + trim(start: number, stop: number): void; + + /** + * + * @brief 返回列表的长度 + * @return 返回列表的长度 + * + * + */ + len(): number; + + /** + * + * @brief 返回列表中指定区间内的元素,区间以偏移量 start 和 stop 指定,包含 start 和 stop 的元素 + * @param start 指定查询的起始下标,0 表示第一个元素,-1 表示最后一个元素 + * @param stop 指定查询的结束下标,0 表示第一个元素,-1 表示最后一个元素 + * @return 包含指定区间内的元素的数组 + * + * + */ + range(start: number, stop: number): any[]; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/RedisSet.d.ts b/types/fibjs/declare/RedisSet.d.ts new file mode 100644 index 0000000000..76e360ed7e --- /dev/null +++ b/types/fibjs/declare/RedisSet.d.ts @@ -0,0 +1,129 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Redis 数据库客户端 Set 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @detail 用以操作 Redis 的 Set 对象,创建方法:,```JavaScript,var db = require("db");,var rdb = new db.openRedis("redis-server");,var set = rdb.getSet("test");,``` + */ + +declare class Class_RedisSet extends Class__object { + + + + /** + * + * @brief 将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略 + * @param members 指定要添加的元素数组 + * @return 被添加到集合中的新元素的数量,不包括被忽略的元素 + * + * + */ + add(members: any[]): number; + + /** + * + * @brief 同时将多个 field-value (域-值)对设置到哈希表中,此命令会覆盖哈希表中已存在的域 + * @param members 指定要添加的元素列表 + * @return 被添加到集合中的新元素的数量,不包括被忽略的元素 + * + * + */ + add(...members: any[]): number; + + /** + * + * @brief 移除集合中的一个或多个 member 元素 + * @param members 指定要移除的元素数组 + * @return 被成功移除的元素的数量,不包括被忽略的元素 + * + * + */ + remove(members: any[]): number; + + /** + * + * @brief 移除集合中的一个或多个 member 元素 + * @param members 指定要移除的元素列表 + * @return 被成功移除的元素的数量,不包括被忽略的元素 + * + * + */ + remove(...members: any[]): number; + + /** + * + * @brief 返回集合中元素的数量 + * @return 返回集合的长度 + * + * + */ + len(): number; + + /** + * + * @brief 判断 member 元素是否集合的成员 + * @param member 指定检查的 member + * @return 如果 member 元素是集合的成员,返回 true + * + * + */ + exists(member: Class_Buffer): boolean; + + /** + * + * @brief 返回集合中的所有成员 + * @return 集合中所有成员的列表 + * + * + */ + members(): any[]; + + /** + * + * @brief 移除并返回集合中的一个随机元素 + * @return 被移除的随机元素。当集合是空集时,返回 null + * + * + */ + pop(): Class_Buffer; + + /** + * + * @brief 从集合中获取随机的一个元素 + * @return 返回一个元素;如果集合为空,返回 null + * + * + */ + randMember(): any; + + /** + * + * @brief 从集合中获取随机的若干元素 + * @param count 指定返回的元素个数。正数,返回一个包含 count 个元素的数组;负数,返回一个数组,数组中的元素可能会重复出现多次,而数组的长度为 count 的绝对值 + * @return 返回一个列表;如果集合为空,返回空列表 + * + * + */ + randMember(count: number): any; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/RedisSortedSet.d.ts b/types/fibjs/declare/RedisSortedSet.d.ts new file mode 100644 index 0000000000..8a98643ea9 --- /dev/null +++ b/types/fibjs/declare/RedisSortedSet.d.ts @@ -0,0 +1,158 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Redis 数据库客户端 SortedSet 对象,此对象为包含指定 key 的客户端,只有调用其方法才会操作数据库 + * @detail 用以操作 Redis 的 SortedSet 对象,创建方法:,```JavaScript,var db = require("db");,var rdb = new db.openRedis("redis-server");,var set = rdb.getSortedSet("test");,``` + */ + +declare class Class_RedisSortedSet extends Class__object { + + + + /** + * + * @brief 将一个或多个 member 元素及其 score 值加入到有序集当中 + * @param sms 指定要添加的 member/score 对象 + * @return 被成功添加的新成员的数量,不包括那些被更新的、已经存在的成员 + * + * + */ + add(sms: Object): number; + + /** + * + * @brief 将一个或多个 member 元素及其 score 值加入到有序集当中 + * @param sms 指定要添加的 member/score 列表 + * @return 被成功添加的新成员的数量,不包括那些被更新的、已经存在的成员 + * + * + */ + add(...sms: any[]): number; + + /** + * + * @brief 返回有序集中,成员 member 的 score 值 + * @param member 指定要查询的 member + * @return member 成员的 score 值,以字符串形式表示 + * + * + */ + score(member: Class_Buffer): Class_Buffer; + + /** + * + * @brief 为有序集的成员 member 的 score 值加上增量 num + * @param member 指定要修改的 member + * @param num 指定要加上的数值 + * @return member 成员的新 score 值,以字符串形式表示 + * + * + */ + incr(member: Class_Buffer, num?: number/** = 1*/): Class_Buffer; + + /** + * + * @brief 移除有序集中的一个或多个 member 元素 + * @param members 指定要移除的元素数组 + * @return 被成功移除的元素的数量,不包括被忽略的元素 + * + * + */ + remove(members: any[]): number; + + /** + * + * @brief 移除有序集中的一个或多个 member 元素 + * @param members 指定要移除的元素列表 + * @return 被成功移除的元素的数量,不包括被忽略的元素 + * + * + */ + remove(...members: any[]): number; + + /** + * + * @brief 返回有序集中元素的数量 + * @return 返回有序集的长度 + * + * + */ + len(): number; + + /** + * + * @brief 返回有序集中, score 值在 min 和 max 之间(默认包括 score 值等于 min 或 max )的成员的数量 + * @param min 指定统计的最小 score + * @param max 指定统计的最大 score + * @return score 值在 min 和 max 之间的成员的数量 + * + * + */ + count(min: number, max: number): number; + + /** + * + * @brief 返回有序集中,指定区间内的成员,成员的位置按 score 值递增(从小到大)来排序 + * @param start 指定查询的起始下标,0 表示第一个元素,-1 表示最后一个元素 + * @param stop 指定查询的结束下标,0 表示第一个元素,-1 表示最后一个元素 + * @param withScores 指定是否在结果中包含 score + * @return 指定区间内,带有 score 值(可选)的有序集成员的列表 + * + * + */ + range(start: number, stop: number, withScores?: boolean/** = false*/): any[]; + + /** + * + * @brief 返回有序集中,指定区间内的成员,成员的位置按 score 值递减(从大到小)来排序 + * @param start 指定查询的起始下标,0 表示第一个元素,-1 表示最后一个元素 + * @param stop 指定查询的结束下标,0 表示第一个元素,-1 表示最后一个元素 + * @param withScores 指定是否在结果中包含 score + * @return 指定区间内,带有 score 值(可选)的有序集成员的列表 + * + * + */ + rangeRev(start: number, stop: number, withScores?: boolean/** = false*/): any[]; + + /** + * + * @brief 有序集中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列 + * @param member 指定要查询的 member + * @return member 如果 member 是有序集 key 的成员,返回 member 的排名。如果 member 不是有序集 key 的成员,返回 nil + * + * + */ + rank(member: Class_Buffer): number; + + /** + * + * @brief 有序集中成员 member 的排名。其中有序集成员按 score 值递减(从大到小)顺序排列 + * @param member 指定要查询的 member + * @return member 如果 member 是有序集 key 的成员,返回 member 的排名。如果 member 不是有序集 key 的成员,返回 nil + * + * + */ + rankRev(member: Class_Buffer): number; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Routing.d.ts b/types/fibjs/declare/Routing.d.ts new file mode 100644 index 0000000000..af67796f22 --- /dev/null +++ b/types/fibjs/declare/Routing.d.ts @@ -0,0 +1,262 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 消息处理器路由对象 + * @detail 路由对象是 http 消息处理的核心对象,服务器根据路由的设定,匹配 url 和 method,并将 http 消息转发到相应的处理器,以完成不同的事务。,,一个简单的路由,可以直接以 JSON 对象的形式提供,比如:,```JavaScript,var http = require('http');,,var svr = new http.Server(8080, {, '/': r => r.response.write('home'),, '/help': r => r.response.write('help'),});,,svr.run();,```,如果需要更复杂的路由定制,可以自行创建 Routing 对象并根据需要处理路由策略:,```JavaScript,var http = require('http');,var mq = require('mq');,,var app = new mq.Routing();,,app.get('/', r => r.response.write('home'));,app.get('/help', r => r.response.write('help'));,,app.post('/help', r => r.response.write('post a help.'));,,app.get('/home/:user', (r, user) => r.response.write('hello ' + user));,,app.get('/user/:id(\\d+)', (r, id) => r.response.write('get ' + id));,,app.get('/actions', {, '/run': r => r.response.write('running'),, '/sleep': r => r.response.write('sleeping'),, '(.*)': r => r.response.write('........'),});,,var svr = new http.Server(8080, app);,svr.run();,```,路由对象根据设定的规则匹配消息,将消息传递给符合规则的第一个处理器。后加入的路由规则优先匹配。创建方法:,```JavaScript,var routing = new mq.Routing({, "^/func1(/.*)$": func1,, "^/func2(/.*)$": func2,});,```,正则表达式匹配的项目修改消息的 value 属性,子项目存入消息的 params 属性。例如:,```JavaScript,var routing = new mq.Routing({, "^/func1(/([0-9]+)/([0-9]+)\.html)$": func1,,});,```,匹配消息 "/func1/123/456.html" 后,value == "/123/456.html",params == ["123", "456"];,,如果匹配的结果没有子项,则 value 为空,params 为空。例如:,```JavaScript,var routing = new mq.Routing({, "^/func1/[0-9]+/[0-9]+\.html$": func1,,});,```,匹配消息 "/func1/123/456.html" 后,value == "",params == [];,,如果匹配的结果第一级有多个子项,则 value 为空,params 为第一级子项。例如:,```JavaScript,var routing = new mq.Routing({, "^/func1/([0-9]+)/([0-9]+)\.html$": func1,,});,```,匹配消息 "/func1/123/456.html" 后,value == "",params == ["123", "456"];,,如果匹配的结果只有一个子项,并且无下级子项,则 value 和 params 均为此子项。例如:,```JavaScript,var routing = new mq.Routing({, "^/func1/([0-9]+)/[0-9]+\.html$": func1,,});,```,匹配消息 "/func1/123/456.html" 后,value == "123",params == ["123"]; + */ +/// +declare class Class_Routing extends Class_Handler { + + + + /** + * + * @brief 创建一个消息处理器路由对象 + * @param map 初始化路由参数 + * + * + * + */ + constructor(map?: Object/** = v8::Object::New(isolate)*/); + + /** + * + * @brief 创建一个消息处理器路由对象 + * @param method 指定 http 请求方法,"*" 接受所有方法 + * @param map 初始化路由参数 + * + * + * + */ + constructor(method: string, map: Object); + + /** + * + * @brief 从已有路由对象中添加规则,添加后原路由将被清空 + * @param route 已经初始化的路由对象 + * @return 返回路由对象本身 + * + * + * + */ + append(route: Class_Routing): Class_Routing; + + /** + * + * @brief 添加一组路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + append(map: Object): Class_Routing; + + /** + * + * @brief 添加一条路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + append(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一条路由规则 + * @param method 指定 http 请求方法,"*" 接受所有方法 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + append(method: string, pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组接受所有 http 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + all(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受所有 http 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + all(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组 GET 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + get(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http GET 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + get(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组接受 http POST 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + post(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http POST 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + post(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组接受 http DELETE 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + del(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http DELETE 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + del(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组 PUT 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + put(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http PUT 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + put(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组 PATCH 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + patch(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http PATCH 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + patch(pattern: string, hdlr: Class_Handler): Class_Routing; + + /** + * + * @brief 添加一组 FIND 方法路由规则 + * @param map 路由参数 + * @return 返回路由对象本身 + * + * + * + */ + find(map: Object): Class_Routing; + + /** + * + * @brief 添加一条接受 http FIND 方法路由规则 + * @param pattern 消息匹配格式 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * @return 返回路由对象本身 + * + * + * + */ + find(pattern: string, hdlr: Class_Handler): Class_Routing; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SQLite.d.ts b/types/fibjs/declare/SQLite.d.ts new file mode 100644 index 0000000000..0eb314fe3b --- /dev/null +++ b/types/fibjs/declare/SQLite.d.ts @@ -0,0 +1,66 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief sqlite 数据库连接对象 + * @detail 使用 db.open 或 db.openSQLite 创建,创建方式:,```JavaScript,var slite = db.openSQLite("sqlite:/path/to/db");,``` + */ +/// +declare class Class_SQLite extends Class_DbConnection { + + /** + * class prop + * + * + * @brief 当前数据库文件名 + * + * @readonly + * @type String + */ + + fileName: string + + /** + * class prop + * + * + * @brief 查询和设置数据库超时时间,以毫秒为单位 + * + * + * @type Integer + */ + + timeout: number + + + + /** + * + * @brief 备份当前数据库到新文件 + * @param fileName 指定备份的数据库文件名 + * + * @async + */ + backup(fileName: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SandBox.d.ts b/types/fibjs/declare/SandBox.d.ts new file mode 100644 index 0000000000..5a0b2de6fb --- /dev/null +++ b/types/fibjs/declare/SandBox.d.ts @@ -0,0 +1,177 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 安全沙箱对象,用于管理一个独立的运行空间 + * @detail 所有的代码都运行在自己的沙箱中,全局的 require 会调用当前沙箱加载模块,沙箱会通过 require 传递给加载的沙箱。下面的示例创建一个沙箱,限制只允许访问全局基础模块中的 assert 模块,并添加 a 和 b 两个定制模块:,```JavaScript,var vm = require('vm');,var sbox = new vm.SandBox({, a: 100,, b: 200,, assert: require('assert'),});,,var mod_in_sbox = sbox.require('./path/to/mod');,``` + */ + +declare class Class_SandBox extends Class__object { + + /** + * class prop + * + * + * @brief 查询沙箱的 global 对象 + * + * @readonly + * @type Object + */ + + global: Object + + + + /** + * + * @brief 构造一个新的安全沙箱对象,并初始化基础模块 + * @param mods 指定要添加的模块对象字典 + * + * + * + */ + constructor(mods: Object); + + /** + * + * @brief 构造一个新的安全沙箱对象,并初始化基础模块 + * @param mods 指定要添加的模块对象字典 + * @param require 自定义 require 函数,当模块不存在时,先调用自定义函数,无返回再从文件中加载 + * + * + * + */ + constructor(mods: Object, require: Function); + + /** + * + * @brief 构造一个独立 Global 新的安全沙箱对象,并初始化基础模块 + * @param mods 指定要添加的模块对象字典 + * @param global 指定初始化的 Global 属性 + * + * + * + */ + constructor(mods: Object, global: Object); + + /** + * + * @brief 构造一个独立 Global 新的安全沙箱对象,并初始化基础模块 + * @param mods 指定要添加的模块对象字典 + * @param require 自定义 require 函数,当模块不存在时,先调用自定义函数,无返回再从文件中加载 + * @param global 指定初始化的 Global 属性 + * + * + * + */ + constructor(mods: Object, require: Function, global: Object); + + /** + * + * @brief 向沙箱中添加一个基础模块 + * @param id 指定要添加的模块名称,此路径与当前运行脚本无关,必须为绝对路径或者模块名 + * @param mod 指定要添加的模块对象 + * + * + * + */ + add(id: string, mod: any): void; + + /** + * + * @brief 向沙箱中添加一组基础模块 + * @param mods 指定要添加的模块对象字典,添加的 javascript 模块将会生成一份复制,以避免沙箱修改对象产生互相干扰 + * + * + * + */ + add(mods: Object): void; + + /** + * + * @brief 向沙箱中添加一个脚本模块 + * @param srcname 指定要添加的脚本名称,srcname 必须包含扩展名,比如 json 或者 js, jsc + * @param script 指定要添加的二进制代码 + * @return 返回加载的模块对象 + * + * + * + */ + addScript(srcname: string, script: Class_Buffer): any; + + /** + * + * @brief 从沙箱中删除指定的基础模块 + * @param id 指定要删除的模块名称,此路径与当前运行脚本无关,必须为绝对路径或者模块名 + * + * + * + */ + remove(id: string): void; + + /** + * + * @brief 复制当前沙箱,新沙箱包含当前沙箱的模块,以及相同的名称和 require 函数 + * @return 复制的新沙箱 + * + * + * + */ + clone(): Class_SandBox; + + /** + * + * @brief 运行一个脚本 + * @param fname 指定要运行的脚本路径,此路径与当前运行脚本无关,必须为绝对路径 + * @param argv 指定要运行的参数,此参数可在脚本内使用 argv 获取 + * + * + * + */ + run(fname: string, argv?: any[]/** = v8::Array::New(isolate)*/): void; + + /** + * + * @brief 查询一个模块并返回模块完整文件名 + * @param id 指定要加载的模块名称 + * @param base 指定查找路径 + * @return 返回加载的模块完整文件名 + * + * + * + */ + resolve(id: string, base: string): string; + + /** + * + * @brief 加载一个模块并返回模块对象 + * @param id 指定要加载的模块名称 + * @param base 指定查找路径 + * @return 返回加载的模块对象 + * + * + * + */ + require(id: string, base: string): any; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SeekableStream.d.ts b/types/fibjs/declare/SeekableStream.d.ts new file mode 100644 index 0000000000..4b7a989346 --- /dev/null +++ b/types/fibjs/declare/SeekableStream.d.ts @@ -0,0 +1,112 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 可移动当前指针的流对象接口 + * @detail + */ +/// +declare class Class_SeekableStream extends Class_Stream { + + + + /** + * + * @brief 移动文件当前操作位置 + * @param offset 指定新的位置 + * @param whence 指定位置基准,允许的值为:SEEK_SET, SEEK_CUR, SEEK_END + * + * + * + */ + seek(offset: number, whence: number): void; + + /** + * + * @brief 查询流当前位置 + * @return 返回流当前位置 + * + * + * + */ + tell(): number; + + /** + * + * @brief 移动当前位置到流开头 + * + * + */ + rewind(): void; + + /** + * + * @brief 查询流尺寸 + * @return 返回流尺寸 + * + * + * + */ + size(): number; + + /** + * + * @brief 从流内读取剩余的全部数据 + * @return 返回从流内读取的数据,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + readAll(): Class_Buffer; + + /** + * + * @brief 修改文件尺寸,如果新尺寸小于原尺寸,则文件被截断 + * @param bytes 新的文件尺寸 + * + * + * @async + */ + truncate(bytes: number): void; + + /** + * + * @brief 查询文件是否到结尾 + * @return 返回 True 表示结尾 + * + * + * + */ + eof(): boolean; + + /** + * + * @brief 查询当前文件的基础信息 + * @return 返回 Stat 对象描述文件信息 + * + * + * @async + */ + stat(): Class_Stat; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Semaphore.d.ts b/types/fibjs/declare/Semaphore.d.ts new file mode 100644 index 0000000000..b35c8636ab --- /dev/null +++ b/types/fibjs/declare/Semaphore.d.ts @@ -0,0 +1,69 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 纤程信号量对象 + * @detail 信号量对象管理一个内部计数器,此计数器调用 acquire 或者 wait 后减一,调用 release 或者 post 后加一。,计数器不会减至负数,因为 acquire 和 wait 在发现数值为 0 的时候,会休眠当前纤程,直至其它纤程通过 release 或 post 增加计数器的值。,,信号量常用的场合是限制资源并发使用,以及生产者/消费者模式的应用。,,以数据库请求为例,限制资源并发使用的情形:,```JavaScript,var maxconnections = 5;,var l = new coroutine.Semaphore(maxconnections);,,......,,l.acquire();,var conn = connectdb(),.....,conn.close();,l.release();,```,,生产者/消费者模式通常则将信号量与队列配合使用。生产者向队列中加入数据,并 post 一个信号,消费者则先 wait 信号,获取信号后去队查询取数据。 + */ +/// +declare class Class_Semaphore extends Class_Lock { + + + + /** + * + * @brief 信号量构造函数 + * @param value 计数器初始数值 + * + * + * + */ + constructor(value?: number/** = 1*/); + + /** + * + * @brief 等待一个信号量,等同于 acquire(true) + * + * + */ + wait(): void; + + /** + * + * @brief 释放一个信号量,等同于 release() + * + * + */ + post(): void; + + /** + * + * @brief 尝试获取一个信号,如不能获取,则立即返回并返回 false,等同于 acquire(false) + * @return 获取成功则返回 true + * + * + * + */ + trywait(): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Service.d.ts b/types/fibjs/declare/Service.d.ts new file mode 100644 index 0000000000..5ce3b5e064 --- /dev/null +++ b/types/fibjs/declare/Service.d.ts @@ -0,0 +1,176 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 系统服务管理对象 + * @detail + */ +/// +declare class Class_Service extends Class_EventEmitter { + + /** + * class prop + * + * + * @brief 查询和设置服务名称 + * + * + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 查询和绑定服务停止事件,相当于 on("stop", func); + * + * + * @type Function + */ + + onstop: Function + + /** + * class prop + * + * + * @brief 查询和绑定服务暂停事件,相当于 on("pause", func); + * + * + * @type Function + */ + + onpause: Function + + /** + * class prop + * + * + * @brief 查询和绑定服务恢复事件,相当于 on("continue", func); + * + * + * @type Function + */ + + oncontinue: Function + + + + /** + * + * @brief 系统服务管理对象构造函数 + * @param name 服务名称 + * @param worker 服务运行函数 + * @param event 服务事件处理 + * + * + * + */ + constructor(name: string, worker: Function, event?: Object/** = v8::Object::New(isolate)*/); + + /** + * + * @brief 开始运行服务实体 + * + * @async + */ + run(): void; + + /** + * + * @brief 安装服务到系统 + * @param name 服务名称 + * @param cmd 服务命令行 + * @param displayName 服务显示名称 + * @param description 服务描述信息 + * + * + * + */ + static install(name: string, cmd: string, displayName?: string/** = ""*/, description?: string/** = ""*/): void; + + /** + * + * @brief 从系统中卸载服务 + * @param name 服务名称 + * + * + * + */ + static remove(name: string): void; + + /** + * + * @brief 启动服务 + * @param name 服务名称 + * + * + * + */ + static start(name: string): void; + + /** + * + * @brief 停止服务 + * @param name 服务名称 + * + * + * + */ + static stop(name: string): void; + + /** + * + * @brief 重启服务 + * @param name 服务名称 + * + * + * + */ + static restart(name: string): void; + + /** + * + * @brief 检测服务是否安装 + * @param name 服务名称 + * @return 服务安装返回 True + * + * + * + */ + static isInstalled(name: string): boolean; + + /** + * + * @brief 检测服务是否运行 + * @param name 服务名称 + * @return 服务运行返回 True + * + * + * + */ + static isRunning(name: string): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Smtp.d.ts b/types/fibjs/declare/Smtp.d.ts new file mode 100644 index 0000000000..9c320582be --- /dev/null +++ b/types/fibjs/declare/Smtp.d.ts @@ -0,0 +1,146 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Smtp对象 + * @detail + */ + +declare class Class_Smtp extends Class__object { + + /** + * class prop + * + * + * @brief 查询和设置超时时间 单位毫秒 + * + * + * @type Integer + */ + + timeout: number + + /** + * class prop + * + * + * @brief 查询 Smtp 对象当前连接的 Socket + * + * @readonly + * @type Stream + */ + + socket: Class_Stream + + + + /** + * + * @brief Smtp 对象构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 建立到指定的服务器 + * @param url 指定连接的协议,可以是:tcp://host:port 或者 ssl://host:port + * + * + * @async + */ + connect(url: string): void; + + /** + * + * @brief 发送指定命令,并返回响应,服务器报错则抛出错误 + * @param cmd 命令名 + * @param arg 参数 + * @return 如果成功,返回服务器响应 + * + * + * @async + */ + command(cmd: string, arg: string): string; + + /** + * + * @brief 发送 HELO 命令,服务器报错则抛出错误 + * @param hostname 主机名,缺省为“localhost” + * + * + * @async + */ + hello(hostname?: string/** = "localhost"*/): void; + + /** + * + * @brief 用指定的用户及密码登录服务器,服务器报错则抛出错误 + * @param username 用户名 + * @param password 密码 + * + * + * @async + */ + login(username: string, password: string): void; + + /** + * + * @brief 指定发件人信箱,服务器报错则抛出错误 + * @param address 发件人信箱 + * + * + * @async + */ + from(address: string): void; + + /** + * + * @brief 指定收件人信箱,服务器报错则抛出错误 + * @param address 收件人信箱 + * + * + * @async + */ + to(address: string): void; + + /** + * + * @brief 发送文本到收件人,服务器报错则抛出错误 + * @param txt 要发送的文本 + * + * + * @async + */ + data(txt: string): void; + + /** + * + * @brief 退出并关闭连接,服务器报错则抛出错误 + * + * @async + */ + quit(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Socket.d.ts b/types/fibjs/declare/Socket.d.ts new file mode 100644 index 0000000000..a3de6699a5 --- /dev/null +++ b/types/fibjs/declare/Socket.d.ts @@ -0,0 +1,232 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + + + +/** module Or Internal Object */ +/** + * @brief 网络套接口对象 + * @detail Socket 属于 net 模块,创建方法,```JavaScript,var s = new net.Socket();,``` + */ +/// +declare class Class_Socket extends Class_Stream { + + /** + * class prop + * + * + * @brief 查询当前 Socket 对象的地址集 + * + * @readonly + * @type Integer + */ + + family: number + + /** + * class prop + * + * + * @brief 查询当前 Socket 对象的协议族 + * + * @readonly + * @type Integer + */ + + type: number + + /** + * class prop + * + * + * @brief 查询当前连接的对方地址 + * + * @readonly + * @type String + */ + + remoteAddress: string + + /** + * class prop + * + * + * @brief 查询当前连接的对方端口 + * + * @readonly + * @type Integer + */ + + remotePort: number + + /** + * class prop + * + * + * @brief 查询当前连接的本地地址 + * + * @readonly + * @type String + */ + + localAddress: string + + /** + * class prop + * + * + * @brief 查询当前连接的本地端口 + * + * @readonly + * @type Integer + */ + + localPort: number + + /** + * class prop + * + * + * @brief 查询和设置超时时间 单位毫秒 + * + * + * @type Integer + */ + + timeout: number + + + + /** + * + * @brief Socket 构造函数,创建一个新的 Socket 对象 + * @param family 指定地址集,缺省为 AF_INET,ipv4 + * @param type 指定协议族,缺省为 SOCK_STREAM,tcp + * + * + * + */ + constructor(family?: number/** = undefined*/, type?: number/** = undefined*/); + + /** + * + * @brief 建立一个 tcp 连接 + * @param host 指定对方地址或主机名 + * @param port 指定对方端口 + * + * + * @async + */ + connect(host: string, port: number): void; + + /** + * + * @brief 将当前 Socket 绑定至本地所有地址的指定端口 + * @param port 指定绑定的端口 + * @param allowIPv4 指定是否接受 ipv4 连接,缺省为 true。本参数在 ipv6 时有效,并依赖于操作系统 + * + * + * + */ + bind(port: number, allowIPv4?: boolean/** = true*/): void; + + /** + * + * @brief 将当前 Socket 绑定至指定地址的指定端口 + * @param addr 指定绑定的地址 + * @param port 指定绑定的端口 + * @param allowIPv4 指定是否接受 ipv4 连接,缺省为 true。本参数在 ipv6 时有效,并依赖于操作系统 + * + * + * + */ + bind(addr: string, port: number, allowIPv4?: boolean/** = true*/): void; + + /** + * + * @brief 开始监听连接请求 + * @param backlog 指定请求队列长度,超出的请求将被拒绝,缺省为 120 + * + * + * + */ + listen(backlog?: number/** = 120*/): void; + + /** + * + * @brief 等待并接受一个连接 + * @return 返回接收到得连接对象 + * + * + * @async + */ + accept(): Class_Socket; + + /** + * + * @brief 从连接读取指定大小的数据,不同于 read 方法,recv 并不保证读完要求的数据,而是在读取到数据后立即返回 + * @param bytes 指定要读取的数据量,缺省读取任意尺寸的数据 + * @return 返回从连接读取的数据 + * + * + * @async + */ + recv(bytes?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 读取一个 UDP 包 + * recvfrom 返回结果中包含以下内容: + * - data: 接收到的二进制数据块 + * - address: 发送方的地址 + * - port: 发送方的端口 + * @param bytes 指定要读取的数据量,缺省读取任意尺寸的数据 + * @return 返回从连接读取的数据包 + * + * + * @async + */ + recvfrom(bytes?: number/** = -1*/): any; + + /** + * + * @brief 将给定的数据写入连接,此方法等效于 write 方法 + * @param data 给定要写入的数据 + * + * + * @async + */ + send(data: Class_Buffer): void; + + /** + * + * @brief 向给定 ip:port 发送一个 UDP 包 + * @param data 给定要写入的数据 + * @param host 指定目标 ip 或主机名 + * @param port 指定目标端口 + * + * + * @async + */ + sendto(data: Class_Buffer, host: string, port: number): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SslHandler.d.ts b/types/fibjs/declare/SslHandler.d.ts new file mode 100644 index 0000000000..1ed85a5ce0 --- /dev/null +++ b/types/fibjs/declare/SslHandler.d.ts @@ -0,0 +1,106 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief ssl 协议转换处理器 + * @detail 用以将数据流转换为 ssl 流协议。SslHandler 是对 SslSocket 的封装,用于构建服务器,逻辑上相当于:,```JavaScript,var ss = new ssl.Socket(crt, key);,,function(s){, var s1 = ss.accept(s);, hdlr.invoke(s1);, s1.close();,},``` + */ +/// +declare class Class_SslHandler extends Class_Handler { + + /** + * class prop + * + * + * @brief 设定证书验证模式,缺省为 VERIFY_NONE + * + * + * @type Integer + */ + + verification: number + + /** + * class prop + * + * + * @brief 客户端证书验证证书链 + * + * @readonly + * @type X509Cert + */ + + ca: Class_X509Cert + + /** + * class prop + * + * + * @brief ssl 协议转换处理器当前事件处理接口对象 + * + * + * @type Handler + */ + + handler: Class_Handler + + + + /** + * + * @brief SslHandler 构造函数,创建一个新的 SslHandler 对象 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(certs: any[], hdlr: Class_Handler); + + /** + * + * @brief SslHandler 构造函数,创建一个新的 SslHandler 对象 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey, hdlr: Class_Handler); + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SslServer.d.ts b/types/fibjs/declare/SslServer.d.ts new file mode 100644 index 0000000000..0213c0b10e --- /dev/null +++ b/types/fibjs/declare/SslServer.d.ts @@ -0,0 +1,137 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief ssl 服务器对象,可方便创建一个标准多纤程 ssl 服务器 + * @detail SslServer 对象是将 TcpServer 和 SslHandler 组合封装的对象,方便快速搭建服务器,逻辑上相当于:,```JavaScript,var svr = new net.SslServer(addr, port, new ssl.Handler(crt, key, function(req){, ...,}));,```,,创建方法:,```JavaScript,var ssl = require("ssl");,var svr = new http.Server(crt, key, function(req){, ...,});,``` + */ +/// +declare class Class_SslServer extends Class_TcpServer { + + /** + * class prop + * + * + * @brief 设定证书验证模式,缺省为 VERIFY_NONE + * + * + * @type Integer + */ + + verification: number + + /** + * class prop + * + * + * @brief 客户端证书验证证书链 + * + * @readonly + * @type X509Cert + */ + + ca: Class_X509Cert + + + + /** + * + * @brief SslServer 构造函数,在所有本机地址侦听 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * @param port 指定 ssl 服务器侦听端口 + * @param listener 指定 ssl 接收到的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(certs: any[], port: number, listener: Class_Handler); + + /** + * + * @brief SslServer 构造函数 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * @param addr 指定 ssl 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 ssl 服务器侦听端口 + * @param listener 指定 ssl 接收到的连接的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(certs: any[], addr: string, port: number, listener: Class_Handler); + + /** + * + * @brief SslServer 构造函数,在所有本机地址侦听 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * @param port 指定 ssl 服务器侦听端口 + * @param listener 指定 ssl 接收到的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey, port: number, listener: Class_Handler); + + /** + * + * @brief SslServer 构造函数 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * @param addr 指定 ssl 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 ssl 服务器侦听端口 + * @param listener 指定 ssl 接收到的连接的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey, addr: string, port: number, listener: Class_Handler); + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SslSocket.d.ts b/types/fibjs/declare/SslSocket.d.ts new file mode 100644 index 0000000000..4b7b6986e8 --- /dev/null +++ b/types/fibjs/declare/SslSocket.d.ts @@ -0,0 +1,139 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief ssl 网络套接口对象 + * @detail SslSocket 属于 ssl 模块,创建方法,```JavaScript,var s = new ssl.Socket();,``` + */ +/// +declare class Class_SslSocket extends Class_Stream { + + /** + * class prop + * + * + * @brief 设定证书验证模式,缺省为 VERIFY_REQUIRED + * + * + * @type Integer + */ + + verification: number + + /** + * class prop + * + * + * @brief 证书链,客户端模式 connect 时自动引用 ssl.ca,服务器模式 accept 生成 SslSocket 自动引用当前 SslSocket 的 ca + * + * @readonly + * @type X509Cert + */ + + ca: Class_X509Cert + + /** + * class prop + * + * + * @brief 连接对方的证书 + * + * @readonly + * @type X509Cert + */ + + peerCert: Class_X509Cert + + /** + * class prop + * + * + * @brief 查询消息 ssl 建立时的下层流对象 + * + * @readonly + * @type Stream + */ + + stream: Class_Stream + + + + /** + * + * @brief SslSocket 构造函数,创建一个新的 SslSocket 对象 + * + * certs 格式为: + * ```JavaScript + * [ + * { + * crt: [X509Cert object], + * key: [PKey object] + * }, + * { + * crt: [X509Cert object], + * key: [PKey object] + * } + * ] + * ``` + * @param certs 服务器证书列表 + * + * + * + */ + constructor(certs?: any[]/** = v8::Array::New(isolate)*/); + + /** + * + * @brief SslSocket 构造函数,创建一个新的 SslSocket 对象 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * + * + * + */ + constructor(crt: Class_X509Cert, key: Class_PKey); + + /** + * + * @brief 在给定的连接上连接 ssl 连接,客户端模式 + * @param s 给定的底层连接 + * @param server_name 指定服务器名称,可缺省 + * @return 连接成功返回 0,证书可选验证时,验证不成功则返回非 0,详细错误见 ssl 模块 + * + * + * @async + */ + connect(s: Class_Stream, server_name?: string/** = ""*/): number; + + /** + * + * @brief 在给定的连接上接收一个 ssl 连接,并生成一个新的 SslSocket + * @param s 给定的底层连接 + * @return 返回新建立的 SslSocket 对象 + * + * + * @async + */ + accept(s: Class_Stream): Class_SslSocket; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Stat.d.ts b/types/fibjs/declare/Stat.d.ts new file mode 100644 index 0000000000..fef64f6c73 --- /dev/null +++ b/types/fibjs/declare/Stat.d.ts @@ -0,0 +1,219 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 文件的基础信息对象 + * @detail Stat 对象通过 fs.stat, File.stat, fs.readdir 查询,不可独立创建 + */ + +declare class Class_Stat extends Class__object { + + /** + * class prop + * + * + * @brief 文件名称 + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 文件尺寸 + * + * @readonly + * @type Long + */ + + size: number + + /** + * class prop + * + * + * @brief 文件权限,Windows 不支持此属性 + * + * @readonly + * @type Integer + */ + + mode: number + + /** + * class prop + * + * + * @brief 文件最后修改时间 + * + * @readonly + * @type Date + */ + + mtime: Date + + /** + * class prop + * + * + * @brief 文件最后访问时间 + * + * @readonly + * @type Date + */ + + atime: Date + + /** + * class prop + * + * + * @brief 文件创建时间 + * + * @readonly + * @type Date + */ + + ctime: Date + + /** + * class prop + * + * + * @brief 文件拥有者的id + * + * @readonly + * @type Integer + */ + + uid: number + + /** + * class prop + * + * + * @brief 文件所属的组id + * + * @readonly + * @type Integer + */ + + gid: number + + + + /** + * + * @brief 查询文件是否有写入权限 + * @return 为 true 则有写入权限 + * + * + * + */ + isWritable(): boolean; + + /** + * + * @brief 查询文件是否有读权限 + * @return 为 true 则有读权限 + * + * + * + */ + isReadable(): boolean; + + /** + * + * @brief 查询文件是否有执行权限 + * @return 为 true 则有执行权限 + * + * + * + */ + isExecutable(): boolean; + + /** + * + * @brief 查询文件是否隐藏 + * @return 为 true 则隐藏 + * + * + * + */ + isHidden(): boolean; + + /** + * + * @brief 查询文件是否是目录 + * @return 为 true 则是目录 + * + * + * + */ + isDirectory(): boolean; + + /** + * + * @brief 查询文件是否是文件 + * @return 为 true 则是文件 + * + * + * + */ + isFile(): boolean; + + /** + * + * @brief 查询文件是否是符号链接 + * @return 为 true 则是符号链接 + * + * + * + */ + isSymbolicLink(): boolean; + + /** + * + * @brief 查询文件是否是内存文件 + * @return 为 true 则是内存文件 + * + * + * + */ + isMemory(): boolean; + + /** + * + * @brief 查询文件是否是 Socket + * @return 为 true 则是 Socket + * + * + * + */ + isSocket(): boolean; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Stats.d.ts b/types/fibjs/declare/Stats.d.ts new file mode 100644 index 0000000000..7e9a96d1c4 --- /dev/null +++ b/types/fibjs/declare/Stats.d.ts @@ -0,0 +1,103 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 数据统计对象,用以构建应用运行时数据收集 + * @detail 创建方法:,```JavaScript,var util = require("util");,var stats = new util.Stats(["begin", "end", "error"]);,```,一些内部对象会提供预先定义的的统计对象 + */ + +declare class Class_Stats extends Class__object { + + + + /** + * + * @brief 数据统计对象构造方法 + * @param keys 指定计数器的名称 + * + * + * + */ + constructor(keys: any[]); + + /** + * + * @brief 数据统计对象构造方法 + * @param staticKeys 指定静态计数器的名称,静态计数器不会被 reset + * @param keys 指定计数器的名称 + * + * + * + */ + constructor(staticKeys: any[], keys: any[]); + + /** + * + * @brief 指定的计数器增一 + * @param key 指定计数器名称 + * + * + * + */ + inc(key: string): void; + + /** + * + * @brief 指定的计数器减一 + * @param key 指定计数器名称 + * + * + * + */ + dec(key: string): void; + + /** + * + * @brief 指定的计数器加指定值 + * @param key 指定计数器名称 + * @param value 指定数值 + * + * + * + */ + add(key: string, value: number): void; + + /** + * + * @brief 初始化计数器,除 staticKeys 指定的计数器全部清零 + * + * + */ + reset(): void; + + /** + * + * @brief 查询上次 reset 到现在的运行时间 + * @return 返回上次 reset 到现在的运行时间 + * + * + * + */ + uptime(): number; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Stream.d.ts b/types/fibjs/declare/Stream.d.ts new file mode 100644 index 0000000000..723cc78fae --- /dev/null +++ b/types/fibjs/declare/Stream.d.ts @@ -0,0 +1,82 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 流操作对象,用于二进制数据流读写 + * @detail Stream 为基础对象,用于为流处理定义标准借口,不能独立创建 + */ + +declare class Class_Stream extends Class__object { + + + + /** + * + * @brief 从流内读取指定大小的数据 + * @param bytes 指定要读取的数据量,缺省为读取随机大小的数据块,读出的数据尺寸取决于设备 + * @return 返回从流内读取的数据,若无数据可读,或者连接中断,则返回 null + * + * + * @async + */ + read(bytes?: number/** = -1*/): Class_Buffer; + + /** + * + * @brief 将给定的数据写入流 + * @param data 给定要写入的数据 + * + * + * @async + */ + write(data: Class_Buffer): void; + + /** + * + * @brief 将文件缓冲区内容写入物理设备 + * + * @async + */ + flush(): void; + + /** + * + * @brief 关闭当前流对象 + * + * @async + */ + close(): void; + + /** + * + * @brief 复制流数据到目标流中 + * @param stm 目标流对象 + * @param bytes 复制的字节数 + * @return 返回复制的字节数 + * + * + * @async + */ + copyTo(stm: Class_Stream, bytes?: number/** = -1*/): number; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/StringDecoder.d.ts b/types/fibjs/declare/StringDecoder.d.ts new file mode 100644 index 0000000000..7958f2d74d --- /dev/null +++ b/types/fibjs/declare/StringDecoder.d.ts @@ -0,0 +1,146 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 流解码对象 + * @detail + */ + +declare class Class_StringDecoder extends Class__object { + + /** + * class prop + * + * + * @brief 内部使用。 + * + * + * @type Integer + */ + + lastNeed: number + + /** + * class prop + * + * + * @brief 内部使用。 + * + * + * @type Integer + */ + + lastTotal: number + + /** + * class prop + * + * + * @brief 内部使用。 + * + * + * @type Buffer + */ + + lastChar: Class_Buffer + + /** + * class prop + * + * + * @brief 解码编码.内部使用。 + * + * + * @type String + */ + + encoding: string + + + + /** + * + * @brief 解码器构造函数 + * @param encoding 解码编码. 默认 'utf8'. + * + * + * + */ + constructor(encoding?: string/** = "utf8"*/); + + /** + * + * @brief 将内部存留的 buffer 作为字符返回。不完整的 UTF-8 和 UTF-16 字节会尝试补全。 + * @return 解码后的字符串. + * + * + * + */ + end(): string; + + /** + * + * @brief 将内部存留的 buffer 作为字符返回。不完整的 UTF-8 和 UTF-16 字节会尝试补全。 + * @param buf 需要解码的 Buffer. 在执行 end 之前,会先调用 write 将 buffer 写入。 + * @return 解码后的字符串. + * + * + * + */ + end(buf: Class_Buffer): string; + + /** + * + * @brief 返回一个解码后的字符串, 确保任何非完整的末尾字符被省略此次不返回,并被存储在内部供下一次的 write 或者 end 方法使用。 + * @param buf 需要解码的 Buffer。 + * @return 解码后的字符串. + * + * + * + */ + write(buf: Class_Buffer): string; + + /** + * + * @brief 内部使用。. + * @param buf 需要解码的 Buffer。 + * @param offset 解码偏移量 + * @return 解码后的字符串. + * + * + * + */ + text(buf: Class_Buffer, offset: number): string; + + /** + * + * @brief 内部使用。. + * @param buf A Buffer containing the bytes to decode. + * @return 解码后的字符串. + * + * + * + */ + fillLast(buf: Class_Buffer): string; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/SubProcess.d.ts b/types/fibjs/declare/SubProcess.d.ts new file mode 100644 index 0000000000..774e121eb5 --- /dev/null +++ b/types/fibjs/declare/SubProcess.d.ts @@ -0,0 +1,103 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 子进程对象 + * @detail ```JavaScript,var process = require("process");,var sub = process.open("ls");,``` + */ +/// +declare class Class_SubProcess extends Class_BufferedStream { + + /** + * class prop + * + * + * @brief 读取当前对象指向的进程的 id + * + * + * @readonly + * @type Integer + */ + + pid: number + + /** + * class prop + * + * + * @brief 读取当前对象指向的进程的标准输入对象 + * + * + * @readonly + * @type BufferedStream + */ + + stdin: Class_BufferedStream + + /** + * class prop + * + * + * @brief 读取当前对象指向的进程的标准输出对象 + * + * + * @readonly + * @type BufferedStream + */ + + stdout: Class_BufferedStream + + + + /** + * + * @brief 杀掉当前对象指向的进程,并传递信号 + * @param signal 传递的信号 + * + * + * + */ + kill(signal: number): void; + + /** + * + * @brief 等待当前对象指向的进程结束,并返回进程结束代码 + * @return 进程的结束代码 + * + * + * @async + */ + wait(): number; + + /** + * + * @brief 查询当前对象所指向的进程是否存在指定名称的窗口,仅限 windows + * @param name 窗口名称 + * @return 窗口存在则返回窗口的 rect,否则返回 undefined + * + * + * + */ + findWindow(name: string): any; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/TcpServer.d.ts b/types/fibjs/declare/TcpServer.d.ts new file mode 100644 index 0000000000..065288c1f1 --- /dev/null +++ b/types/fibjs/declare/TcpServer.d.ts @@ -0,0 +1,127 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief tcp 服务器对象,可方便创建一个标准多纤程 tcp 服务器 + * @detail 使用 TcpServer 对象可以迅速创建一个多纤程并发处理的 tcp 服务器。,```JavaScript,function func(conn),{, var data;,, while(data = conn.read()), conn.write(data);,, conn.close();,},,new net.TcpServer(8080, func).run();,``` + */ + +declare class Class_TcpServer extends Class__object { + + /** + * class prop + * + * + * @brief 服务器当前侦听的 Socket 对象 + * + * @readonly + * @type Socket + */ + + socket: Class_Socket + + /** + * class prop + * + * + * @brief 服务器当前事件处理接口对象 + * + * + * @type Handler + */ + + handler: Class_Handler + + /** + * class prop + * + * + * @brief 查询当前服务器运行状态 + * + * 返回的结果为一个 Stats 对象,初始化计数器如下: + * ```JavaScript + * { + * total : 1000, // 总计处理的连接 + * connections : 100, // 当前正在处理的连接 + * accept : 10, // 上次查询后新建的连接 + * close : 10 // 上次查询后关闭的连接 + * } + * ``` + * + * + * @readonly + * @type Stats + */ + + stats: Class_Stats + + + + /** + * + * @brief TcpServer 构造函数,在所有本机地址侦听 + * @param port 指定 tcp 服务器侦听端口 + * @param listener 指定 tcp 接收到的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(port: number, listener: Class_Handler); + + /** + * + * @brief TcpServer 构造函数 + * @param addr 指定 tcp 服务器侦听地址,为 "" 则在本机所有地址侦听 + * @param port 指定 tcp 服务器侦听端口 + * @param listener 指定 tcp 接收到的连接的内置消息处理器,处理函数,链式处理数组,路由对象,详见 mq.Handler + * + * + * + */ + constructor(addr: string, port: number, listener: Class_Handler); + + /** + * + * @brief 运行服务器并开始接收和分发连接,此函数不会返回 + * + * @async + */ + run(): void; + + /** + * + * @brief 异步运行服务器并开始接收和分发连接,调用后立即返回,服务器在后台运行 + * + * + */ + asyncRun(): void; + + /** + * + * @brief 关闭 socket中止正在运行的服务器 + * + * @async + */ + stop(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Timer.d.ts b/types/fibjs/declare/Timer.d.ts new file mode 100644 index 0000000000..b512d36afb --- /dev/null +++ b/types/fibjs/declare/Timer.d.ts @@ -0,0 +1,73 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 定时器处理器对象 + * @detail + */ + +declare class Class_Timer extends Class__object { + + /** + * class prop + * + * + * @brief 查询当前定时器是否已经终止 + * + * @readonly + * @type Boolean + */ + + stopped: boolean + + + + /** + * + * @brief 维持 fibjs 进程不退出,在定时器等待期间阻止 fibjs 进程退出 + * @return 返回定时器对象 + * + * + * + */ + ref(): Class_Timer; + + /** + * + * @brief 允许 fibjs 进程退出,在定时器等待期间允许 fibjs 进程退出 + * @return 返回定时器对象 + * + * + * + */ + unref(): Class_Timer; + + /** + * + * @brief 取消当前定时器 + * + * + */ + clear(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/UrlObject.d.ts b/types/fibjs/declare/UrlObject.d.ts new file mode 100644 index 0000000000..65d9d59e38 --- /dev/null +++ b/types/fibjs/declare/UrlObject.d.ts @@ -0,0 +1,279 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief Url 处理对象 + * @detail 基础模块。提供 url 的格式化,解析与拼装,```JavaScript,var url = new net.Url('http://www.xici.net/');,var url = new net.Url({protocol: 'http:', hostname:'www.xici.net', pathname:'/'});,``` + */ + +declare class Class_UrlObject extends Class__object { + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的完整 url 地址描述,此描述由其他所有属性组装而成 + * + * + * + * @type String + */ + + href: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的协议名称 + * + * + * + * @type String + */ + + protocol: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象是否包含双斜杠 + * + * + * + * @type Boolean + */ + + slashes: boolean + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的完整验证字符串,由 username 和 password 属性组装而成 + * + * + * + * @type String + */ + + auth: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的验证用户 + * + * + * + * @type String + */ + + username: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的验证密码 + * + * + * + * @type String + */ + + password: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的完整主机描述,由 hastname 和 port 组装而成 + * + * + * + * @type String + */ + + host: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的主机名 + * + * + * + * @type String + */ + + hostname: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的端口号 + * + * + * + * @type String + */ + + port: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的请求完整路径(含请求),由 pathname 和 query 组装而成 + * + * + * + * @type String + */ + + path: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的路径 + * + * + * + * @type String + */ + + pathname: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的请求字符串(含“?”),等效于“?”+query + * + * + * + * @type String + */ + + search: string + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的请求字符串( 不含“?”) + * + * + * + * @type Value + */ + + query: any + + /** + * class prop + * + * + * @brief 查询和设置当前 UrlObject 对象中的请求锚点(含“\#”) + * + * + * + * @type String + */ + + hash: string + + + + /** + * + * @brief UrlObject 对象构造函数,使用参数构造 + * @param args 指定构造参数的字典对象,支持的字段有:protocol, slashes, username, password, hostname, port, pathname, query, hash + * + * + * + */ + constructor(args: Object); + + /** + * + * @brief UrlObject 对象构造函数,使用 url 字符串构造 + * @param url 指定构造 url 字符串 + * @param parseQueryString 指定是否解析 query + * @param slashesDenoteHost 默认为false, 如果设置为true,则从字符串'//'之后到下一个'/'之前的字符串会被解析为host,例如'//foo/bar', 结果应该是{host: 'foo', pathname: '/bar'}而不是{pathname: '//foo/bar'} + * + * + * + */ + constructor(url?: string/** = ""*/, parseQueryString?: boolean/** = false*/, slashesDenoteHost?: boolean/** = false*/); + + /** + * + * @brief 解析一个 url 字符串 + * @param url 指定需要解析的 url 字符串 + * @param parseQueryString 指定是否解析 query + * @param slashesDenoteHost 默认为false, 如果设置为true,则从字符串'//'之后到下一个'/'之前的字符串会被解析为host,例如'//foo/bar', 结果应该是{host: 'foo', pathname: '/bar'}而不是{pathname: '//foo/bar'} + * + * + * + */ + parse(url: string, parseQueryString?: boolean/** = false*/, slashesDenoteHost?: boolean/** = false*/): void; + + /** + * + * @brief 使用指定的参数构造 UrlObject + * @param args 指定构造参数的字典对象,支持的字段有:protocol, slashes, username, password, hostname, port, pathname, query, hash + * + * + * + */ + format(args: Object): void; + + /** + * + * @brief 重定位 url 路径,自动识别新路径为相对路径还是绝对路径 + * @param url 指定新的路径 + * @return 返回包含重定位数据的对象 + * + * + * + */ + resolve(url: string): Class_UrlObject; + + /** + * + * @brief 标准化路径 + * + * + * + */ + normalize(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/WebSocket.d.ts b/types/fibjs/declare/WebSocket.d.ts new file mode 100644 index 0000000000..08201ff96e --- /dev/null +++ b/types/fibjs/declare/WebSocket.d.ts @@ -0,0 +1,192 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief WebSocket 包协议转换处理器 + * @detail 用以将 Http 协议转换为 WebSocket 包协议消息。创建方式:,```JavaScript,var ws = require('ws');,var http = require('http');,,var serv = new http.Server(8811, ws.upgrade((conn) => {,conn.onmessage = msg => {, conn.send(new Date());,};,}));,,serv.run(r => 0);,,var sock = new ws.Socket('ws://127.0.0.1:8811');,sock.on('open', () => {, setInterval(() => {, sock.send('get date');, }, 1000);,});,,sock.onmessage = evt => {, console.log(evt.data);,},``` + */ +/// +declare class Class_WebSocket extends Class_EventEmitter { + + /** + * class prop + * + * + * @brief 查询当前对象连接的服务器 + * + * @readonly + * @type String + */ + + url: string + + /** + * class prop + * + * + * @brief 查询当前对象连接时的协议 + * + * @readonly + * @type String + */ + + protocol: string + + /** + * class prop + * + * + * @brief 查询当前对象连接的源 + * + * @readonly + * @type String + */ + + origin: string + + /** + * class prop + * + * + * @brief 查询当前对象的连接状态,参见 ws + * + * @readonly + * @type Integer + */ + + readyState: number + + /** + * class prop + * + * + * @brief 查询和绑定连接成功事件,相当于 on("open", func); + * + * + * @type Function + */ + + onopen: Function + + /** + * class prop + * + * + * @brief 查询和绑定接受到对方消息的事件,相当于 on("message", func); + * + * + * @type Function + */ + + onmessage: Function + + /** + * class prop + * + * + * @brief 查询和绑定连接关闭的事件,相当于 on("close", func); + * + * + * @type Function + */ + + onclose: Function + + /** + * class prop + * + * + * @brief 查询和绑定错误发生的事件,相当于 on("error", func); + * + * + * @type Function + */ + + onerror: Function + + + + /** + * + * @brief WebSocket 构造函数 + * @param url 指定连接的服务器 + * @param protocol 指定握手协议,缺省为 "" + * @param origin 指定握手时模拟的源 + * + * + * + */ + constructor(url: string, protocol?: string/** = ""*/, origin?: string/** = ""*/); + + /** + * + * @brief 关闭当前连接,此操作会向对方发送 CLOSE 数据包,并等待对方响应 + * @param code 指定关闭的代码,允许值为 3000-4999 或者 1000,缺省为 1000 + * @param reason 指定关闭的原因,缺省为 "" + * + * + * + */ + close(code?: number/** = 1000*/, reason?: string/** = ""*/): void; + + /** + * + * @brief 向对方发送一段文本 + * @param data 指定发送的文本 + * + * + * + */ + send(data: string): void; + + /** + * + * @brief 向对方发送一段二进制数据 + * @param data 指定发送的二进制数据 + * + * + * + */ + send(data: Class_Buffer): void; + + /** + * + * @brief 维持 fibjs 进程不退出,在对象绑定期间阻止 fibjs 进程退出 + * @return 返回当前对象 + * + * + * + */ + ref(): Class_WebSocket; + + /** + * + * @brief 允许 fibjs 进程退出,在对象绑定期间允许 fibjs 进程退出 + * @return 返回当前对象 + * + * + * + */ + unref(): Class_WebSocket; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/WebSocketMessage.d.ts b/types/fibjs/declare/WebSocketMessage.d.ts new file mode 100644 index 0000000000..989a12c2ff --- /dev/null +++ b/types/fibjs/declare/WebSocketMessage.d.ts @@ -0,0 +1,84 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + + + +/** module Or Internal Object */ +/** + * @brief websocket 消息对象 + * @detail 创建方法:,```JavaScript,var ws = require("ws");,,var msg = new ws.Message();,``` + */ +/// +declare class Class_WebSocketMessage extends Class_Message { + + /** + * class prop + * + * + * @brief 查询和读取 websocket 掩码标记,缺省为 true + * + * + * @type Boolean + */ + + masked: boolean + + /** + * class prop + * + * + * @brief 查询和读取 websocket 压缩状态,缺省为 false + * + * + * @type Boolean + */ + + compress: boolean + + /** + * class prop + * + * + * @brief 查询和设置最大包尺寸,以字节为单位,缺省为 67108864(64M) + * + * + * @type Integer + */ + + maxSize: number + + + + /** + * + * @brief 包处理消息对象构造函数 + * @param type websocket 消息类型,缺省为 websocket.BINARY + * @param masked websocket 消息掩码,缺省为 true + * @param compress 标记消息是否压缩,缺省为 false + * @param maxSize 最大包尺寸,以 MB 为单位,缺省为 67108864(64M) + * + * + * + */ + constructor(type?: number/** = undefined*/, masked?: boolean/** = true*/, compress?: boolean/** = false*/, maxSize?: number/** = 67108864*/); + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/WebView.d.ts b/types/fibjs/declare/WebView.d.ts new file mode 100644 index 0000000000..2bf1258bcf --- /dev/null +++ b/types/fibjs/declare/WebView.d.ts @@ -0,0 +1,172 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 浏览器窗口对象 + * @detail WebView 是一个嵌入浏览器的窗口组件,目前仅支持 windows ie。,,由于 WebView 内的 JavaScript 程序与 fibjs 并不在同一个引擎内,所以如果需要与宿主程序进行通讯,需要通过消息进行。,,WebView 用于通讯的对象是 external,external 支持一个方法 postMessage 和两个事件 onmessage、onclose。,,一个简单的通讯示例代码如下:,```JavaScript,// index.js,var gui = require('gui');,var webview = gui.open('fs:index.html');,,webview.onmessage = msg => console.log(msg);,,webview.onload = evt => webview.postMessage("hello from fibjs");,,webview.wait();,```,,index.html 的内容如下:,```html,,```, 在用户窗口关闭之前,会触发 external.onclose 事件,external.onclose 可以决定是否关闭。如果 external.onclose 返回 false,则此次操作取消,否则将关闭窗口。,,以下的例子,会在用户点关闭后等待 5 秒后再关闭窗口。,```html,,```,上面的代码中,因为 window.close 本身也会触发 onclose 事件,所以需要增加一个开关变量,用于识别是否需要处理此次事件。 + */ +/// +declare class Class_WebView extends Class_EventEmitter { + + /** + * class prop + * + * + * @brief 查询和设置窗口是否显示 + * + * + * @type Boolean + */ + + visible: boolean + + /** + * class prop + * + * + * @brief 查询和绑定加载成功事件,相当于 on("load", func); + * + * + * @type Function + */ + + onload: Function + + /** + * class prop + * + * + * @brief 查询和绑定窗口移动事件,相当于 on("move", func); + * + * 以下示例会在窗口移动时输出窗口的左上角坐标: + * ```JavaScript + * var gui = require('gui'); + * var webview = gui.open('fs:index.html'); + * + * webview.onmove = evt => console.log(evt.left, evt.top); + * ``` + * + * + * + * @type Function + */ + + onmove: Function + + /** + * class prop + * + * + * @brief 查询和绑定窗口尺寸改变事件,相当于 on("size", func); + * + * 以下示例会在窗口改变大小时输出窗口的尺寸: + * ```JavaScript + * var gui = require('gui'); + * var webview = gui.open('fs:index.html'); + * + * webview.onresize = evt => console.log(evt.width, evt.height); + * ``` + * + * + * + * @type Function + */ + + onresize: Function + + /** + * class prop + * + * + * @brief 查询和绑定窗口关闭事件,WebView 关闭后会触发此时间,相当于 on("closed", func); + * + * + * @type Function + */ + + onclosed: Function + + /** + * class prop + * + * + * @brief 查询和绑定接受 webview 内 postMessage 消息事件,相当于 on("message", func); + * + * + * @type Function + */ + + onmessage: Function + + + + /** + * + * @brief 设置 webview 的页面 html + * @param html 设置的 html + * + * + * @async + */ + setHtml(html: string): void; + + /** + * + * @brief 打印当前窗口文档 + * @param mode 打印参数,0: 快速打印; 1: 标准打印; 2: 打印预览。缺省为 1 + * + * + * @async + */ + print(mode?: number/** = 1*/): void; + + /** + * + * @brief 关闭当前窗口 + * + * @async + */ + close(): void; + + /** + * + * @brief 等待当前窗口关闭 + * 宿主程序在创建窗口后,需要进入等待,否则随着宿主程序的退出,窗口将自动关闭。同时 wait 的调用也并不是必须的,你可以在打开窗口后处理其它业务,只需要保证程序不会自行退出即可。 + * + * + * @async + */ + wait(): void; + + /** + * + * @brief 向 webview 内发送消息 + * postMessage 需要在窗口加载完成后发送消息,在此之前发送的消息会丢失。因此建议在 onload 事件触发后再调用此方法。 + * @param msg 要发送的消息 + * + * + * @async + */ + postMessage(msg: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/Worker.d.ts b/types/fibjs/declare/Worker.d.ts new file mode 100644 index 0000000000..9e8fa4f50a --- /dev/null +++ b/types/fibjs/declare/Worker.d.ts @@ -0,0 +1,66 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief 独立线程工作对象 + * @detail + */ +/// +declare class Class_Worker extends Class_EventEmitter { + + /** + * class prop + * + * + * @brief 查询和绑定接受 postMessage 消息事件,相当于 on("message", func); + * + * + * @type Function + */ + + onmessage: Function + + + + /** + * + * @brief Worker 对象构造函数 + * @param path 指定 Worker 入口脚本,只接受绝对路径 + * @param opts 构造选项,暂未支持 + * + * + * + */ + constructor(path: string, opts?: Object/** = v8::Object::New(isolate)*/); + + /** + * + * @brief 向 Master 或 Worker 发送消息, + * @param data 指定发送的消息内容 + * + * + * + */ + postMessage(data: any): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/X509Cert.d.ts b/types/fibjs/declare/X509Cert.d.ts new file mode 100644 index 0000000000..17f4a259b4 --- /dev/null +++ b/types/fibjs/declare/X509Cert.d.ts @@ -0,0 +1,263 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief x509 证书对象 + * @detail X509Cert 对象属于 crypto 模块,创建:,```JavaScript,var k = new crypto.X509Cert();,``` + */ + +declare class Class_X509Cert extends Class__object { + + /** + * class prop + * + * + * @brief 获取证书的版本 + * + * @readonly + * @type Integer + */ + + version: number + + /** + * class prop + * + * + * @brief 获取证书的序列号 + * + * @readonly + * @type String + */ + + serial: string + + /** + * class prop + * + * + * @brief 获取证书颁发者的可分辨名称 + * + * @readonly + * @type String + */ + + issuer: string + + /** + * class prop + * + * + * @brief 获取证书的主题可分辨名称 + * + * @readonly + * @type String + */ + + subject: string + + /** + * class prop + * + * + * @brief 获取证书的生效时间 + * + * @readonly + * @type Date + */ + + notBefore: Date + + /** + * class prop + * + * + * @brief 获取证书的到期时间 + * + * @readonly + * @type Date + */ + + notAfter: Date + + /** + * class prop + * + * + * @brief 获取证书是否是 ca 证书 + * + * @readonly + * @type Boolean + */ + + ca: boolean + + /** + * class prop + * + * + * @brief 获取证书的 pathlen + * + * @readonly + * @type Integer + */ + + pathlen: number + + /** + * class prop + * + * + * @brief 获取证书的使用范围 + * + * 结果为全部或部分以下内容:digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign + * + * + * @readonly + * @type String + */ + + usage: string + + /** + * class prop + * + * + * @brief 获取证书的 Netscape 证书类型 + * + * 结果为全部或部分以下内容:client, server, email, objsign, reserved, sslCA, emailCA, objCA + * + * + * @readonly + * @type String + */ + + type: string + + /** + * class prop + * + * + * @brief 获取证书的公钥 + * + * @readonly + * @type PKey + */ + + publicKey: Class_PKey + + /** + * class prop + * + * + * @brief 获取证书链中得下一个证书 + * + * @readonly + * @type X509Cert + */ + + next: Class_X509Cert + + + + /** + * + * @brief X509Cert 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 加载一个 DER 格式的证书,可多次调用 + * @param derCert DER 格式的证书 + * + * + * + */ + load(derCert: Class_Buffer): void; + + /** + * + * @brief 加载一个 CRT/PEM/TXT 格式的证书,可多次调用 + * + * load 加载 mozilla 的 certdata,txt, 可于 http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt 下载使用 + * @param txtCert PEM 格式的证书 + * + * + * + */ + load(txtCert: string): void; + + /** + * + * @brief 加载一个 CRT/PEM/DER/TXT 格式的证书,可多次调用 + * + * loadFile 加载 mozilla 的 certdata,txt, 可于 http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt 下载使用 + * @param filename 证书文件名 + * + * + * + */ + loadFile(filename: string): void; + + /** + * + * @brief 加载自带的缺省根证书 + * 此证书内容源自:http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt + * + * + */ + loadRootCerts(): void; + + /** + * + * @brief 使用当前证书链验证给定的证书 + * @param cert 给定需要验证的证书 + * @return 如果验证成功则返回 True + * + * + * @async + */ + verify(cert: Class_X509Cert): boolean; + + /** + * + * @brief 导出已经加载的证书 + * @return 以数组方式导出证书链 + * + * + * + */ + dump(): any[]; + + /** + * + * @brief 清空已经加载的证书 + * + * + */ + clear(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/X509Crl.d.ts b/types/fibjs/declare/X509Crl.d.ts new file mode 100644 index 0000000000..44c3f2a4fc --- /dev/null +++ b/types/fibjs/declare/X509Crl.d.ts @@ -0,0 +1,90 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief x509 撤销证书对象 + * @detail X509Crl 对象属于 crypto 模块,创建:,```JavaScript,var k = new crypto.X509Crl();,``` + */ + +declare class Class_X509Crl extends Class__object { + + + + /** + * + * @brief X509Crl 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief 加载一个 DER 格式的撤销证书,可多次调用 + * @param derCrl DER 格式的撤销证书 + * + * + * + */ + load(derCrl: Class_Buffer): void; + + /** + * + * @brief 加载一个 PEM 格式的撤销证书,可多次调用 + * @param pemCrl PEM 格式的撤销证书 + * + * + * + */ + load(pemCrl: string): void; + + /** + * + * @brief 加载一个 PEM/DER 格式的撤销证书,可多次调用 + * @param filename 撤销证书文件名 + * + * + * + */ + loadFile(filename: string): void; + + /** + * + * @brief 导出已经加载的撤销证书 + * @return 以数组方式导出撤销证书链 + * + * + * + */ + dump(): any[]; + + /** + * + * @brief 清空已经加载的撤销证书 + * + * + * + */ + clear(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/X509Req.d.ts b/types/fibjs/declare/X509Req.d.ts new file mode 100644 index 0000000000..5474d3f6d8 --- /dev/null +++ b/types/fibjs/declare/X509Req.d.ts @@ -0,0 +1,155 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + + + +/** module Or Internal Object */ +/** + * @brief x509 证书请求对象 + * @detail X509Req 对象属于 crypto 模块,创建:,```JavaScript,var k = new crypto.X509Req();,``` + */ + +declare class Class_X509Req extends Class__object { + + /** + * class prop + * + * + * @brief 获取证书的主题可分辨名称 + * + * @readonly + * @type String + */ + + subject: string + + /** + * class prop + * + * + * @brief 获取证书的公钥 + * + * @readonly + * @type PKey + */ + + publicKey: Class_PKey + + + + /** + * + * @brief X509Req 构造函数 + * + * + */ + constructor(); + + /** + * + * @brief X509Req 构造函数,根据给定的信息创建一个证书请求 + * + * @param subject 证书的主题可分辨名称 + * @param key 证书的公钥 + * @param hash 证书摘要算法,缺省为 hash.SHA1 + * + * + * + */ + constructor(subject: string, key: Class_PKey, hash?: number/** = undefined*/); + + /** + * + * @brief 加载一个 DER 格式的证书请求 + * @param derReq DER 格式的证书请求 + * + * + * + */ + load(derReq: Class_Buffer): void; + + /** + * + * @brief 加载一个 PEM 格式的证书请求 + * @param pemReq PEM 格式的证书请求 + * + * + * + */ + load(pemReq: string): void; + + /** + * + * @brief 加载一个 PEM/DER 格式的证书请求,可多次调用 + * @param filename 证书请求文件名 + * + * + * + */ + loadFile(filename: string): void; + + /** + * + * @brief 返回当前证书请求的 PEM 格式编码 + * @return 当前证书请求的 PEM 格式编码 + * + * + * + */ + exportPem(): string; + + /** + * + * @brief 返回当前证书请求的 DER 格式编码 + * @return 当前证书请求的 DER 格式编码 + * + * + * + */ + exportDer(): Class_Buffer; + + /** + * + * @brief 签名当前证书请求为正式证书 + * + * opts 接收的字段如下: + * ```JavaScript + * { + * ca: false, // 证书为 ca,缺省为 false + * pathlen: -1, // 证书深度,缺省为 -1 + * notBefore: "", // 证书生效时间,缺省为当前时间 + * notAfter: "", // 证书失效时间,缺省为 notBefore 后一年 + * usage: "", // 证书使用范围,接收:digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign + * type: "" // 证书 Netscape 证书类型,接收:client, server, email, objsign, reserved, sslCA, emailCA, objCA + * } + * ``` + * @param issuer 签名机构的可分辨名称 + * @param key 签名机构的私钥 + * @param opts 其他可选参数 + * @return 返回签名后的正式证书 + * + * + * @async + */ + sign(issuer: string, key: Class_PKey, opts?: Object/** = v8::Object::New(isolate)*/): Class_X509Cert; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlAttr.d.ts b/types/fibjs/declare/XmlAttr.d.ts new file mode 100644 index 0000000000..b95e3902c9 --- /dev/null +++ b/types/fibjs/declare/XmlAttr.d.ts @@ -0,0 +1,124 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlAttr 对象表示 XmlElement 对象的属性 + * @detail + */ + +declare class Class_XmlAttr extends Class__object { + + /** + * class prop + * + * + * @brief 查询元素的本地名称。如果选定的节点无命名空间,则该属性等同于 nodeName + * + * + * @readonly + * @type String + */ + + localName: string + + /** + * class prop + * + * + * @brief 属性的值 + * + * + * + * @type String + */ + + value: string + + /** + * class prop + * + * + * @brief 属性的名称 + * + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 查询元素的命名空间的 URI。如果选定的节点无命名空间,则该属性返回 NULL + * + * + * @readonly + * @type String + */ + + namespaceURI: string + + /** + * class prop + * + * + * @brief 查询和设置元素的命名空间前缀。如果选定的节点无命名空间,则该属性返回 NULL + * + * + * + * @type String + */ + + prefix: string + + /** + * class prop + * + * + * @brief 属性的名称,为兼容的目的 + * + * + * @readonly + * @type String + */ + + nodeName: string + + /** + * class prop + * + * + * @brief 属性的值,为兼容的目的 + * + * + * + * @type String + */ + + nodeValue: string + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlCDATASection.d.ts b/types/fibjs/declare/XmlCDATASection.d.ts new file mode 100644 index 0000000000..31fd64ecc9 --- /dev/null +++ b/types/fibjs/declare/XmlCDATASection.d.ts @@ -0,0 +1,33 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlCDATASection 对象表示文档中的 CDATA 区段 + * @detail XmlCDATASection 接口是 XmlText 接口的子接口,没有定义任何自己的属性和方法。通过从 XmlNode 接口继承 nodeValue 属性,或通过从 XmlCharacterData 接口继承 data 属性,可以访问 CDATA Section 的文本内容。,,虽然通常可以把 XmlCDATASection 节点作为 XmlText 节点处理,但要注意 XmlNode 的 normalize 方法不并入相邻的 CDATA 部分。,,使用 XmlDocument 的 createXmlCDATASection 方法来创建一个 XmlCDATASection 。,,CDATA 区段包含了不会被解析器解析的文本。CDATA 区段中的标签不会被视为标记,同时实体也不会被展开。主要的目的是为了包含诸如 XML 片段之类的材料,而无需转义所有的分隔符。,,在一个 CDATA 中唯一被识别的分隔符是 "]]>",它可标示 CDATA 区段的结束。CDATA 区段不能进行嵌套。 + */ +/// +declare class Class_XmlCDATASection extends Class_XmlText { + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlCharacterData.d.ts b/types/fibjs/declare/XmlCharacterData.d.ts new file mode 100644 index 0000000000..eb83981983 --- /dev/null +++ b/types/fibjs/declare/XmlCharacterData.d.ts @@ -0,0 +1,115 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlCharacterData 接口提供了 XmlText 和 XmlComment 节点的常用功能 + * @detail XmlCharacterData 是 XmlText 和 XmlComment 节点的超接口。文档从不包含 XmlCharacterData 节点,它们只包含 XmlText 节点和 XmlComment 节点。但由于这两种节点具有相似的功能,因此此处定义了这些函数,以便 XmlText 和 XmlComment 可以继承它。 + */ +/// +declare class Class_XmlCharacterData extends Class_XmlNode { + + /** + * class prop + * + * + * @brief 该节点包含的文本 + * + * + * + * @type String + */ + + data: string + + /** + * class prop + * + * + * @brief 该节点包含的字符数 + * + * + * @readonly + * @type Integer + */ + + length: number + + + + /** + * + * @brief 从节点中提取子串 + * @param offset 要返回的第一个字符的位置 + * @param count 要返回的子串中的字符数 + * @return 返回提取的字符串 + * + * + * + */ + substringData(offset: number, count: number): string; + + /** + * + * @brief 把字符串附加到节点上 + * @param arg 要附加到节点的字符串 + * + * + * + */ + appendData(arg: string): void; + + /** + * + * @brief 把字符串插入节点 + * @param offset 要把字符串插入节点的字符位置 + * @param arg 要插入的字符串 + * + * + * + */ + insertData(offset: number, arg: string): void; + + /** + * + * @brief 从节点删除文本 + * @param offset 要删除的第一个字符的位置 + * @param count 要删除的字符的数量 + * + * + * + */ + deleteData(offset: number, count: number): void; + + /** + * + * @brief 用指定的字符串替换节点的字符 + * @param offset 节点要替换的字符位置 + * @param count 要替换的字符的数量 + * @param arg 要插入的字符串 + * + * + * + */ + replaceData(offset: number, count: number, arg: string): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlComment.d.ts b/types/fibjs/declare/XmlComment.d.ts new file mode 100644 index 0000000000..7ba55a9740 --- /dev/null +++ b/types/fibjs/declare/XmlComment.d.ts @@ -0,0 +1,33 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlComment 对象表示文档中注释节点的内容 + * @detail XmlComment 节点表示 XML 文档中的注释。,使用由 XmlCharacterData 接口继承的 data 属性,或使用由 XmlNode 接口继承的 nodeValue 属性,可以访问注释的内容。(即 之间的文本)。使用由 XmlCharacterData 接口继承的各种方法可以操作注释的内容。,,使用 XmlDocument.createComment() 来创建一个注释对象。 + */ +/// +declare class Class_XmlComment extends Class_XmlCharacterData { + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlDocument.d.ts b/types/fibjs/declare/XmlDocument.d.ts new file mode 100644 index 0000000000..9e0b770e81 --- /dev/null +++ b/types/fibjs/declare/XmlDocument.d.ts @@ -0,0 +1,290 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlDocument 对象代表整个 XML 文档 + * @detail XmlDocument 对象是一棵文档树的根,可为我们提供对文档数据的最初(或最顶层)的访问入口。,用于元素节点、文本节点、注释、处理指令等均无法存在于 XmlDocument 之外, XmlDocument 对象同样提供了创建这些对象的方法。 XmlNode 对象提供了一个 ownerDocument 属性,此属性可把它们与在其中创建它们的 XmlDocument 关联起来。 + */ +/// +declare class Class_XmlDocument extends Class_XmlNode { + + /** + * class prop + * + * + * @brief 返回用于文档的编码(在解析时) + * + * + * @readonly + * @type String + */ + + inputEncoding: string + + /** + * class prop + * + * + * @brief 设置或返回文档是否为 standalone + * + * + * + * @type Boolean + */ + + xmlStandalone: boolean + + /** + * class prop + * + * + * @brief 设置或返回文档的 XML 版本 + * + * + * + * @type String + */ + + xmlVersion: string + + /** + * class prop + * + * + * @brief 返回与文档相关的文档类型声明(Document Type Declaration) + * + * 对于没有 DTD 的 XML 文档,则返回 null。此属性可提供对 XmlDocumentType 对象( XmlDocument 的一个子节点)的直接访问。 + * + * + * @readonly + * @type XmlDocumentType + */ + + doctype: Class_XmlDocumentType + + /** + * class prop + * + * + * @brief 返回文档的根节点 + * + * + * @readonly + * @type XmlElement + */ + + documentElement: Class_XmlElement + + /** + * class prop + * + * + * @brief 返回 HTML 文档的 head 节点,仅在 html 模式有效 + * + * + * @readonly + * @type XmlElement + */ + + head: Class_XmlElement + + /** + * class prop + * + * + * @brief 返回 HTML 文档的 title 节点的内容,仅在 html 模式有效 + * + * + * @readonly + * @type String + */ + + title: string + + /** + * class prop + * + * + * @brief 返回 HTML 文档的 body 节点,仅在 html 模式有效 + * + * + * @readonly + * @type XmlElement + */ + + body: Class_XmlElement + + + + /** + * + * @brief 构造一个 XmlDocument 对象 + * @param type 指定文档对象的类型,缺省为 "text/xml",若需要处理 html 则需要指定 "text/html" + * + * + * + */ + constructor(type?: string/** = "text/xml"*/); + + /** + * + * @brief 通过解析一个 XML/HTML 字符串来组成该文档,不支持多语种 + * @param source 要解析的 XML/HTML 文本,取决于文档创建时的类型 + * + * + * + */ + load(source: string): void; + + /** + * + * @brief 通过解析一个二进制 XML/HTML 字符串来组成该文档,并根据语种自动转换 + * @param source 要解析的 XML/HTML 文本,取决于文档创建时的类型 + * + * + * + */ + load(source: Class_Buffer): void; + + /** + * + * @brief 返回带有指定名称的所有元素的一个节点列表 + * + * 该方法将返回一个 XmlNodeList 对象(可以作为只读数组处理),该对象存放文档中具有指定标签名的所有 XmlElement 节点,它们存放的顺序就是在源文档中出现的顺序。 XmlNodeList 对象是“活”的,即如果在文档中添加或删除了指定标签名的元素,它的内容会自动进行必要的更新。 + * @param tagName 需检索的标签名。值 "*" 匹配所有的标签 + * @return 文档树中具有指定标记的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByTagName(tagName: string): Class_XmlNodeList; + + /** + * + * @brief 返回带有指定命名空间和名称的所有元素的一个节点列表 + * + * 该方法与 getElementsByTagName() 方法相似,只是它根据命名空间和名称来检索元素。 + * @param namespaceURI 指定检索的命名空间 URI。值 "*" 可匹配所有的标签 + * @param localName 需检索的标签名。值 "*" 匹配所有的标签 + * @return 文档树中具有指定标记的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByTagNameNS(namespaceURI: string, localName: string): Class_XmlNodeList; + + /** + * + * @brief 返回拥有指定 id 属性的元素 + * + * 该方法将遍历文档的子孙节点,返回一个 XmlElement 节点对象,表示第一个具有指定 id 属性的文档元素。。 + * @param id 需检索的 id + * @return 节点树中具有指定 id 属性的 XmlElement 节点 + * + * + * + */ + getElementById(id: string): Class_XmlElement; + + /** + * + * @brief 返回带有指定 class 名称的所有元素的一个节点列表 + * + * 该方法将返回一个 XmlNodeList 对象(可以作为只读数组处理),该对象存放文档中具有指定 class 名的所有 XmlElement 节点,它们存放的顺序就是在源文档中出现的顺序。 XmlNodeList 对象是“活”的,即如果在文档中添加或删除了指定标签名的元素,它的内容会自动进行必要的更新。 + * @param className 需检索的 class 名称 + * @return 文档树中具有指定 class 名的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByClassName(className: string): Class_XmlNodeList; + + /** + * + * @brief 创建元素节点 + * @param tagName 指定元素节点规定名称 + * @return 返回新创建的 XmlElement 节点,具有指定的标签名 + * + * + * + */ + createElement(tagName: string): Class_XmlElement; + + /** + * + * @brief 创建带有指定命名空间的元素节点 + * @param namespaceURI 指定元素节点命名空间 URI + * @param qualifiedName 指定元素节点规定名称 + * @return 返回新创建的 XmlElement 节点,具有指定的标签名 + * + * + * + */ + createElementNS(namespaceURI: string, qualifiedName: string): Class_XmlElement; + + /** + * + * @brief 创建文本节点 + * @param data 指定此节点的文本 + * @return 返回新创建的 XmlText 节点,表示指定的 data 字符串 + * + * + * + */ + createTextNode(data: string): Class_XmlText; + + /** + * + * @brief 创建注释节点 + * @param data 指定此节点的注释文本 + * @return 返回新创建的 XmlComment 节点,注释文本为指定的 data + * + * + * + */ + createComment(data: string): Class_XmlComment; + + /** + * + * @brief 创建 XmlCDATASection 节点 + * @param data 指定此节点规定 CDATA 数据 + * @return 返回新创建的 XmlCDATASection 节点,内容为指定的 data + * + * + * + */ + createCDATASection(data: string): Class_XmlCDATASection; + + /** + * + * @brief 创建 XmlProcessingInstruction 节点 + * @param target 指定处理指令的目标 + * @param data 指定处理指令的内容文本 + * @return 新创建的 ProcessingInstruction 节点 + * + * + * + */ + createProcessingInstruction(target: string, data: string): Class_XmlProcessingInstruction; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlDocumentType.d.ts b/types/fibjs/declare/XmlDocumentType.d.ts new file mode 100644 index 0000000000..129b1c7f5c --- /dev/null +++ b/types/fibjs/declare/XmlDocumentType.d.ts @@ -0,0 +1,72 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlDocumentType 对象用于访问 XML 所定义的实体 + * @detail + */ +/// +declare class Class_XmlDocumentType extends Class_XmlNode { + + /** + * class prop + * + * + * @brief 返回 DTD 的名称 + * + * + * @readonly + * @type String + */ + + name: string + + /** + * class prop + * + * + * @brief 可返回外部 DTD 的公共识别符 + * + * + * @readonly + * @type String + */ + + publicId: string + + /** + * class prop + * + * + * @brief 可返回外部 DTD 的系统识别符 + * + * + * @readonly + * @type String + */ + + systemId: string + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlElement.d.ts b/types/fibjs/declare/XmlElement.d.ts new file mode 100644 index 0000000000..8b55b1a625 --- /dev/null +++ b/types/fibjs/declare/XmlElement.d.ts @@ -0,0 +1,301 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlElement 对象表示 XML 文档中的元素 + * @detail + */ +/// +declare class Class_XmlElement extends Class_XmlNode { + + /** + * class prop + * + * + * @brief 查询元素的命名空间的 URI。如果选定的节点无命名空间,则该属性返回 NULL + * + * + * @readonly + * @type String + */ + + namespaceURI: string + + /** + * class prop + * + * + * @brief 查询和设置元素的命名空间前缀。如果选定的节点无命名空间,则该属性返回 NULL + * + * + * + * @type String + */ + + prefix: string + + /** + * class prop + * + * + * @brief 查询元素的本地名称。如果选定的节点无命名空间,则该属性等同于 nodeName + * + * + * @readonly + * @type String + */ + + localName: string + + /** + * class prop + * + * + * @brief 返回元素的标签名 + * + * + * @readonly + * @type String + */ + + tagName: string + + /** + * class prop + * + * + * ! 查询和设置元素的 id 属性 + * + * + * + * @type String + */ + + id: string + + /** + * class prop + * + * + * ! 查询和设置选定元素的文本。查询时,返回元素节点内所有文本节点的值;设置时,删除所有子节点,并用单个文本节点来替换它们。 + * + * + * + * @type String + */ + + textContent: string + + /** + * class prop + * + * + * ! 查询和设置选定元素的 HTML 文本,仅在 html 模式有效。查询时,返回元素节点内所有子节点的 HTML 编码;设置时,删除所有子节点,并用指定的 HTML 解码后替换它们。 + * + * + * + * @type String + */ + + innerHTML: string + + /** + * class prop + * + * + * ! 查询和设置元素的 class 属性,仅在 html 模式有效 + * + * + * + * @type String + */ + + className: string + + /** + * class prop + * + * + * @brief 返回包含被选节点属性的 NamedNodeMap。如果被选节点不是元素,则该属性返回 NULL。 + * + * + * @readonly + * @type XmlNamedNodeMap + */ + + attributes: Class_XmlNamedNodeMap + + + + /** + * + * @brief 通过名称查询属性的值 + * @param name 指定查询的属性名 + * @return 返回属性的值 + * + * + * + */ + getAttribute(name: string): string; + + /** + * + * @brief 通过命名空间 URI 和名称来获取属性值 + * @param namespaceURI 指定查询的命名空间 URI + * @param localName 指定查询的属性名 + * @return 返回属性的值 + * + * + * + */ + getAttributeNS(namespaceURI: string, localName: string): string; + + /** + * + * @brief 创建或改变某个新属性 + * + * 该方法把指定的属性设置为指定的值。如果不存在具有指定名称的属性,该方法将创建一个新属性 + * @param name 指定要设置的属性名 + * @param value 指定要设置的属性值 + * + * + * + */ + setAttribute(name: string, value: string): void; + + /** + * + * @brief 创建或改变具有命名空间的属性 + * + * 该方法与 setAttribute 方法类似,只是要创建或设置的属性由命名空间 URI 和限定名(由名字空间前缀、冒号和名字空间中的本地名构成)共同指定。除了可以改变一个属性的值以外,使用该方法还可以改变属性的名字空间前缀 + * @param namespaceURI 指定要设置的命名空间 URI + * @param qualifiedName 指定要设置的属性名 + * @param value 指定要设置的属性值 + * + * + * + */ + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + + /** + * + * @brief 通过名称删除指定的属性 + * @param name 指定删除的属性名 + * + * + * + */ + removeAttribute(name: string): void; + + /** + * + * @brief 通过命名空间和名称删除指定的属性 + * @param namespaceURI 指定要删除的命名空间 URI + * @param localName 指定删除的属性名 + * + * + * + */ + removeAttributeNS(namespaceURI: string, localName: string): void; + + /** + * + * @brief 查询当前节点是否拥有指定名称的属性 + * @param name 指定查询的属性名称 + * @return 如果当前元素节点拥有指定属性,则返回 true,否则返回 false + * + * + * + */ + hasAttribute(name: string): boolean; + + /** + * + * @brief 查询当前节点是否拥有指定命名空间和名称的属性 + * @param namespaceURI 指定要查询的命名空间 URI + * @param localName 指定查询的属性名称 + * @return 如果当前元素节点拥有指定属性,则返回 true,否则返回 false + * + * + * + */ + hasAttributeNS(namespaceURI: string, localName: string): boolean; + + /** + * + * @brief 返回拥有指定名称的所有元素的 XmlNodeList + * + * 该方法将遍历指定元素的子孙节点,返回一个 XmlElement 节点的 XmlNodeList 对象,表示所有具有指定标签名的文档元素。元素在返回的数组中的顺序就是它们出现在文档源代码中的顺序。 + * + * XmlDocument 接口也定义了 getElementsByTagName 方法,它与该方法相似,但遍历整个文档,而不是遍历某个元素的子孙节点。 + * @param tagName 需检索的标签名。值 "*" 匹配所有的标签 + * @return 节点树中具有指定标记的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByTagName(tagName: string): Class_XmlNodeList; + + /** + * + * @brief 返回拥有指定命名空间和名称的所有元素的 XmlNodeList + * + * 该方法与 getElementsByTagName 方法相似,只是想获取的元素的标记名被指定为命名空间 URI 和在命名空间中定义的本地名的组合。 + * @param namespaceURI 指定要查询的命名空间 URI + * @param localName 需检索的标签名。值 "*" 匹配所有的标签 + * @return 节点树中具有指定标记的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByTagNameNS(namespaceURI: string, localName: string): Class_XmlNodeList; + + /** + * + * @brief 返回拥有指定 id 属性的元素 + * + * 该方法将遍历指定元素的子孙节点,返回一个 XmlElement 节点对象,表示第一个具有指定 id 属性的文档元素。。 + * + * XmlDocument 接口也定义了 getElementsByTagName 方法,它与该方法相似,但遍历整个文档,而不是遍历某个元素的子孙节点。 + * @param id 需检索的 id + * @return 节点树中具有指定 id 属性的 XmlElement 节点 + * + * + * + */ + getElementById(id: string): Class_XmlElement; + + /** + * + * @brief 返回带有指定 class 名称的所有元素的一个节点列表 + * + * 该方法将返回一个 XmlNodeList 对象(可以作为只读数组处理),该对象存放文档中具有指定 class 名的所有 XmlElement 节点,它们存放的顺序就是在源文档中出现的顺序。 XmlNodeList 对象是“活”的,即如果在文档中添加或删除了指定标签名的元素,它的内容会自动进行必要的更新。 + * @param className 需检索的 class 名称 + * @return 文档树中具有指定 class 名的 XmlElement 节点的 XmlNodeList 集合。返回的元素节点的顺序就是它们在源文档中出现的顺序。 + * + * + * + */ + getElementsByClassName(className: string): Class_XmlNodeList; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlNamedNodeMap.d.ts b/types/fibjs/declare/XmlNamedNodeMap.d.ts new file mode 100644 index 0000000000..ea852a624c --- /dev/null +++ b/types/fibjs/declare/XmlNamedNodeMap.d.ts @@ -0,0 +1,68 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlNamedNodeMap 对象表示一个无顺序的属性列表 + * @detail + */ + +declare class Class_XmlNamedNodeMap extends Class__object { + + /** + * class prop + * + * + * @brief 返回属性列表中的属性数目 + * + * + * @readonly + * @type Integer + */ + + length: number + + + + /** + * + * @brief 返回属性列表中处于指定的索引号的属性 + * @param index 指定要查询的索引 + * @return 指定索引号的属性 + * + * + * + */ + item(index: number): Class_XmlAttr; + + /** + * + * @brief 查询指定名称的属性 + * @param name 指定要查询的名称 + * @return 返回查询出的属性 + * + * + * + */ + getNamedItem(name: string): Class_XmlAttr; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlNode.d.ts b/types/fibjs/declare/XmlNode.d.ts new file mode 100644 index 0000000000..efab8bd60e --- /dev/null +++ b/types/fibjs/declare/XmlNode.d.ts @@ -0,0 +1,315 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlNode 对象是整个 DOM 的基础数据类型 + * @detail + */ + +declare class Class_XmlNode extends Class__object { + + /** + * class prop + * + * + * @brief 返回节点的节点类型 + * + * 不同对象的 nodeType 会返回不同的值: + * - XmlElement: ELEMENT_NODE(1) + * - XmlAttr: ATTRIBUTE_NODE(2) + * - XmlText: TEXT_NODE(3) + * - XmlCDATASection: CDATA_SECTION_NODE(4) + * - XmlProcessingInstruction: PROCESSING_INSTRUCTION_NODE(7) + * - XmlComment: COMMENT_NODE(8) + * - XmlDocument: DOCUMENT_NODE(9) + * - XmlDocumentType: DOCUMENT_TYPE_NODE(10) + * + * + * @readonly + * @type Integer + */ + + nodeType: number + + /** + * class prop + * + * + * @brief 返回节点的名称,根据其类型 + * + * 不同对象的 nodeName 会返回不同的值: + * - XmlElement: element name + * - XmlAttr: 属性名称 + * - XmlText: \#text + * - XmlCDATASection: \#cdata-section + * - XmlProcessingInstruction: 返回指定目标 target + * - XmlComment: \#comment + * - XmlDocument: \#document + * - XmlDocumentType: doctype 名称 + * + * + * @readonly + * @type String + */ + + nodeName: string + + /** + * class prop + * + * + * @brief 返回节点的名称,根据其类型 + * + * 不同对象的 nodeName 会返回不同的值: + * - XmlElement: null + * - XmlAttr: 属性的值 + * - XmlText: 节点的内容 + * - XmlCDATASection: 节点的内容 + * - XmlProcessingInstruction: 返回指定内容 data + * - XmlComment: 注释文本 + * - XmlDocument: null + * - XmlDocumentType: null + * + * + * + * @type String + */ + + nodeValue: string + + /** + * class prop + * + * + * @brief 返回节点的根元素(XmlDocument 对象) + * + * + * @readonly + * @type XmlDocument + */ + + ownerDocument: Class_XmlDocument + + /** + * class prop + * + * + * @brief 可返回某节点的父节点 + * + * + * @readonly + * @type XmlNode + */ + + parentNode: Class_XmlNode + + /** + * class prop + * + * + * @brief 返回指定节点的子节点的节点列表 + * + * + * @readonly + * @type XmlNodeList + */ + + childNodes: Class_XmlNodeList + + /** + * class prop + * + * + * @brief 返回节点的首个子节点 + * + * + * @readonly + * @type XmlNode + */ + + firstChild: Class_XmlNode + + /** + * class prop + * + * + * @brief 返回节点的最后一个子节点 + * + * + * @readonly + * @type XmlNode + */ + + lastChild: Class_XmlNode + + /** + * class prop + * + * + * @brief 返回某节点之前紧跟的节点(处于同一树层级),如果没有此节点,那么该属性返回 null + * + * + * @readonly + * @type XmlNode + */ + + previousSibling: Class_XmlNode + + /** + * class prop + * + * + * @brief 返回某个元素之后紧跟的节点(处于同一树层级中),如果无此节点,则属性返回 null + * + * + * @readonly + * @type XmlNode + */ + + nextSibling: Class_XmlNode + + + + /** + * + * @brief 查询是否存在子节点 + * @return 存在任何子节点时返回 true,否则返回 false + * + * + * + */ + hasChildNodes(): boolean; + + /** + * + * @brief 合并相邻的 Text 节点并删除空的 Text 节点 + * + * 这个方法将遍历当前节点的所有子孙节点,通过删除空的 Text 节点,已经合并所有相邻的 Text 节点来规范化文档。该方法在进行节点的插入或删除操作后,对于简化文档树的结构很有用。 + * + * + * + */ + normalize(): void; + + /** + * + * @brief 创建指定的节点的精确拷贝 + * + * 该方法将复制并返回调用它的节点的副本。如果传递给它的参数是 true,它还将递归复制当前节点的所有子孙节点。 否则,它只复制当前节点。返回的节点不属于文档树,它的 parentNode 属性为 null。当复制的是 Element 节点时,它的所有属性都将被复制。 + * @param deep 是否深度拷贝,为 true 时,被克隆的节点会克隆原节点的所有子节点 + * @return 返回所复制的节点 + * + * + * + */ + cloneNode(deep?: boolean/** = true*/): Class_XmlNode; + + /** + * + * @brief 返回在当前节点上匹配指定的命名空间 URI 的前缀 + * @param namespaceURI 指定匹配的命名空间 URI + * @return 返回匹配的前缀,未匹配到返回 null + * + * + * + */ + lookupPrefix(namespaceURI: string): string; + + /** + * + * @brief 返回在当前节点上匹配指定的前缀的命名空间 URI + * @param prefix 指定匹配的前缀 + * @return 返回匹配的命名空间 URI,未匹配到返回 null + * + * + * + */ + lookupNamespaceURI(prefix: string): string; + + /** + * + * @brief 在已有的子节点前插入一个新的子节点 + * + * 如果文档树中已经存在了 newChild,它将从文档树中删除,然后重新插入它的新位置。来自一个文档的节点(或由一个文档创建的节点)不能插入另一个文档。也就是说,newChild 的 ownerDocument 属性必须与当前节点的 ownerDocument 属性相同。 + * @param newChild 插入新的节点 + * @param refChild 在此节点前插入新节点 + * @return 返回新的子节点 + * + * + * + */ + insertBefore(newChild: Class_XmlNode, refChild: Class_XmlNode): Class_XmlNode; + + /** + * + * @brief 在已有的子节点后插入一个新的子节点 + * + * 如果文档树中已经存在了 newChild,它将从文档树中删除,然后重新插入它的新位置。来自一个文档的节点(或由一个文档创建的节点)不能插入另一个文档。也就是说,newChild 的 ownerDocument 属性必须与当前节点的 ownerDocument 属性相同。 + * @param newChild 插入新的节点 + * @param refChild 在此节点后插入新节点 + * @return 返回新的子节点 + * + * + * + */ + insertAfter(newChild: Class_XmlNode, refChild: Class_XmlNode): Class_XmlNode; + + /** + * + * @brief 向节点的子节点列表的末尾添加新的子节点 + * + * 如果文档树中已经存在了 newChild,它将从文档树中删除,然后重新插入它的新位置。来自一个文档的节点(或由一个文档创建的节点)不能插入另一个文档。也就是说,newChild 的 ownerDocument 属性必须与当前节点的 ownerDocument 属性相同。 + * @param newChild 指定添加的节点 + * @return 返回这个新的子节点 + * + * + * + */ + appendChild(newChild: Class_XmlNode): Class_XmlNode; + + /** + * + * @brief 将某个子节点替换为另一个 + * + * 如果文档树中已经存在了 newChild,它将从文档树中删除,然后重新插入它的新位置。来自一个文档的节点(或由一个文档创建的节点)不能插入另一个文档。也就是说,newChild 的 ownerDocument 属性必须与当前节点的 ownerDocument 属性相同。 + * @param newChild 指定新的节点 + * @param oldChild 指定被替换的节点 + * @return 如替换成功,此方法可返回被替换的节点,如替换失败,则返回 null + * + * + * + */ + replaceChild(newChild: Class_XmlNode, oldChild: Class_XmlNode): Class_XmlNode; + + /** + * + * @brief 从子节点列表中删除某个节点 + * @param oldChild 指定被删除的节点 + * @return 如删除成功,此方法可返回被删除的节点,如失败,则返回 null + * + * + * + */ + removeChild(oldChild: Class_XmlNode): Class_XmlNode; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlNodeList.d.ts b/types/fibjs/declare/XmlNodeList.d.ts new file mode 100644 index 0000000000..df0abeb83b --- /dev/null +++ b/types/fibjs/declare/XmlNodeList.d.ts @@ -0,0 +1,57 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlNodeList 对象代表一个有顺序的节点列表 + * @detail + */ + +declare class Class_XmlNodeList extends Class__object { + + /** + * class prop + * + * + * @brief 返回节点列表中的节点数目 + * + * + * @readonly + * @type Integer + */ + + length: number + + + + /** + * + * @brief 返回节点列表中处于指定的索引号的节点 + * @param index 指定要查询的索引 + * @return 指定索引号的节点 + * + * + * + */ + item(index: number): Class_XmlNode; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlProcessingInstruction.d.ts b/types/fibjs/declare/XmlProcessingInstruction.d.ts new file mode 100644 index 0000000000..b9d903d977 --- /dev/null +++ b/types/fibjs/declare/XmlProcessingInstruction.d.ts @@ -0,0 +1,59 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlProcessingInstruction 对象表示 xml 处理指令 + * @detail + */ +/// +declare class Class_XmlProcessingInstruction extends Class_XmlNode { + + /** + * class prop + * + * + * @brief 返回此处理指令的目标 + * + * + * @readonly + * @type String + */ + + target: string + + /** + * class prop + * + * + * @brief 设置或返回此处理指令的内容 + * + * + * + * @type String + */ + + data: string + + + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/XmlText.d.ts b/types/fibjs/declare/XmlText.d.ts new file mode 100644 index 0000000000..b950de3f1d --- /dev/null +++ b/types/fibjs/declare/XmlText.d.ts @@ -0,0 +1,48 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief XmlText 对象表示元素或属性的文本内容 + * @detail XmlText 节点表示 XML 文档中的一系列纯文本。因为纯文本出现在 XML 的元素和属性中,所以 XmlText 节点通常作为 XmlElement 节点和 XmlAttr 节点的子节点出现。,,XmlText 节点继承了 XmlCharacterData 接口,通过从 XmlCharacterData 接口继承的 data 属性或从 XmlNode 接口继承的 nadevalue 属性,可以访问 XmlText 节点的文本内容。,,用从 XmlCharacterData 继承的方法或 XmlText 接口自身定义的 splitText() 方法可以操作 XmlText 节点。使用 XmlDocument 的 createTextNode 来创建一个新的 XmlText 节点。,,XmlText 节点没有子节点。,,关于从文档的子树中删除空 XmlText 节点与合并相邻的 XmlText 节点的方法,请参阅 XmlNode.normalize 方法。 + */ +/// +declare class Class_XmlText extends Class_XmlCharacterData { + + + + /** + * + * @brief 按照指定的 offset 把文本节点分割为两个节点 + * + * 该方法将在指定的 offset 处把 XmlText 节点分割成两个节点。原始的 XmlText 节点将被修改,使它包含 offset 指定的位置之前的文本内容(但不包括文本内容)。新的 XmlText 节点将被创建,用于存放从 offset 位置(包括该位置上的字符)到原字符结尾的所有字符。新的 XmlText 节点是该方法的返回值。此外,如果原始的 XmlText 节点具有 parentNode,新的 XmlText 节点将插入这个父节点,紧邻在原始节点之后。 + * + * XmlCDATASection 接口继承了 XmlText 接口, XmlCDATASection 节点也可以使用该方法 ,只是新创建的节点是 XmlCDATASection 节点,而不是 XmlText 节点。 + * @param offset 规定在何处分割文本节点。开始值以 0 开始 + * @return 从当前节点分割出的 Text 节点 + * + * + * + */ + splitText(offset: number): Class_XmlText; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/ZipFile.d.ts b/types/fibjs/declare/ZipFile.d.ts new file mode 100644 index 0000000000..69cff23908 --- /dev/null +++ b/types/fibjs/declare/ZipFile.d.ts @@ -0,0 +1,168 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + +/** module Or Internal Object */ +/** + * @brief zip 文件访问对象 + * @detail + */ + +declare class Class_ZipFile extends Class__object { + + + + /** + * + * @brief 获取文件名列表 + * @return 返回包含文件名的列表对象 + * + * + * @async + */ + namelist(): any[]; + + /** + * + * @brief 获取文件信息列表 + * 文件信息包含字段有:filename, date, compress_type, compress_size, file_size, password, data + * @return 返回包含文件信息的列表对象 + * + * + * @async + */ + infolist(): any[]; + + /** + * + * @brief 获取文件信息 + * 文件信息包含字段有:filename, date, compress_type, compress_size, file_size, password, data + * @param member 指定要获取信息的文件名 + * @return 返回文件信息对象 + * + * + * @async + */ + getinfo(member: string): any; + + /** + * + * @brief 返回从压缩文件读取的数据 + * @param member 指定要读取的文件名 + * @param password 解压密码, 默认没有密码 + * @return 返回文件的所有数据 + * + * + * @async + */ + read(member: string, password?: string/** = ""*/): Class_Buffer; + + /** + * + * @brief 解压所有文件 + * @param password 解压密码, 默认没有密码 + * @return 包含所有文件数据及信息的列表 + * + * + * @async + */ + readAll(password?: string/** = ""*/): any[]; + + /** + * + * @brief 解压指定文件 + * @param member 指定要解压的文件名 + * @param path 指定要解压到的路径 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + extract(member: string, path: string, password?: string/** = ""*/): void; + + /** + * + * @brief 解压指定文件到流 + * @param member 指定要解压的文件名 + * @param strm 指定要解压到的流 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + extract(member: string, strm: Class_SeekableStream, password?: string/** = ""*/): void; + + /** + * + * @brief 解压所有文件到指定路径 + * @param path 指定要解压到的路径 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + extractAll(path: string, password?: string/** = ""*/): void; + + /** + * + * @brief 写入指定文件到压缩文件 + * @param filename 指定要写入的文件 + * @param inZipName 压缩在zip文件内的文件名 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + write(filename: string, inZipName: string, password?: string/** = ""*/): void; + + /** + * + * @brief 写入指定文件到压缩文件 + * @param data 指定要写入的文件数据 + * @param inZipName 压缩在zip文件内的文件名 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + write(data: Class_Buffer, inZipName: string, password?: string/** = ""*/): void; + + /** + * + * @brief 写入指定文件到压缩文件 + * @param strm 指定要写入文件数据流 + * @param inZipName 压缩在zip文件内的文件名 + * @param password 解压密码, 默认没有密码 + * + * + * @async + */ + write(strm: Class_SeekableStream, inZipName: string, password?: string/** = ""*/): void; + + /** + * + * @brief 关闭打开的zip文件 + * + * @async + */ + close(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/ZmqSocket.d.ts b/types/fibjs/declare/ZmqSocket.d.ts new file mode 100644 index 0000000000..ffe2165928 --- /dev/null +++ b/types/fibjs/declare/ZmqSocket.d.ts @@ -0,0 +1,105 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ +/// + + + + + + +/** module Or Internal Object */ +/** + * @brief ZeroMQ 套接口对象 + * @detail + */ + +declare class Class_ZmqSocket extends Class__object { + + /** + * class prop + * + * + * @brief 查询当前 socket 类型 + * + * @readonly + * @type Integer + */ + + type: number + + + + /** + * + * @brief ZmqSocket 对象构造函数 + * @param type 指定 socket 类型,缺省为 zmq.PAIR + * + * + * + */ + constructor(type?: number/** = undefined*/); + + /** + * + * @brief 绑定指定地址和端口 + * @param addr 指定绑定的地址,如:"tcp://*:3000" + * + * + * + */ + bind(addr: string): void; + + /** + * + * @brief 连接到指定地址的服务器 + * @param addr 指定连接的地址,如:"tcp://*:3000" + * + * + * + */ + connect(addr: string): void; + + /** + * + * @brief 接收一个数据包 + * @return 返回接收到的数据包 + * + * + * @async + */ + recv(): Class_Buffer; + + /** + * + * @brief 发送一个数据包 + * @param data 指定发送的数据包 + * + * + * + */ + send(data: Class_Buffer): void; + + /** + * + * @brief 关闭当前 socket + * + * + */ + close(): void; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/_test_env.d.ts b/types/fibjs/declare/_test_env.d.ts new file mode 100644 index 0000000000..56bef11fa1 --- /dev/null +++ b/types/fibjs/declare/_test_env.d.ts @@ -0,0 +1,41 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + +/// +import test from 'test' + +/// +import _assert from 'assert' + +declare global { + const describe: typeof test.describe + const xdescribe: typeof test.xdescribe + const odescribe: typeof test.odescribe + const it: typeof test.it + const xit: typeof test.xit + const oit: typeof test.oit + const before: typeof test.before + const after: typeof test.after + const beforeEach: typeof test.beforeEach + const afterEach: typeof test.afterEach + const run: typeof test.run + const setup: typeof test.setup + + const assert: typeof _assert +} +/** declare const describe: test.describe; */ + + diff --git a/types/fibjs/declare/assert.d.ts b/types/fibjs/declare/assert.d.ts new file mode 100644 index 0000000000..239c02eb98 --- /dev/null +++ b/types/fibjs/declare/assert.d.ts @@ -0,0 +1,794 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 断言测试模块,如果测试值为假,则报错,报错行为可设定继续运行或者错误抛出 + * @detail 引用方法:,```JavaScript,var assert = require('assert');,```,或者通过 test 模块引用:,```JavaScript,var test = require('test');,var assert = test.assert;,```,或者通过 test.setup 配置:,```JavaScript,require("test").setup();,``` + */ +declare module "assert" { + + + module assert { + + + + + + /** + * + * @brief 测试数值为真,为假则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function Function(actual?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为真,为假则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function ok(actual?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为假,为真则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notOk(actual?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值等于预期值,不相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function equal(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不等于预期值,相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notEqual(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值严格等于预期值,不相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function strictEqual(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不严格等于预期值,相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notStrictEqual(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值深度等于预期值,不相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function deepEqual(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不深度等于预期值,相等则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notDeepEqual(actual?: any/** = v8::Undefined(isolate)*/, expected?: any/** = v8::Undefined(isolate)*/, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值近似等于预期值,否则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param delta 近似的小数精度 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function closeTo(actual: any, expected: any, delta: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不近似等于预期值,否则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param delta 近似的小数精度 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notCloseTo(actual: any, expected: any, delta: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值小于预期值,大于或等于则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function lessThan(actual: any, expected: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不小于预期值,小于则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notLessThan(actual: any, expected: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值大于预期值,小于或等于则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function greaterThan(actual: any, expected: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不大于预期值,大于则断言失败 + * @param actual 要测试的数值 + * @param expected 预期的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notGreaterThan(actual: any, expected: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试变量存在,为假则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function exist(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试变量不存在,为真则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notExist(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为布尔值真,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isTrue(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为布尔值真,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotTrue(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为布尔值假,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isFalse(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为布尔值假,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotFalse(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为 Null,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNull(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为 Null,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotNull(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为 undefined,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isUndefined(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为 undefined,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isDefined(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为函数,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isFunction(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为函数,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotFunction(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为对象,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isObject(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为对象,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotObject(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为数组,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isArray(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为数组,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotArray(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为字符串,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isString(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为字符串,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotString(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为数字,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNumber(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为数字,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotNumber(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为布尔,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isBoolean(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为布尔,否则断言失败 + * @param actual 要测试的数值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function isNotBoolean(actual: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值为给定类型,否则断言失败 + * @param actual 要测试的数值 + * @param type 指定的类型 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function typeOf(actual: any, type: string, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试数值不为给定类型,否则断言失败 + * @param actual 要测试的数值 + * @param type 指定的类型 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notTypeOf(actual: any, type: string, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试对象中包含指定属性,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function property(object: any, prop: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试对象中不包含指定属性,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notProperty(object: any, prop: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 深度测试对象中包含指定属性,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性,以“.”分割 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function deepProperty(object: any, prop: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 深度测试对象中不包含指定属性,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性,以“.”分割 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function notDeepProperty(object: any, prop: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试对象中指定属性的值为给定值,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性 + * @param value 给定的值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function propertyVal(object: any, prop: any, value: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试对象中指定属性的值不为给定值,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性 + * @param value 给定的值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function propertyNotVal(object: any, prop: any, value: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 深度测试对象中指定属性的值为给定值,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性,以“.”分割 + * @param value 给定的值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function deepPropertyVal(object: any, prop: any, value: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 深度测试对象中指定属性的值不为给定值,否则断言失败 + * @param object 要测试的对象 + * @param prop 要测试的属性,以“.”分割 + * @param value 给定的值 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function deepPropertyNotVal(object: any, prop: any, value: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试给定的代码会抛出错误,未抛出则断言失败 + * @param block 指定测试的代码,以函数形式给出 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function throws(block: Function, msg?: string/** = ""*/): void; + + /** + * + * @brief 测试给定的代码不会抛出错误,抛出则断言失败 + * @param block 指定测试的代码,以函数形式给出 + * @param msg 断言失败时的提示信息 + * + * + * + */ + export function doesNotThrow(block: Function, msg?: string/** = ""*/): void; + + /** + * + * @brief 如果参数为真,则抛出 + * @param object 参数 + * + * + * + */ + export function ifError(object?: any/** = v8::Undefined(isolate)*/): void; + + } /** end of `module assert` */ + export = assert +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/base32.d.ts b/types/fibjs/declare/base32.d.ts new file mode 100644 index 0000000000..289e9799f8 --- /dev/null +++ b/types/fibjs/declare/base32.d.ts @@ -0,0 +1,239 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief base32 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var base32 = encoding.base32;,```,或者,```JavaScript,var base32 = require('base32');,``` + */ +declare module "base32" { + + + module base32 { + + + + + + /** + * + * @brief 以 base32 方式编码数据 + * @param data 要编码的数据 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: Class_Buffer): string; + + /** + * + * @brief 以 base32 方式解码字符串为二进制数据 + * @param data 要解码的字符串 + * @return 返回解码的二进制数据 + * + * + * + */ + export function decode(data: string): Class_Buffer; + + } /** end of `module base32` */ + export = base32 +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/base64.d.ts b/types/fibjs/declare/base64.d.ts new file mode 100644 index 0000000000..7112c938e6 --- /dev/null +++ b/types/fibjs/declare/base64.d.ts @@ -0,0 +1,240 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief base64 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var base64 = encoding.base64;,```,或者,```JavaScript,var base64 = require('base64');,``` + */ +declare module "base64" { + + + module base64 { + + + + + + /** + * + * @brief 以 base64 方式编码数据 + * @param data 要编码的数据 + * @param url 指定是否使用 url 安全字符编码 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: Class_Buffer, url?: boolean/** = false*/): string; + + /** + * + * @brief 以 base64 方式解码字符串为二进制数据 + * @param data 要解码的字符串 + * @return 返回解码的二进制数据 + * + * + * + */ + export function decode(data: string): Class_Buffer; + + } /** end of `module base64` */ + export = base64 +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/base64vlq.d.ts b/types/fibjs/declare/base64vlq.d.ts new file mode 100644 index 0000000000..983bc2ad47 --- /dev/null +++ b/types/fibjs/declare/base64vlq.d.ts @@ -0,0 +1,250 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief base64vlq 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var base64vlq = encoding.base64vlq;,```,或者,```JavaScript,var base64vlq = require('base64vlq');,``` + */ +declare module "base64vlq" { + + + module base64vlq { + + + + + + /** + * + * @brief 以 base64vlq 方式编码数据 + * @param data 要编码的数据 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: number): string; + + /** + * + * @brief 以 base64vlq 方式编码数据 + * @param data 要编码的数据 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: any[]): string; + + /** + * + * @brief 以 base64vlq 方式解码字符串为二进制数据 + * @param data 要解码的字符串 + * @return 返回解码的二进制数据 + * + * + * + */ + export function decode(data: string): any[]; + + } /** end of `module base64vlq` */ + export = base64vlq +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/bson.d.ts b/types/fibjs/declare/bson.d.ts new file mode 100644 index 0000000000..31079539f8 --- /dev/null +++ b/types/fibjs/declare/bson.d.ts @@ -0,0 +1,239 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief bson 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var bson = encoding.bson;,```,或者,```JavaScript,var bson = require('bson');,``` + */ +declare module "bson" { + + + module bson { + + + + + + /** + * + * @brief 以 bson 格式编码变量 + * @param data 要编码的变量 + * @return 返回编码的二进制数据 + * + * + * + */ + export function encode(data: Object): Class_Buffer; + + /** + * + * @brief 以 bson 方式解码字符串为一个变量 + * @param data 要解码的二进制数据 + * @return 返回解码的变量 + * + * + * + */ + export function decode(data: Class_Buffer): Object; + + } /** end of `module bson` */ + export = bson +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/console.d.ts b/types/fibjs/declare/console.d.ts new file mode 100644 index 0000000000..87fe5f2cc1 --- /dev/null +++ b/types/fibjs/declare/console.d.ts @@ -0,0 +1,892 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 控制台访问对象 + * @detail 全局对象。可用于提示信息,警告和错误记录。通过启动配置文件,可将日志定位到不同的设备,以便于跟踪。日志支持格式化输出,例如:,```JavaScript,console.log("%d + %d = %d", 100, 200, 100 + 200);,```,可以使用的格式化参数如下:,- %s - 字符串,- %d - 数字,包括整数和数字,- %j - 以 JSON 格式输出对象,- %% - 输出字符 '%' 本身 + */ +declare module "console" { + + + module console { + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const FATAL = 0; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const ALERT = 1; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const CRIT = 2; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const ERROR = 3; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const WARN = 4; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const NOTICE = 5; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const INFO = 6; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const DEBUG = 7; + + /** + * + * @brief loglevel 仅用于输出,信息输出后不换行,file 和 syslog 不保存此级别信息 + * + * + */ + export const PRINT = 9; + + /** + * + * @brief loglevel 级别常量 + * + * + */ + export const NOTSET = 10; + + + + + + /** + * + * @brief 添加 console 输出系统,支持的设备为 console, syslog, event,最多可以添加 10 个输出 + * + * 通过配置 console,可以将程序输出和系统错误发往不同设备,用于运行环境信息收集。 + * + * type 为配置,为设备名称字符串: + * + * ```JavaScript + * console.add("console"); + * ``` + * + * syslog 仅在 posix 平台有效: + * ```JavaScript + * console.add("syslog"); + * ``` + * + * event 仅在 windows 平台有效: + * ```JavaScript + * console.add("event"); + * ``` + * + * @param type 输出设备 + * + * + * + */ + export function add(type: string): void; + + /** + * + * @brief 添加 console 输出系统,支持的设备为 console, syslog, event 和 file,最多可以添加 10 个输出 + * + * 通过配置 console,可以将程序输出和系统错误发往不同设备,用于运行环境信息收集。 + * + * cfg 可以为一个设备配置对象: + * ```JavaScript + * console.add({ + * type: "console", + * levels: [console.INFO, console.ERROR] // 选项,省略则输出全部级别日志 + * }); + * ``` + * + * syslog 仅在 posix 平台有效: + * ```JavaScript + * console.add({ + * type: "syslog", + * levels: [console.INFO, console.ERROR] + * }); + * ``` + * + * event 仅在 windows 平台有效: + * ```JavaScript + * console.add({ + * type: "event", + * levels: [console.INFO, console.ERROR] + * }); + * ``` + * + * file 日志: + * ```JavaScript + * console.add({ + * type: "file", + * levels: [console.INFO, console.ERROR], + * // 必选项,指定日志输出文件,可使用 s% 指定插入日期位置,不指定则添加在结尾 + * path: "path/to/file_%s.log", + * // 选项,可选值为 "day", "hour", "minute", "###k", "###m", "###g",缺省为 "1m" + * split: "30m", + * // 选项,可选范围为 2-128,缺省为 128 + * count: 10 + * }); + * ``` + * + * @param cfg 输出配置 + * + * + * + */ + export function add(cfg: Object): void; + + /** + * + * @brief 批量添加 console 输出系统,支持的设备为 console, syslog, event 和 file,最多可以添加 10 个输出 + * + * 通过配置 console,可以将程序输出和系统错误发往不同设备,用于运行环境信息收集。 + * + * ```JavaScript + * console.add(["console", { + * type: "syslog", + * levels: [console.INFO, console.ERROR] + * }]); + * ``` + * + * @param cfg 输出配置数组 + * + * + * + */ + export function add(cfg: any[]): void; + + /** + * + * @brief 初始化到缺省设置,只在 console 输出信息 + * + * + */ + export function reset(): void; + + /** + * + * @brief 记录普通日志信息,与 info 等同 + * + * 记录一般等级的日志信息。通常用于输出非错误性提示信息。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function log(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录普通日志信息,与 info 等同 + * + * 记录一般等级的日志信息。通常用于输出非错误性提示信息。 + * @param args 可选参数列表 + * + * + * + */ + export function log(...args: any[]): void; + + /** + * + * @brief 记录调试日志信息 + * + * 记录调试日志信息。通常用于输出调试信息。不重要。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function debug(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录调试日志信息 + * + * 记录调试日志信息。通常用于输出调试信息。不重要。 + * @param args 可选参数列表 + * + * + * + */ + export function debug(...args: any[]): void; + + /** + * + * @brief 记录普通日志信息,与 log 等同 + * + * 记录一般等级的日志信息。通常用于输出非错误性提示信息。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function info(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录普通日志信息,与 log 等同 + * + * 记录一般等级的日志信息。通常用于输出非错误性提示信息。 + * @param args 可选参数列表 + * + * + * + */ + export function info(...args: any[]): void; + + /** + * + * @brief 记录警告日志信息 + * + * 记录警告日志信息。通常用于输出提示性调试信息。一般重要。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function notice(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录警告日志信息 + * + * 记录警告日志信息。通常用于输出提示性调试信息。一般重要。 + * @param args 可选参数列表 + * + * + * + */ + export function notice(...args: any[]): void; + + /** + * + * @brief 记录警告日志信息 + * + * 记录警告日志信息。通常用于输出警告性调试信息。重要。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function warn(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录警告日志信息 + * + * 记录警告日志信息。通常用于输出警告性调试信息。重要。 + * @param args 可选参数列表 + * + * + * + */ + export function warn(...args: any[]): void; + + /** + * + * @brief 记录错误日志信息 + * + * 记录用于错误日志信息。通常用于输出错误信息。非常重要。系统的出错信息也会以此等级记录。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function error(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录错误日志信息 + * + * 记录用于错误日志信息。通常用于输出错误信息。非常重要。系统的出错信息也会以此等级记录。 + * @param args 可选参数列表 + * + * + * + */ + export function error(...args: any[]): void; + + /** + * + * @brief 记录关键错误日志信息 + * + * 记录用于关键错误日志信息。通常用于输出关键错误信息。非常重要。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function crit(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录关键错误日志信息 + * + * 记录用于关键错误日志信息。通常用于输出关键错误信息。非常重要。 + * @param args 可选参数列表 + * + * + * + */ + export function crit(...args: any[]): void; + + /** + * + * @brief 记录警报错误日志信息 + * + * 记录用于警报错误日志信息。通常用于输出警报错误信息。非常重要。为最高级别信息。 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function alert(fmt: string, ...args: any[]): void; + + /** + * + * @brief 记录警报错误日志信息 + * + * 记录用于警报错误日志信息。通常用于输出警报错误信息。非常重要。为最高级别信息。 + * @param args 可选参数列表 + * + * + * + */ + export function alert(...args: any[]): void; + + /** + * + * @brief 用 JSON 格式输出对象 + * @param obj 给定要显示的对象 + * + * + * + */ + export function dir(obj: any): void; + + /** + * + * @brief 启动一个计时器 + * + * @param label 标题,缺省为空字符串。 + * + * + * + */ + export function time(label?: string/** = "time"*/): void; + + /** + * + * @brief 输出指定计时器当前计时值 + * + * @param label 标题,缺省为空字符串。 + * + * + * + */ + export function timeElapse(label?: string/** = "time"*/): void; + + /** + * + * @brief 结束指定计时器,并输出最后计时值 + * + * @param label 标题,缺省为空字符串。 + * + * + * + */ + export function timeEnd(label?: string/** = "time"*/): void; + + /** + * + * @brief 输出当前调用堆栈 + * + * 通过日志输出当前调用堆栈。 + * @param label 标题,缺省为空字符串。 + * + * + * + */ + export function trace(label?: string/** = "trace"*/): void; + + /** + * + * @brief 断言测试,如果测试值为假,则报错 + * @param value 测试的数值 + * @param msg 报错信息 + * + * + * + */ + export function assert(value: any, msg?: string/** = ""*/): void; + + /** + * + * @brief 向控制台输出格式化文本,输出内容不会记入日志系统,输出文本后不会自动换行,可连续输出 + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * + * + * + */ + export function print(fmt: string, ...args: any[]): void; + + /** + * + * @brief 向控制台输出格式化文本,输出内容不会记入日志系统,输出文本后不会自动换行,可连续输出 + * @param args 可选参数列表 + * + * + * + */ + export function print(...args: any[]): void; + + /** + * + * @brief 移动控制台光标到指定位置 + * @param row 指定新光标的行坐标 + * @param column 指定新光标的列坐标 + * + * + * + */ + export function moveTo(row: number, column: number): void; + + /** + * + * @brief 隐藏控制台光标 + * + * + */ + export function hideCursor(): void; + + /** + * + * @brief 显示控制台光标 + * + * + */ + export function showCursor(): void; + + /** + * + * @brief 清除控制台 + * + * + */ + export function clear(): void; + + /** + * + * @brief 按下一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键,可以为:control, alt, shift, command + * + * + * + */ + export function keyDown(key: string, modifier?: string/** = ""*/): void; + + /** + * + * @brief 按下一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键数组,可以为:control, alt, shift, command + * + * + * + */ + export function keyDown(key: string, modifier: any[]): void; + + /** + * + * @brief 松开一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键,可以为:control, alt, shift, command + * + * + * + */ + export function keyUp(key: string, modifier?: string/** = ""*/): void; + + /** + * + * @brief 松开一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键数组,可以为:control, alt, shift, command + * + * + * + */ + export function keyUp(key: string, modifier: any[]): void; + + /** + * + * @brief 点击并松开一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键,可以为:control, alt, shift, command + * + * + * + */ + export function keyTap(key: string, modifier?: string/** = ""*/): void; + + /** + * + * @brief 点击并松开一个按键 + * + * 参数 key 可以使用字符串传入功能键: + * - 功能键:f1 - f12 + * - 方向键:up, down,left, right, home, end, pageup, pagedown + * - 编辑键:backspace, delete, insert, enter, tab, escape, space + * - 控制键:control, alt, shift, command + * @param key 指定按键,单字符直接传入,功能键传入名称 + * @param modifier 指定控制键数组,可以为:control, alt, shift, command + * + * + * + */ + export function keyTap(key: string, modifier: any[]): void; + + /** + * + * @brief 输入一个字符串 + * @param text 指定输入的字符串 + * + * + * + */ + export function typeString(text: string): void; + + /** + * + * @brief 移动鼠标到指定的位置 + * @param x 指定 x 坐标 + * @param y 指定 y 坐标 + * + * + * + */ + export function moveMouse(x: number, y: number): void; + + /** + * + * @brief 按下一个鼠标键 + * @param button 指定鼠标键名称,允许值为: left, right, moddle + * + * + * + */ + export function mouseUp(button: string): void; + + /** + * + * @brief 放开一个鼠标键 + * @param button 指定鼠标键名称,允许值为: left, right, moddle + * + * + * + */ + export function mouseDown(button: string): void; + + /** + * + * @brief 点击一个鼠标键 + * @param button 指定鼠标键名称,允许值为: left, right, moddle + * @param dbclick 指定是否双击,缺省为 false + * + * + * + */ + export function clickMouse(button: string, dbclick?: boolean/** = false*/): void; + + /** + * + * @brief 从控制台读取用户输入 + * @param msg 提示信息 + * @return 返回用户输入的信息 + * + * + * @async + */ + export function readLine(msg?: string/** = ""*/): string; + + } /** end of `module console` */ + export = console +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/constants.d.ts b/types/fibjs/declare/constants.d.ts new file mode 100644 index 0000000000..4c98aa29ce --- /dev/null +++ b/types/fibjs/declare/constants.d.ts @@ -0,0 +1,217 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 常用常量定义模块 + * @detail 引用方法:,```JavaScript,var constants = require('constants');,``` + */ +declare module "constants" { + + + module constants { + + + + + + } /** end of `module constants` */ + export = constants +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/coroutine.d.ts b/types/fibjs/declare/coroutine.d.ts new file mode 100644 index 0000000000..70a295cc8a --- /dev/null +++ b/types/fibjs/declare/coroutine.d.ts @@ -0,0 +1,343 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 并发控制模块 + * @detail 引用方法:,```JavaScript,var coroutine = require('coroutine');,``` + */ +declare module "coroutine" { + + + module coroutine { + + + + /** + * + * @brief 锁对象,参见 Lock + * + * + */ + export class Lock extends Class_Lock {} + + + /** + * + * @brief 信号量对象,参见 Semaphore + * + * + */ + export class Semaphore extends Class_Semaphore {} + + + /** + * + * @brief 条件变量对象,参见 Condition + * + * + */ + export class Condition extends Class_Condition {} + + + /** + * + * @brief 事件对象,参见 Event + * + * + */ + export class Event extends Class_Event {} + + + /** + * + * @brief 独立线程工作对象,参见 Worker + * + * + */ + export class Worker extends Class_Worker {} + + + + + /** + * + * @brief 启动一个纤程并返回纤程对象 + * @param func 制定纤程执行的函数 + * @param args 可变参数序列,此序列会在纤程内传递给函数 + * @return 返回纤程对象 + * + * + * + */ + export function start(func: Function, ...args: any[]): Class_Fiber; + + /** + * + * @brief 并行执行一组函数,并等待返回 + * @param funcs 并行执行的函数数组 + * @param fibers 限制并发 fiber 数量,缺省为 -1,启用与 funcs 数量相同 fiber + * @return 返回函数执行结果的数组 + * + * + * + */ + export function parallel(funcs: any[], fibers?: number/** = -1*/): any[]; + + /** + * + * @brief 并行执行一个函数处理一组数据,并等待返回 + * @param datas 并行执行的数据数组 + * @param func 并行执行的函数 + * @param fibers 限制并发 fiber 数量,缺省为 -1,启用与 datas 数量相同 fiber + * @return 返回函数执行结果的数组 + * + * + * + */ + export function parallel(datas: any[], func: Function, fibers?: number/** = -1*/): any[]; + + /** + * + * @brief 并行执行一个函数多次,并等待返回 + * @param func 并行执行的函数数 + * @param num 重复任务数量 + * @param fibers 限制并发 fiber 数量,缺省为 -1,启用与 funcs 数量相同 fiber + * @return 返回函数执行结果的数组 + * + * + * + */ + export function parallel(func: Function, num: number, fibers?: number/** = -1*/): any[]; + + /** + * + * @brief 并行执行一组函数,并等待返回 + * @param funcs 一组并行执行的函数 + * @return 返回函数执行结果的数组 + * + * + * + */ + export function parallel(...funcs: any[]): any[]; + + /** + * + * @brief 返回当前纤程 + * @return 当前纤程对象 + * + * + * + */ + export function current(): Class_Fiber; + + /** + * + * @brief 暂停当前纤程指定的时间 + * @param ms 指定要暂停的时间,以毫秒为单位,缺省为 0,即有空闲立即回恢复运行 + * + * + * @async + */ + export function sleep(ms?: number/** = 0*/): void; + + } /** end of `module coroutine` */ + export = coroutine +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/crypto.d.ts b/types/fibjs/declare/crypto.d.ts new file mode 100644 index 0000000000..18be4fbabc --- /dev/null +++ b/types/fibjs/declare/crypto.d.ts @@ -0,0 +1,606 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 加密算法模块 + * @detail 使用方法:,```JavaScript,var crypto = require('crypto');,``` + */ +declare module "crypto" { + + + module crypto { + + /** + * + * @brief 指定对称加密算法 AES,支持 128, 192, 256 位 key,分组密码工作模式支持 ECB, CBC, CFB128, CTR, GCM + * + * + */ + export const AES = 1; + + /** + * + * @brief 指定对称加密算法 CAMELLIA,支持 128, 192, 256 位 key,分组密码工作模式支持 ECB, CBC, CFB128, CTR, GCM + * + * + */ + export const CAMELLIA = 2; + + /** + * + * @brief 指定对称加密算法 DES,支持 64 位 key,分组密码工作模式支持 ECB, CBC + * + * + */ + export const DES = 3; + + /** + * + * @brief 指定对称加密算法 DES-EDE,支持 128 位 key,分组密码工作模式支持 ECB, CBC + * + * + */ + export const DES_EDE = 4; + + /** + * + * @brief 指定对称加密算法 DES-EDE3,支持 192 位 key,分组密码工作模式支持 ECB, CBC + * + * + */ + export const DES_EDE3 = 5; + + /** + * + * @brief 指定对称加密算法 BLOWFISH,支持 192 位 key,分组密码工作模式支持 ECB, CBC, CFB64, CTR + * + * + */ + export const BLOWFISH = 6; + + /** + * + * @brief 指定对称加密算法 ARC4,支持 40, 56, 64, 128 位 key + * + * + */ + export const ARC4 = 7; + + /** + * + * @brief 指定分组密码工作模式支持 ECB + * + * + */ + export const ECB = 1; + + /** + * + * @brief 指定分组密码工作模式支持 CBC + * + * + */ + export const CBC = 2; + + /** + * + * @brief 指定分组密码工作模式支持 CFB64 + * + * + */ + export const CFB64 = 3; + + /** + * + * @brief 指定分组密码工作模式支持 CFB128 + * + * + */ + export const CFB128 = 4; + + /** + * + * @brief 指定分组密码工作模式支持 OFB + * + * + */ + export const OFB = 5; + + /** + * + * @brief 指定分组密码工作模式支持 CTR + * + * + */ + export const CTR = 6; + + /** + * + * @brief 指定分组密码工作模式支持 GCM + * + * + */ + export const GCM = 7; + + /** + * + * @brief 指定流密码模式 + * + * + */ + export const STREAM = 8; + + /** + * + * @brief 指定分组密码工作模式支持 CCM + * + * + */ + export const CCM = 9; + + /** + * + * @brief 指定填充模式为 PKCS7 + * + * + */ + export const PKCS7 = 0; + + /** + * + * @brief 指定填充模式为 ONE_AND_ZEROS + * + * + */ + export const ONE_AND_ZEROS = 1; + + /** + * + * @brief 指定填充模式为 ZEROS_AND_LEN + * + * + */ + export const ZEROS_AND_LEN = 2; + + /** + * + * @brief 指定填充模式为 ZEROS + * + * + */ + export const ZEROS = 3; + + /** + * + * @brief 指定填充模式为 NOPADDING + * + * + */ + export const NOPADDING = 4; + + + + /** + * + * @brief Cipher 构造函数,参见 Cipher + * + * + */ + export class Cipher extends Class_Cipher {} + + + /** + * + * @brief PKey 构造函数,参见 PKey + * + * + */ + export class PKey extends Class_PKey {} + + + /** + * + * @brief X509Cert 构造函数,参见 X509Cert + * + * + */ + export class X509Cert extends Class_X509Cert {} + + + /** + * + * @brief X509Crl 构造函数,参见 X509Crl + * + * + */ + export class X509Crl extends Class_X509Crl {} + + + /** + * + * @brief X509Req 构造函数,参见 X509Req + * + * + */ + export class X509Req extends Class_X509Req {} + + + + + /** + * + * @brief 根据给定的算法名称创建一个信息摘要对象 + * @param algo 指定信息摘要对象的算法 + * @return 返回信息摘要对象 + * + * + * + */ + export function createHash(algo: string): Class_Digest; + + /** + * + * @brief 根据给定的算法名称创建一个 hmac 信息摘要对象 + * @param algo 指定信息摘要对象的算法 + * @param key 二进制签名密钥 + * @return 返回信息摘要对象 + * + * + * + */ + export function createHmac(algo: string, key: Class_Buffer): Class_Digest; + + /** + * + * @brief 加载一个 PEM/DER 格式的密钥文件 + * @param filename 密钥文件名 + * @param password 解密密码 + * @return 返回包含密钥的对象 + * + * + * + */ + export function loadPKey(filename: string, password?: string/** = ""*/): Class_PKey; + + /** + * + * @brief 加载一个 CRT/PEM/DER/TXT 格式的证书,可多次调用 + * + * loadFile 加载 mozilla 的 certdata,txt, 可于 http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt 下载使用 + * @param filename 证书文件名 + * @return 返回包含证书的对象 + * + * + * + */ + export function loadCert(filename: string): Class_X509Cert; + + /** + * + * @brief 加载一个 PEM/DER 格式的撤销证书,可多次调用 + * @param filename 撤销证书文件名 + * @return 返回包含撤销证书的对象 + * + * + * + */ + export function loadCrl(filename: string): Class_X509Crl; + + /** + * + * @brief 加载一个 PEM/DER 格式的证书请求,可多次调用 + * @param filename 证书请求文件名 + * @return 返回包含请求证书的对象 + * + * + * + */ + export function loadReq(filename: string): Class_X509Req; + + /** + * + * @brief 生成指定尺寸的随机数,使用 havege 生成器 + * @param size 指定生成的随机数尺寸 + * @return 返回生成的随机数 + * + * + * @async + */ + export function randomBytes(size: number): Class_Buffer; + + /** + * + * @brief 生成指定尺寸的低强度随机数,使用快速的算法 + * @param size 指定生成的随机数尺寸 + * @return 返回生成的随机数 + * + * + * @async + */ + export function simpleRandomBytes(size: number): Class_Buffer; + + /** + * + * @brief 生成指定尺寸的伪随机数,使用 entropy 生成器 + * @param size 指定生成的随机数尺寸 + * @return 返回生成的随机数 + * + * + * @async + */ + export function pseudoRandomBytes(size: number): Class_Buffer; + + /** + * + * @brief 生成给定数据的可视化字符图像 + * @param data 指定要展示的数据 + * @param title 指定字符图像的标题,多字节字符会导致宽度错误 + * @param size 字符图像尺寸 + * @return 返回生成的可视化字符串图像 + * + * + * + */ + export function randomArt(data: Class_Buffer, title: string, size?: number/** = 8*/): string; + + /** + * + * @brief 依据 pbkdf1 根据明文 password 生成要求的二进制钥匙 + * @param password 指定使用的密码 + * @param salt 指定 hmac 使用的 salt + * @param iterations 指定迭代次数 + * @param size 指定钥匙尺寸 + * @param algo 指定要使用的 hash 算法,详见 hash 模块 + * @return 返回生成的二进制钥匙 + * + * + * @async + */ + export function pbkdf1(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algo: number): Class_Buffer; + + /** + * + * @brief 依据 pbkdf1 根据明文 password 生成要求的二进制钥匙 + * @param password 指定使用的密码 + * @param salt 指定 hmac 使用的 salt + * @param iterations 指定迭代次数 + * @param size 指定钥匙尺寸 + * @param algoName 指定要使用的 hash 算法,详见 hash 模块 + * @return 返回生成的二进制钥匙 + * + * + * @async + */ + export function pbkdf1(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algoName: string): Class_Buffer; + + /** + * + * @brief 依据 rfc2898 根据明文 password 生成要求的二进制钥匙 + * @param password 指定使用的密码 + * @param salt 指定 hmac 使用的 salt + * @param iterations 指定迭代次数 + * @param size 指定钥匙尺寸 + * @param algo 指定要使用的 hash 算法,详见 hash 模块 + * @return 返回生成的二进制钥匙 + * + * + * @async + */ + export function pbkdf2(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algo: number): Class_Buffer; + + /** + * + * @brief 依据 rfc2898 根据明文 password 生成要求的二进制钥匙 + * @param password 指定使用的密码 + * @param salt 指定 hmac 使用的 salt + * @param iterations 指定迭代次数 + * @param size 指定钥匙尺寸 + * @param algoName 指定要使用的 hash 算法,详见 hash 模块 + * @return 返回生成的二进制钥匙 + * + * + * @async + */ + export function pbkdf2(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algoName: string): Class_Buffer; + + } /** end of `module crypto` */ + export = crypto +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/db.d.ts b/types/fibjs/declare/db.d.ts new file mode 100644 index 0000000000..5e69a8489e --- /dev/null +++ b/types/fibjs/declare/db.d.ts @@ -0,0 +1,345 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 数据库访问模块 + * @detail 基础模块。可用于创建和操作数据库资源,引用方式:,```JavaScript,var db = require('db');,``` + */ +declare module "db" { + + + module db { + + + + + + /** + * + * @brief 打开一个数据库,此方法为通用入口,根据提供的 connString 不同调用不同的引擎 + * @param connString 数据库描述,如:mysql://user:pass\@host/db + * @return 返回数据库连接对象 + * + * + * @async + */ + export function open(connString: string): Class__object; + + /** + * + * @brief 打开一个 mysql 数据库 + * @param connString 数据库描述,如:mysql://user:pass\@host/db + * @return 返回数据库连接对象 + * + * + * @async + */ + export function openMySQL(connString: string): Class_MySQL; + + /** + * + * @brief 打开一个 mysql 数据库 + * @param connString 数据库描述,如:mssql://user:pass\@host/db + * @return 返回数据库连接对象 + * + * + * @async + */ + export function openMSSQL(connString: string): Class_MSSQL; + + /** + * + * @brief 打开一个 sqlite 数据库 + * @param connString 数据库描述,如:sqlite:test.db 或者 test.db + * @return 返回数据库连接对象 + * + * + * @async + */ + export function openSQLite(connString: string): Class_SQLite; + + /** + * + * @brief 打开一个 mongodb 数据库 + * @param connString 数据库描述 + * @return 返回数据库连接对象 + * + * + * @async + */ + export function openMongoDB(connString: string): Class_MongoDB; + + /** + * + * @brief 打开一个 leveldb 数据库 + * @param connString 数据库描述,如:level:test.db 或者 test.db + * @return 返回数据库对象 + * + * + * @async + */ + export function openLevelDB(connString: string): Class_LevelDB; + + /** + * + * @brief 打开一个 Redis 数据库 + * @param connString 数据库描述,如:redis://server:port 或者 "server" + * @return 返回数据库连接对象 + * + * + * @async + */ + export function openRedis(connString: string): Class_Redis; + + /** + * + * @brief 格式化一个 sql 命令,并返回格式化结果 + * + * @param sql 格式化字符串,可选参数用 ? 指定。例如:'SELECT FROM TEST WHERE [id]=?' + * @param args 可选参数列表 + * @return 返回格式化之后的 sql 命令 + * + * + * + */ + export function format(sql: string, ...args: any[]): string; + + /** + * + * @brief 格式化一个 mysql 命令,并返回格式化结果 + * + * @param sql 格式化字符串,可选参数用 ? 指定。例如:'SELECT FROM TEST WHERE [id]=?' + * @param args 可选参数列表 + * @return 返回格式化之后的 sql 命令 + * + * + * + */ + export function formatMySQL(sql: string, ...args: any[]): string; + + /** + * + * @brief 格式化一个 mssql 命令,并返回格式化结果 + * + * @param sql 格式化字符串,可选参数用 ? 指定。例如:'SELECT FROM TEST WHERE [id]=?' + * @param args 可选参数列表 + * @return 返回格式化之后的 sql 命令 + * + * + * + */ + export function formatMSSQL(sql: string, ...args: any[]): string; + + /** + * + * @brief 将字符串编码为 SQL 安全编码字符串 + * @param str 要编码的字符串 + * @param mysql 指定 mysql 编码,缺省为 false + * @return 返回编码后的字符串 + * + * + * + */ + export function escape(str: string, mysql?: boolean/** = false*/): string; + + } /** end of `module db` */ + export = db +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/dgram.d.ts b/types/fibjs/declare/dgram.d.ts new file mode 100644 index 0000000000..1f87090814 --- /dev/null +++ b/types/fibjs/declare/dgram.d.ts @@ -0,0 +1,294 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief dgram 模块提供了 UDP 数据包 socket 的实现 + * @detail 基础模块,引用方式:,```JavaScript,var dgram = require('dgram');,``` + */ +declare module "dgram" { + + + module dgram { + + + + /** + * + * @brief dgram.Socket 对象是一个封装了数据包函数功能的 EventEmitter。参见 DgramSocket + * dgram.Socket 实例是由 dgram.createSocket() 创建的。创建 dgram.Socket 实例不需要使用 new 关键字。 + * + * + * + */ + export class DgramSocket extends Class_DgramSocket {} + + + + + /** + * + * @brief 创建一个 dgram.Socket 对象 + * + * opts 允许的选项是: + * ```JavaScript + * { + * "type": "udp4" | "udp6", // 必填 + * "reuseAddr": true | false, //若设置为 true,socket.bind() 则会重用地址,即时另一个进程已经在其上面绑定了一个套接字。 默认是 false + * "recvBufferSize": ###, // 设置 SO_RCVBUF 套接字值 + * "sendBufferSize": ### //设置 SO_RCVBUF 套接字值 + * } + * ``` + * @param opts + * @return 返回创建的 Socket 对象 + * + * + * + */ + export function createSocket(opts: Object): Class_DgramSocket; + + /** + * + * @brief 创建一个 dgram.Socket 对象 + * + * opts 允许的选项是: + * ```JavaScript + * { + * "type": "udp4" | "udp6", // 必填 + * "reuseAddr": true | false, //若设置为 true,socket.bind() 则会重用地址,即时另一个进程已经在其上面绑定了一个套接字。 默认是 false + * "recvBufferSize": ###, // 设置 SO_RCVBUF 套接字值 + * "sendBufferSize": ### //设置 SO_RCVBUF 套接字值 + * } + * ``` + * @param opts + * @param callback 为 'message' 事件添加一个监听器。 + * @return 返回创建的 Socket 对象 + * + * + * + */ + export function createSocket(opts: Object, callback: Function): Class_DgramSocket; + + /** + * + * @brief 创建一个 dgram.Socket 对象 + * @param type 套接字族,'udp4' 或 'udp6'。 + * @return 返回创建的 Socket 对象 + * + * + * + */ + export function createSocket(type: string): Class_DgramSocket; + + /** + * + * @brief 创建一个 dgram.Socket 对象 + * @param type 套接字族,'udp4' 或 'udp6'。 + * @param callback 为 'message' 事件添加一个监听器。 + * @return 返回创建的 Socket 对象 + * + * + * + */ + export function createSocket(type: string, callback: Function): Class_DgramSocket; + + } /** end of `module dgram` */ + export = dgram +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/dns.d.ts b/types/fibjs/declare/dns.d.ts new file mode 100644 index 0000000000..80a8d5fb32 --- /dev/null +++ b/types/fibjs/declare/dns.d.ts @@ -0,0 +1,239 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief dns 域名查询模块 + * @detail 基础模块,引用方式:,```JavaScript,var dns = require('dns');,``` + */ +declare module "dns" { + + + module dns { + + + + + + /** + * + * @brief 查询给定的主机名的地址 + * @param name 指定主机名 + * @return 返回查询的 ip 字符串数组 + * + * + * @async + */ + export function resolve(name: string): any[]; + + /** + * + * @brief 查询给定的主机名的地址 + * @param name 指定主机名 + * @return 返回查询的 ip 字符串 + * + * + * @async + */ + export function lookup(name: string): string; + + } /** end of `module dns` */ + export = dns +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/encoding.d.ts b/types/fibjs/declare/encoding.d.ts new file mode 100644 index 0000000000..3b02a36c47 --- /dev/null +++ b/types/fibjs/declare/encoding.d.ts @@ -0,0 +1,346 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + + + + + + + + + + + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 编码与解码模块,用于处理不同的数据编码格式与二进制之间的转换 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,``` + */ +declare module "encoding" { + + import base32NS = require('base32') + import base64NS = require('base64') + import base64vlqNS = require('base64vlq') + import hexNS = require('hex') + import iconvNS = require('iconv') + import jsonNS = require('json') + import bsonNS = require('bson') + + module encoding { + + + + /** + * + * @brief base32 编码与解码模块 + * + * + */ + + export const base32: typeof base32NS + + /** + * + * @brief base64 编码与解码模块 + * + * + */ + + export const base64: typeof base64NS + + /** + * + * @brief base64vlq 编码与解码模块 + * + * + */ + + export const base64vlq: typeof base64vlqNS + + /** + * + * @brief hex 编码与解码模块 + * + * + */ + + export const hex: typeof hexNS + + /** + * + * @brief iconv 编码与解码模块 + * + * + */ + + export const iconv: typeof iconvNS + + /** + * + * @brief json 编码与解码模块 + * + * + */ + + export const json: typeof jsonNS + + /** + * + * @brief bson 编码与解码模块 + * + * + */ + + export const bson: typeof bsonNS + + + + /** + * + * @brief 将字符串编码为 javascript 转义字符串,用以在 javascript 代码中包含文本 + * @param str 要编码的字符串 + * @param json 是否生成json兼容字符串 + * @return 返回编码的字符串 + * + * + * + */ + export function jsstr(str: string, json?: boolean/** = false*/): string; + + /** + * + * @brief url 字符串安全编码 + * @param url 要编码的 url + * @return 返回编码的字符串 + * + * + * + */ + export function encodeURI(url: string): string; + + /** + * + * @brief url 部件字符串安全编码 + * @param url 要编码的 url + * @return 返回编码的字符串 + * + * + * + */ + export function encodeURIComponent(url: string): string; + + /** + * + * @brief url 安全字符串解码 + * @param url 要解码的 url + * @return 返回解码的字符串 + * + * + * + */ + export function decodeURI(url: string): string; + + } /** end of `module encoding` */ + export = encoding +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/fs.d.ts b/types/fibjs/declare/fs.d.ts new file mode 100644 index 0000000000..4fbc6988ed --- /dev/null +++ b/types/fibjs/declare/fs.d.ts @@ -0,0 +1,648 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 文件系统处理模块 + * @detail 使用方法:,```JavaScript,var fs = require('fs');,``` + */ +declare module "fs" { + + + module fs { + + /** + * + * @brief seek 方式常量,移动到绝对位置 + * + * + */ + export const SEEK_SET = 0; + + /** + * + * @brief seek 方式常量,移动到当前位置的相对位置 + * + * + */ + export const SEEK_CUR = 1; + + /** + * + * @brief seek 方式常量,移动到文件结尾的相对位置 + * + * + */ + export const SEEK_END = 2; + + + + + + /** + * + * @brief 查询指定的文件或目录是否存在 + * @param path 指定要查询的路径 + * @return 返回 True 表示文件或目录存在 + * + * + * @async + */ + export function exists(path: string): boolean; + + /** + * + * @brief 查询用户对指定的文件的权限 + * @param path 指定要查询的路径 + * @param mode 指定查询的权限,默认为文件是否存在 + * + * + * @async + */ + export function access(path: string, mode?: number/** = 0*/): void; + + /** + * + * @brief 创建硬链接文件, windows 下不支持此方法 + * @param oldPath 源文件 + * @param newPath 将要被创建的文件 + * + * + * @async + */ + export function link(oldPath: string, newPath: string): void; + + /** + * + * @brief 删除指定的文件 + * @param path 指定要删除的路径 + * + * + * @async + */ + export function unlink(path: string): void; + + /** + * + * @brief 创建一个目录 + * @param path 指定要创建的目录名 + * @param mode 指定文件权限,Windows 忽略此参数 + * + * + * @async + */ + export function mkdir(path: string, mode?: number/** = 0777*/): void; + + /** + * + * @brief 删除一个目录 + * @param path 指定要删除的目录名 + * + * + * @async + */ + export function rmdir(path: string): void; + + /** + * + * @brief 重新命名一个文件 + * @param from 指定更名的文件 + * @param to 指定要修改的新文件名 + * + * + * @async + */ + export function rename(from: string, to: string): void; + + /** + * + * @brief 复制一个文件 + * @param from 指定更名的文件 + * @param to 指定要修改的新文件名 + * + * + * @async + */ + export function copy(from: string, to: string): void; + + /** + * + * @brief 设置指定文件的访问权限,Windows 不支持此方法 + * @param path 指定操作的文件 + * @param mode 指定设定的访问权限 + * + * + * @async + */ + export function chmod(path: string, mode: number): void; + + /** + * + * @brief 设置指定文件的访问权限,若文件是软连接则不改变指向文件的权限,只在macOS、BSD 系列平台上可用 + * @param path 指定操作的文件 + * @param mode 指定设定的访问权限 + * + * + * @async + */ + export function lchmod(path: string, mode: number): void; + + /** + * + * @brief 设置指定文件的拥有者,Windows 不支持此方法 + * @param path 指定设置的文件 + * @param uid 文件拥有者用户id + * @param gid 文件拥有者组id + * + * + * @async + */ + export function chown(path: string, uid: number, gid: number): void; + + /** + * + * @brief 设置指定文件的拥有者,如果指定的文件是软连接则不会改变其指向文件的拥有者,Windows 不支持此方法 + * @param path 指定设置的文件 + * @param uid 文件拥有者用户id + * @param gid 文件拥有者组id + * + * + * @async + */ + export function lchown(path: string, uid: number, gid: number): void; + + /** + * + * @brief 查询指定文件的基础信息 + * @param path 指定查询的文件 + * @return 返回文件的基础信息 + * + * + * @async + */ + export function stat(path: string): Class_Stat; + + /** + * + * @brief 查询指定文件的基础信息, 和stat不同的是, 当path是一个软连接的时候,返回的将是这个软连接的信息而不是指向的文件的信息 + * @param path 指定查询的文件 + * @return 返回文件的基础信息 + * + * + * @async + */ + export function lstat(path: string): Class_Stat; + + /** + * + * @brief 读取指定的软连接文件, windows 下不支持此方法 + * @param path 指定读取的软连接文件 + * @return 返回软连接指向的文件名 + * + * + * @async + */ + export function readlink(path: string): string; + + /** + * + * @brief 返回指定路径的绝对路径,如果指定路径中包含相对路径也会被展开 + * @param path 指定读取的路径 + * @return 返回处理后的绝对路径 + * + * + * @async + */ + export function realpath(path: string): string; + + /** + * + * @brief 创建软连接文件 + * @param target 目标文件,可以是文件、目录、或不存在的路径 + * @param linkpath 将被创建的软连接文件 + * @param type 创建的软连接类型, 可选类型为'file', 'dir', 'junction', 默认为'file', 该参数只在windows上有效,当为'junction'的时候将要创建的目标路径linkpath必须为绝对路径, 而target则会被自动转化为绝对路径。 + * + * + * @async + */ + export function symlink(target: string, linkpath: string, type?: string/** = "file"*/): void; + + /** + * + * @brief 修改文件尺寸,如果指定的长度大于源文件大小则用'\0'填充,否则多于的文件内容将丢失 + * @param path 指定被修改文件的路径 + * @param len 指定修改后文件的大小 + * + * + * @async + */ + export function truncate(path: string, len: number): void; + + /** + * + * @brief 根据文件描述符,读取文件内容 + * @param fd 文件描述符 + * @param buffer 读取结果写入的 Buffer 对象 + * @param offset Buffer 写入偏移量, 默认为 0 + * @param length 文件读取字节数,默认为 0 + * @param position 文件读取位置,默认为当前文件位置 + * @return 实际读取的字节数 + * + * + * @async + */ + export function read(fd: number, buffer: Class_Buffer, offset?: number/** = 0*/, length?: number/** = 0*/, position?: number/** = -1*/): number; + + /** + * + * @brief 根据文件描述符,改变文件模式。只在 POSIX 系统有效。 + * @param fd 文件描述符 + * @param mode 文件的模式 + * + * + * @async + */ + export function fchmod(fd: number, mode: number): void; + + /** + * + * @brief 根据文件描述符,改变所有者。只在 POSIX 系统有效。 + * @param fd 文件描述符 + * @param uid 用户id + * @param gid 组id + * + * + * @async + */ + export function fchown(fd: number, uid: number, gid: number): void; + + /** + * + * @brief 根据文件描述符,同步数据到磁盘 + * @param fd 文件描述符 + * + * + * @async + */ + export function fdatasync(fd: number): void; + + /** + * + * @brief 根据文件描述符,同步数据到磁盘 + * @param fd 文件描述符 + * + * + * @async + */ + export function fsync(fd: number): void; + + /** + * + * @brief 读取指定目录的文件信息 + * @param path 指定查询的目录 + * @return 返回目录的文件信息数组 + * + * + * @async + */ + export function readdir(path: string): any[]; + + /** + * + * @brief 打开文件,用于读取,写入,或者同时读写 + * + * 参数 flags 支持的方式如下: + * - 'r' 只读方式,文件不存在则抛出错误。 + * - 'r+' 读写方式,文件不存在则抛出错误。 + * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 + * - 'w+' 读写方式,文件不存在则自动创建。 + * - 'a' 只写添加方式,文件不存在则自动创建。 + * - 'a+' 读写添加方式,文件不存在则自动创建。 + * @param fname 指定文件名 + * @param flags 指定文件打开方式,缺省为 "r",只读方式 + * @return 返回打开的文件对象 + * + * + * @async + */ + export function openFile(fname: string, flags?: string/** = "r"*/): Class_SeekableStream; + + /** + * + * @brief 打开文件描述符 + * + * 参数 flags 支持的方式如下: + * - 'r' 只读方式,文件不存在则抛出错误。 + * - 'r+' 读写方式,文件不存在则抛出错误。 + * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 + * - 'w+' 读写方式,文件不存在则自动创建。 + * - 'a' 只写添加方式,文件不存在则自动创建。 + * - 'a+' 读写添加方式,文件不存在则自动创建。 + * @param fname 指定文件名 + * @param flags 指定文件打开方式,缺省为 "r",只读方式 + * @param mode 当创建文件的时候,指定文件的模式,默认 0666 + * @return 返回打开的文件描述符 + * + * + * @async + */ + export function open(fname: string, flags?: string/** = "r"*/, mode?: number/** = 0666*/): number; + + /** + * + * @brief 关闭文件描述符 + * @param fd 文件描述符 + * + * + * @async + */ + export function close(fd: number): void; + + /** + * + * @brief 打开文本文件,用于读取,写入,或者同时读写 + * + * 参数 flags 支持的方式如下: + * - 'r' 只读方式,文件不存在则抛出错误。 + * - 'r+' 读写方式,文件不存在则抛出错误。 + * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 + * - 'w+' 读写方式,文件不存在则自动创建。 + * - 'a' 只写添加方式,文件不存在则自动创建。 + * - 'a+' 读写添加方式,文件不存在则自动创建。 + * @param fname 指定文件名 + * @param flags 指定文件打开方式,缺省为 "r",只读方式 + * @return 返回打开的文件对象 + * + * + * @async + */ + export function openTextStream(fname: string, flags?: string/** = "r"*/): Class_BufferedStream; + + /** + * + * @brief 打开文本文件,并读取内容 + * @param fname 指定文件名 + * @return 返回文件文本内容 + * + * + * @async + */ + export function readTextFile(fname: string): string; + + /** + * + * @brief 打开二进制文件,并读取内容 + * @param fname 指定文件名 + * @param encoding 指定解码方式,缺省不解码 + * @return 返回文件文本内容 + * + * + * @async + */ + export function readFile(fname: string, encoding?: string/** = ""*/): any; + + /** + * + * @brief 打开文件,以数组方式读取一组文本行,行结尾标识基于 EOL 属性的设置,缺省时,posix:"\n";windows:"\r\n" + * @param fname 指定文件名 + * @param maxlines 指定此次读取的最大行数,缺省读取全部文本行 + * @return 返回读取的文本行数组,若无数据可读,或者连接中断,空数组 + * + * + * + */ + export function readLines(fname: string, maxlines?: number/** = -1*/): any[]; + + /** + * + * @brief 创建文本文件,并写入内容 + * @param fname 指定文件名 + * @param txt 指定要写入的字符串 + * + * + * @async + */ + export function writeTextFile(fname: string, txt: string): void; + + /** + * + * @brief 创建二进制文件,并写入内容 + * @param fname 指定文件名 + * @param data 指定要写入的二进制数据 + * + * + * @async + */ + export function writeFile(fname: string, data: Class_Buffer): void; + + /** + * + * @brief 创建二进制文件,并写入内容 + * @param fname 指定文件名 + * @param data 指定要写入的二进制数据 + * + * + * @async + */ + export function appendFile(fname: string, data: Class_Buffer): void; + + } /** end of `module fs` */ + export = fs +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/gd.d.ts b/types/fibjs/declare/gd.d.ts new file mode 100644 index 0000000000..5629834b34 --- /dev/null +++ b/types/fibjs/declare/gd.d.ts @@ -0,0 +1,587 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 图像文件处理模块 + * @detail 基础模块。可用于创建和操作图像文件,引用方式:,```JavaScript,var gd = require('gd');,``` + */ +declare module "gd" { + + + module gd { + + /** + * + * @brief 图像格式常量,标示当前图像来源为未知 + * + * + */ + export const NONE = 0; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 jpeg 格式数据 + * + * + */ + export const JPEG = 1; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 gif 格式数据 + * + * + */ + export const GIF = 2; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 png 格式数据 + * + * + */ + export const PNG = 3; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 tiff 格式数据 + * + * + */ + export const TIFF = 4; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 bmp 格式数据 + * + * + */ + export const BMP = 5; + + /** + * + * @brief 图像格式常量,标示当前图像来源为 webp 格式数据 + * + * + */ + export const WEBP = 6; + + /** + * + * @brief 图像类型常量,标示当前图像为真彩色图像 + * + * + */ + export const TRUECOLOR = 0; + + /** + * + * @brief 图像类型常量,标示当前图像为调色板图像 + * + * + */ + export const PALETTE = 1; + + /** + * + * @brief 扇形绘制样式,绘制一条连接开始和结束点的圆弧 + * + * + */ + export const ARC = 0; + + /** + * + * @brief 扇形绘制样式,绘制一条连接原点,开始和结束点的直线 + * + * + */ + export const CHORD = 1; + + /** + * + * @brief 扇形绘制样式,绘制不填充的扇形 + * + * + */ + export const NOFILL = 2; + + /** + * + * @brief 扇形绘制样式,绘制一条连接起点和终点的弧和连接原点的直线 + * + * + */ + export const EDGED = 4; + + /** + * + * @brief 镜像方向,横向做镜像处理 + * + * + */ + export const HORIZONTAL = 1; + + /** + * + * @brief 镜像方向,纵向做镜像处理 + * + * + */ + export const VERTICAL = 2; + + /** + * + * @brief 镜像方向,横向和纵向都做镜像处理 + * + * + */ + export const BOTH = 3; + + /** + * + * @brief 旋转方向,向左旋转 + * + * + */ + export const LEFT = 1; + + /** + * + * @brief 旋转方向,向右旋转 + * + * + */ + export const RIGHT = 2; + + /** + * + * @brief 滤波器类型:用平均移除法来达到轮廓效果 + * + * + */ + export const MEAN_REMOVAL = 0; + + /** + * + * @brief 滤波器类型:用边缘检测来突出图像的边缘 + * + * + */ + export const EDGEDETECT = 1; + + /** + * + * @brief 滤波器类型:使图像浮雕化 + * + * + */ + export const EMBOSS = 2; + + /** + * + * @brief 滤波器类型:模糊图像 + * + * + */ + export const SELECTIVE_BLUR = 3; + + /** + * + * @brief 滤波器类型:用高斯算法模糊图像 + * + * + */ + export const GAUSSIAN_BLUR = 4; + + /** + * + * @brief 滤波器类型:将图像中所有颜色反转 + * + * + */ + export const NEGATE = 5; + + /** + * + * @brief 滤波器类型:将图像转换为灰度图 + * + * + */ + export const GRAYSCALE = 6; + + /** + * + * @brief 滤波器类型:使图像更柔滑,用arg1设定柔滑级别 + * + * + */ + export const SMOOTH = 7; + + /** + * + * @brief 滤波器类型:改变图像的亮度,用arg1设定亮度级别,取值范围是-255~255 + * + * + */ + export const BRIGHTNESS = 8; + + /** + * + * @brief 滤波器类型:改变图像的对比度,用arg1设定对比度级别,取值范围是0~100 + * + * + */ + export const CONTRAST = 9; + + /** + * + * @brief 滤波器类型:改变图像的色调,用arg1、arg2、arg3分别指定red、blue、green,每种颜色范围是0~255,arg4为透明度,取值返回是0~127 + * + * + */ + export const COLORIZE = 10; + + + + + + /** + * + * @brief 创建一个新图像 + * @param width 指定图像宽度 + * @param height 指定图像高度 + * @param color 指定图像类型,允许值为 gd.TRUECOLOR 或 gd.PALETTE + * @return 返回创建成功的图像对象 + * + * + * @async + */ + export function create(width: number, height: number, color?: number/** = undefined*/): Class_Image; + + /** + * + * @brief 从格式数据中解码图像 + * @param data 给定解码的图像数据 + * @return 返回解码成功的图像对象 + * + * + * @async + */ + export function load(data: Class_Buffer): Class_Image; + + /** + * + * @brief 从流对象中解码图像 + * @param stm 给定图像数据所在的流对象 + * @return 返回解码成功的图像对象 + * + * + * @async + */ + export function load(stm: Class_SeekableStream): Class_Image; + + /** + * + * @brief 从指定文件中解码图像 + * @param fname 指定文件名 + * @return 返回解码成功的图像对象 + * + * + * @async + */ + export function load(fname: string): Class_Image; + + /** + * + * @brief 通过 rgb 颜色分量生成组合颜色 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @return 返回组合颜色 + * + * + * + */ + export function rgb(red: number, green: number, blue: number): number; + + /** + * + * @brief 通过 rgba 颜色分量生成组合颜色 + * @param red 红色分量,范围为 0-255 + * @param green 绿色分量,范围为 0-255 + * @param blue 蓝色分量,范围为 0-255 + * @param alpha 透明分量,范围为 0.0-1.0 + * @return 返回组合颜色 + * + * + * + */ + export function rgba(red: number, green: number, blue: number, alpha: number): number; + + /** + * + * @brief 通过 hsl 颜色分量生成组合颜色 + * @param hue 色相分量,范围为 0-360 + * @param saturation 饱和度分量,范围为 0.0-1.0 + * @param lightness 亮度分量,范围为 0.0-1.0 + * @return 返回组合颜色 + * + * + * + */ + export function hsl(hue: number, saturation: number, lightness: number): number; + + /** + * + * @brief 通过 hsla 颜色分量生成组合颜色 + * @param hue 色相分量,范围为 0-360 + * @param saturation 饱和度分量,范围为 0.0-1.0 + * @param lightness 亮度分量,范围为 0.0-1.0 + * @param alpha 透明分量,范围为 0.0-1.0 + * @return 返回组合颜色 + * + * + * + */ + export function hsla(hue: number, saturation: number, lightness: number, alpha: number): number; + + /** + * + * @brief 通过 hsb 颜色分量生成组合颜色 + * @param hue 色相分量,范围为 0-360 + * @param saturation 饱和度分量,范围为 0.0-1.0 + * @param brightness 明亮程度分量,范围为 0.0-1.0 + * @return 返回组合颜色 + * + * + * + */ + export function hsb(hue: number, saturation: number, brightness: number): number; + + /** + * + * @brief 通过 hsba 颜色分量生成组合颜色 + * @param hue 色相分量,范围为 0-360 + * @param saturation 饱和度分量,范围为 0.0-1.0 + * @param brightness 明亮程度分量,范围为 0.0-1.0 + * @param alpha 透明分量,范围为 0.0-1.0 + * @return 返回组合颜色 + * + * + * + */ + export function hsba(hue: number, saturation: number, brightness: number, alpha: number): number; + + /** + * + * @brief 通过字符串生成组合颜色 + * @param color 指定颜色的字符串,如:"#ff0000", "ff0000", "#f00", "f00" + * @return 返回组合颜色 + * + * + * + */ + export function color(color: string): number; + + } /** end of `module gd` */ + export = gd +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/global.d.ts b/types/fibjs/declare/global.d.ts new file mode 100644 index 0000000000..4ab9eb1713 --- /dev/null +++ b/types/fibjs/declare/global.d.ts @@ -0,0 +1,513 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 全局对象,所有脚本均可以访问的基础对象 + * @detail + */ +declare module "global" { + + import consoleNS = require('console') + import processNS = require('process') + + module global { + + + + /** + * + * @brief 二进制数据缓存对象,用于 io 读写的数据处理,参见 Buffer 对象。 + * + * + */ + export class Buffer extends Class_Buffer {} + + + /** + * + * @brief 64位整数对象,参见 Int64 对象。 + * + * + */ + export class Int64 extends Class_Int64 {} + + + /** + * + * @brief 控制台访问对象 + * + * + */ + + export const console: typeof consoleNS + + /** + * + * @brief 进程对象 + * + * + */ + + export const process: typeof processNS + + + + /** + * + * @brief 运行一个脚本 + * @param fname 指定要运行的脚本路径 + * @param argv 指定要运行的参数,此参数可在脚本内使用 argv 获取 + * + * + * + */ + export function run(fname: string, argv?: any[]/** = v8::Array::New(isolate)*/): void; + + /** + * + * @brief 加载一个模块并返回模块对象,更多信息参阅 @ref module + * + * require 可用于加载基础模块,文件模块。 + * + * 基础模块是沙箱创建时初始化的模块,引用时只需传递相应的 id,比如 require("net")。 + * + * 文件模块是用户自定义模块,引用时需传递以 ./ 或 ../ 开头的相对路径。文件模块支持 .js, .jsc 和 .json 文件。 + * + * 文件模块也支持 package.json 格式,当模块为目录结构时,require 会先查询 package.json 中的 main,未发现则尝试加载路径下的 index.js, index.jsc 或 index.json。 + * + * 若引用路径不是 ./ 或 ../ 开头,并且非基础模块,require 从当前模块所在路径下的 node_modules 查找,并上级目录递归。 + * + * 基础流程如下: + * + * ```dot + * digraph{ + * node [fontname = "Helvetica,sans-Serif", fontsize = 10]; + * edge [fontname = "Helvetica,sans-Serif", fontsize = 10]; + * + * start [label="起始"]; + * resolve [label="path.resolve" shape="rect"]; + * search [label="从当前路径\n向上递归查找\nnode_modules" shape="rect"]; + * load [label="加载" shape="rect"]; + * end [label="返回" shape="doublecircle"]; + * + * is_native [label="内置模块?" shape="diamond"]; + * is_mod [label="模块?" shape="diamond"]; + * is_abs [label="绝对路径?" shape="diamond"]; + * has_file [label="原名存在?" shape="diamond"]; + * has_ext [label="增加 .js 存在?" shape="diamond"]; + * has_package [label="/package.json\n存在?" shape="diamond"]; + * has_main [label="main 存在?" shape="diamond"]; + * has_index [label="index.js 存在?" shape="diamond"]; + * + * start -> is_native; + * is_native -> end [label="是"]; + * is_native -> is_mod [label="否"]; + * is_mod -> search [label="是"]; + * search -> has_file; + * is_mod -> is_abs [label="否"]; + * is_abs -> has_file [label="是"]; + * is_abs -> resolve [label="否"]; + * resolve -> has_file; + * has_file -> load [label="是"]; + * has_file -> has_ext [label="否"]; + * has_ext -> load [label="是"]; + * has_ext -> has_package [label="否"]; + * has_package -> has_main [label="是"]; + * has_package -> has_index [label="否"]; + * has_main -> load [label="是"]; + * has_main -> has_index [label="否"]; + * has_index -> load [label="是"]; + * has_index -> end [label="否"]; + * load -> end; + * } + * ``` + * + * @param id 指定要加载的模块名称 + * @return 返回加载模块的引出对象 + * + * + * + */ + export function require(id: string): any; + + /** + * + * @brief 在指定的时间后调用函数 + * @param callback 指定回调函数 + * @param timeout 指定延时的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setTimeout(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearTimeout(t: any): void; + + /** + * + * @brief 每间隔指定的时间后调用函数 + * @param callback 指定回调函数 + * @param timeout 指定间隔的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setInterval(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearInterval(t: any): void; + + /** + * + * @brief 每间隔指定的时间后调用函数,这是个高精度定时器,会主动打断正在运行的 JavaScript 脚本执行定时器 + * 由于 setHrInterval 的定时器会中断正在运行的代码执行回调,因此不要在回调函数内修改可能影响其它模块的数据,或者在回调中调用任何标记为 async 的 api 函数,否则将会产生不可预知的结果。例如: + * ```JavaScript + * var timers = require('timers'); + * + * var cnt = 0; + * timers.setHrInterval(() => { + * cnt++; + * }, 100); + * + * while (cnt < 10); + * + * console.error("===============================> done"); + * ``` + * 这段代码中,第 8 行的循环并不会因为 cnt 的改变而结束,因为 JavaScript 在优化代码时会认定在这个循环过程中 cnt 不会被改变。 + * @param callback 指定回调函数 + * @param timeout 指定间隔的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setHrInterval(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearHrInterval(t: any): void; + + /** + * + * @brief 下一个空闲时间立即执行回调函数 + * @param callback 指定回调函数 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setImmediate(callback: Function, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearImmediate(t: any): void; + + /** + * + * @brief 强制要求进行垃圾回收 + * + * + */ + export function GC(): void; + + /** + * + * @brief 进入交互模式,可以交互执行内部命令和代码,仅在启动 js 可以引用 + * + * 参数 cmd 格式如下: + * ```JavaScript + * [ + * { + * cmd: ".test", + * help: "this is a test", + * exec: function(argv) { + * console.log(argv); + * } + * }, + * { + * cmd: ".test1", + * help: "this is an other test", + * exec: function(argv) { + * console.log(argv); + * } + * } + * ] + * ``` + * @param cmds 补充命令 + * + * + * + */ + export function repl(cmds?: any[]/** = v8::Array::New(isolate)*/): void; + + /** + * + * @brief 进入交互模式,可以交互执行内部命令和代码,仅在启动 js 可以引用 + * + * 同一时刻只允许一个 Stream repl,新建一个 Stream repl 时,前一个 repl 将被关闭。 + * + * 参数 cmd 格式如下: + * ```JavaScript + * [ + * { + * cmd: ".test", + * help: "this is a test", + * exec: function(argv) { + * console.log(argv); + * } + * }, + * { + * cmd: ".test1", + * help: "this is an other test", + * exec: function(argv) { + * console.log(argv); + * } + * } + * ] + * ``` + * @param out 输入输出流对象,通常为网络连接 + * @param cmds 补充命令 + * + * + * + */ + export function repl(out: Class_Stream, cmds?: any[]/** = v8::Array::New(isolate)*/): void; + + } /** end of `module global` */ + export = global +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/gui.d.ts b/types/fibjs/declare/gui.d.ts new file mode 100644 index 0000000000..cacc474dd4 --- /dev/null +++ b/types/fibjs/declare/gui.d.ts @@ -0,0 +1,304 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief gui 模块 + * @detail 使用方法:,```JavaScript,var gui = require('gui');,``` + */ +declare module "gui" { + + + module gui { + + /** + * + * @brief WebView ie 模拟版本,指定 ie7 + * + * + */ + export const IE7 = 7000; + + /** + * + * @brief WebView ie 模拟版本,指定 ie8 + * + * + */ + export const IE8 = 8000; + + /** + * + * @brief WebView ie 模拟版本,指定 ie9 + * + * + */ + export const IE9 = 9000; + + /** + * + * @brief WebView ie 模拟版本,指定 ie10 + * + * + */ + export const IE10 = 10000; + + /** + * + * @brief WebView ie 模拟版本,指定 ie11 + * + * + */ + export const IE11 = 11000; + + /** + * + * @brief WebView ie 模拟版本,指定 edge + * + * + */ + export const EDGE = 11001; + + + + + + /** + * + * 设置 WebView 内 ie 最高模拟版本,当系统 ie 版本低于此版本时,将模拟系统安装版本 + * @param ver 指定 ie 模拟版本 + * + * + * + */ + export function setVersion(ver: number): void; + + /** + * + * @brief 打开一个窗口并访问指定网址 + * + * 支持以下参数: + * ```JavaScript + * { + * "left": 100, // 窗口左上角 x,缺省系统自动设定 + * "right": 100, // 窗口左上角 y,缺省系统自动设定 + * "width": 100, // 窗口宽度,缺省系统自动设定 + * "height": 100, // 窗口高度,缺省系统自动设定 + * "border": true, // 是否有边框,缺省有边框 + * "caption": true, // 是否有标题栏,缺省有标题栏 + * "resizable": true, // 是否可改变尺寸,缺省可以改变 + * "maximize": false, // 是否最大化显示,缺省不最大化 + * "visible": true, // 是否显示,缺省显示 + * "debug": true // 是否输出 WebView 内的错误和 console 信息,缺省显示 + * } + * ``` + * 当设定 width 和 height,而未设定 left 或 right 时,窗口将自动居中 + * @param url 指定的网址,,可以使用 fs:path 访问本地文件系统 + * @param opt 打开窗口参数 + * @return 返回打开的窗口对象 + * + * + * + */ + export function open(url: string, opt?: Object/** = v8::Object::New(isolate)*/): Class_WebView; + + } /** end of `module gui` */ + export = gui +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/hash.d.ts b/types/fibjs/declare/hash.d.ts new file mode 100644 index 0000000000..4058086545 --- /dev/null +++ b/types/fibjs/declare/hash.d.ts @@ -0,0 +1,522 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 信息摘要计算模块,可用于计算信息摘要和摘要签名 + * @detail + */ +declare module "hash" { + + + module hash { + + /** + * + * @brief MD2 信息摘要算法标识常量 + * + * + */ + export const MD2 = 1; + + /** + * + * @brief MD4 信息摘要算法标识常量 + * + * + */ + export const MD4 = 2; + + /** + * + * @brief MD5 信息摘要算法标识常量 + * + * + */ + export const MD5 = 3; + + /** + * + * @brief SHA1 信息摘要算法标识常量 + * + * + */ + export const SHA1 = 4; + + /** + * + * @brief SHA224 信息摘要算法标识常量 + * + * + */ + export const SHA224 = 5; + + /** + * + * @brief SHA256 信息摘要算法标识常量 + * + * + */ + export const SHA256 = 6; + + /** + * + * @brief SHA384 信息摘要算法标识常量 + * + * + */ + export const SHA384 = 7; + + /** + * + * @brief SHA512 信息摘要算法标识常量 + * + * + */ + export const SHA512 = 8; + + /** + * + * @brief RIPEMD160 信息摘要算法标识常量 + * + * + */ + export const RIPEMD160 = 9; + + + + + + /** + * + * @brief 根据指定的算法标识创建一个信息摘要运算对象 + * @param algo 指定摘要运算算法 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function digest(algo: number, data: Class_Buffer): Class_Digest; + + /** + * + * @brief 根据指定的算法标识创建一个信息摘要运算对象 + * @param algo 指定摘要运算算法 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function digest(algo: number): Class_Digest; + + /** + * + * @brief 创建一个 MD2 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function md2(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 MD4 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function md4(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 MD5 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function md5(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA1 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function sha1(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA224 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function sha224(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA256 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function sha256(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA384 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function sha384(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA512 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function sha512(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 RIPEMD160 信息摘要运算对象 + * @param data 创建同时更新的二进制数据 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function ripemd160(data: Class_Buffer): Class_Digest; + + /** + * + * @brief 根据指定的算法标识创建一个信息摘要签名运算对象 + * @param algo 指定摘要运算算法 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac(algo: number, key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 MD2 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_md2(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 MD4 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_md4(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 MD5 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_md5(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA1 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_sha1(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA224 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_sha224(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA256 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_sha256(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA384 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_sha384(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 SHA512 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_sha512(key: Class_Buffer): Class_Digest; + + /** + * + * @brief 创建一个 RIPEMD160 信息摘要签名运算对象 + * @param key 二进制签名密钥 + * @return 返回构造的信息摘要对象 + * + * + * + */ + export function hmac_ripemd160(key: Class_Buffer): Class_Digest; + + } /** end of `module hash` */ + export = hash +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/hex.d.ts b/types/fibjs/declare/hex.d.ts new file mode 100644 index 0000000000..b05e3cf7bb --- /dev/null +++ b/types/fibjs/declare/hex.d.ts @@ -0,0 +1,239 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief hex 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var hex = encoding.hex;,```,或者,```JavaScript,var hex = require('hex');,``` + */ +declare module "hex" { + + + module hex { + + + + + + /** + * + * @brief 以 hex 方式编码数据 + * @param data 要编码的数据 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: Class_Buffer): string; + + /** + * + * @brief 以 hex 方式解码字符串为二进制数据 + * @param data 要解码的字符串 + * @return 返回解码的二进制数据 + * + * + * + */ + export function decode(data: string): Class_Buffer; + + } /** end of `module hex` */ + export = hex +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/http.d.ts b/types/fibjs/declare/http.d.ts new file mode 100644 index 0000000000..d5080f12bb --- /dev/null +++ b/types/fibjs/declare/http.d.ts @@ -0,0 +1,441 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 超文本传输协议模块,用以支持 http 协议处理 + * @detail + */ +declare module "http" { + + + module http { + + + + /** + * + * @brief 创建一个 http 请求对象,参见 HttpRequest + * + * + */ + export class HttpRequest extends Class_HttpRequest {} + + + /** + * + * @brief 创建一个 http 响应对象,参见 HttpResponse + * + * + */ + export class HttpResponse extends Class_HttpResponse {} + + + /** + * + * @brief 创建一个 http cookie 对象,参见 HttpCookie + * + * + */ + export class HttpCookie extends Class_HttpCookie {} + + + /** + * + * @brief 创建一个 http 服务器,参见 HttpServer + * + * + */ + export class HttpServer extends Class_HttpServer {} + + + /** + * + * @brief 创建一个 http 客户端,参见 HttpClient + * + * + */ + export class HttpClient extends Class_HttpClient {} + + + /** + * + * @brief 创建一个 https 服务器,参见 HttpsServer + * + * + */ + export class HttpsServer extends Class_HttpsServer {} + + + /** + * + * @brief 创建一个 http 协议处理器对象,参见 HttpHandler + * + * + */ + export class HttpHandler extends Class_HttpHandler {} + + + + + /** + * + * @brief 创建一个 http 静态文件处理器,用以用静态文件响应 http 消息 + * + * fileHandler 支持 gzip 预压缩,当请求接受 gzip 编码,且相同路径下 filename.ext.gz 文件存在时,将直接返回此文件, + * 从而避免重复压缩带来服务器负载。 + * @param root 文件根路径 + * @param mimes 扩展 mime 设置 + * @param autoIndex 是否支持浏览目录文件,缺省为 false,不支持 + * @return 返回一个静态文件处理器用于处理 http 消息 + * + * + * + */ + export function fileHandler(root: string, mimes?: Object/** = v8::Object::New(isolate)*/, autoIndex?: boolean/** = false*/): Class_Handler; + + /** + * + * @brief 发送 http 请求到指定的流对象,并返回结果 + * @param conn 指定处理请求的流对象 + * @param req 要发送的 HttpRequest 对象 + * @return 返回服务器响应 + * + * + * @async + */ + export function request(conn: Class_Stream, req: Class_HttpRequest): Class_HttpResponse; + + /** + * + * @brief 请求指定的 url,并返回结果 + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param method 指定 http 请求方法:GET, POST 等 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function request(method: string, url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 GET 方法请求指定的 url,并返回结果,等同于 request("GET", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function get(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 POST 方法请求指定的 url,并返回结果,等同于 request("POST", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function post(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 DELETE 方法请求指定的 url,并返回结果,等同于 request("DELETE", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function del(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 PUT 方法请求指定的 url,并返回结果,等同于 request("PUT", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function put(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + /** + * + * @brief 用 PATCH 方法请求指定的 url,并返回结果,等同于 request("PATCH", ...) + * opts 包含请求的附加选项,支持的内容如下: + * ```JavaScript + * { + * "query": {}, + * "body": SeekedStream | Buffer | String | {}, + * "json": {}, + * "headers": {} + * } + * ``` + * 其中 body,json 不得同时出现。缺省为 {},不包含任何附加信息 + * @param url 指定 url,必须是包含主机的完整 url + * @param opts 指定附加信息 + * @return 返回服务器响应 + * + * + * @async + */ + export function patch(url: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_HttpResponse; + + } /** end of `module http` */ + export = http +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/iconv.d.ts b/types/fibjs/declare/iconv.d.ts new file mode 100644 index 0000000000..aa431209d3 --- /dev/null +++ b/types/fibjs/declare/iconv.d.ts @@ -0,0 +1,252 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief iconv 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var iconv = encoding.iconv;,```,或者,```JavaScript,var iconv = require('iconv');,``` + */ +declare module "iconv" { + + + module iconv { + + + + + + /** + * + * @brief 用 iconv 将文本转换为二进制数据 + * @param charset 指定字符集 + * @param data 要转换的文本 + * @return 返回解码的二进制数据 + * + * + * + */ + export function encode(charset: string, data: string): Class_Buffer; + + /** + * + * @brief 用 iconv 将 Buffer 内容转换为文本 + * @param charset 指定字符集 + * @param data 要转换的二进制数据 + * @return 返回编码的字符串 + * + * + * + */ + export function decode(charset: string, data: Class_Buffer): string; + + /** + * + * @brief 检测字符集是否被支持 + * @param charset 指定字符集 + * @return 返回是否支持该字符集 + * + * + * + */ + export function isEncoding(charset: string): boolean; + + } /** end of `module iconv` */ + export = iconv +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/index.d.ts b/types/fibjs/declare/index.d.ts new file mode 100644 index 0000000000..949a96997d --- /dev/null +++ b/types/fibjs/declare/index.d.ts @@ -0,0 +1,116 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +import _Global from 'global'; +import _Process from 'process'; + +// declare const process: typeof _Process; +// declare const global: typeof _Global; +// declare const __filename: string; +// declare const __dirname: string; +// declare const require: typeof _Global.require; + +type GlobalExportsType = any; +interface ModuleType { + exports: GlobalExportsType; +} + +type O_Process = typeof _Process +interface RealProcess extends O_Process { + env: { + [key: string]: string; + } +} + +declare global { + var exports: GlobalExportsType; + const module: ModuleType; + const __filename: string; + const __dirname: string; + const process: RealProcess; + const global: typeof _Global; + + + const Buffer: typeof Class_Buffer; + const Int64: typeof Class_Int64; + /** const console: console; */ + /** const process: process; */ + const Master: typeof Class_Worker; + /** const global: Object; */ + /** const run: null; */ + const require: typeof _Global.require + /** const setTimeout: Timer; */ + /** const clearTimeout: null; */ + /** const setInterval: Timer; */ + /** const clearInterval: null; */ + const setHrInterval: typeof _Global.setHrInterval + const clearHrInterval: typeof _Global.clearHrInterval + /** const setImmediate: Timer; */ + /** const clearImmediate: null; */ + const GC: typeof _Global.GC + const repl: typeof _Global.repl +} + + diff --git a/types/fibjs/declare/io.d.ts b/types/fibjs/declare/io.d.ts new file mode 100644 index 0000000000..e0886c95ef --- /dev/null +++ b/types/fibjs/declare/io.d.ts @@ -0,0 +1,259 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 输入输出处理模块 + * @detail 使用方法:,```JavaScript,var io = require('io');,``` + */ +declare module "io" { + + + module io { + + + + /** + * + * @brief 创建一个内存流对象,参见 MemoryStream + * + * + */ + export class MemoryStream extends Class_MemoryStream {} + + + /** + * + * @brief 创建一个缓存流读取对象,参见 BufferedStream + * + * + */ + export class BufferedStream extends Class_BufferedStream {} + + + + + /** + * + * @brief 复制流数据到目标流中 + * @param from 源流对象 + * @param to 目标流对象 + * @param bytes 复制的字节数 + * @return 返回复制的字节数 + * + * + * @async + */ + export function copyStream(from: Class_Stream, to: Class_Stream, bytes?: number/** = -1*/): number; + + /** + * + * @brief 双向复制流数据,直到流中无数据,或者流被关闭 + * @param stm1 流对象一 + * @param stm2 流对象二 + * + * + * @async + */ + export function bridge(stm1: Class_Stream, stm2: Class_Stream): void; + + } /** end of `module io` */ + export = io +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/json.d.ts b/types/fibjs/declare/json.d.ts new file mode 100644 index 0000000000..0dfba0a3d5 --- /dev/null +++ b/types/fibjs/declare/json.d.ts @@ -0,0 +1,239 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief json 编码与解码模块 + * @detail 引用方式:,```JavaScript,var encoding = require('encoding');,var json = encoding.json;,```,或者,```JavaScript,var json = require('json');,``` + */ +declare module "json" { + + + module json { + + + + + + /** + * + * @brief 以 json 格式编码变量 + * @param data 要编码的变量 + * @return 返回编码的字符串 + * + * + * + */ + export function encode(data: any): string; + + /** + * + * @brief 以 json 方式解码字符串为一个变量 + * @param data 要解码的字符串 + * @return 返回解码的变量 + * + * + * + */ + export function decode(data: string): any; + + } /** end of `module json` */ + export = json +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/mq.d.ts b/types/fibjs/declare/mq.d.ts new file mode 100644 index 0000000000..21e4a5a25e --- /dev/null +++ b/types/fibjs/declare/mq.d.ts @@ -0,0 +1,307 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 消息队列模块 + * @detail + */ +declare module "mq" { + + + module mq { + + + + /** + * + * @brief 创建一个消息对象,参见 Message + * + * + */ + export class Message extends Class_Message {} + + + /** + * + * @brief 创建一个 http 协议处理器对象,参见 HttpHandler + * + * + */ + export class HttpHandler extends Class_HttpHandler {} + + + /** + * + * @brief 创建一个消息处理器对象,传递值内置处理器则直接返回 + * + * hdlr 接受内置消息处理器,处理函数,链式处理数组,路由对象: + * - Function javascript 函数,将使用此函数进行处理 + * - Handler 内置处理器,将使用此处理器进行处理 + * - 链式处理数组,等同于返回 new mq.Chain(hdlr),参见 Chain + * - 路由对象,等同于返回 new mq.Routing(hdlr),参见 Routing + * + * 消息处理函数语法如下: + * ```JavaScript + * function func(v){ + * } + * ``` + * 参数 v 为正在处理的消息,返回结果允许有四种: + * - Function javascript 函数,将使用此函数进行下一阶段处理 + * - Handler 内置处理器,将使用此处理器进行下一阶段处理 + * - 链式处理数组,等同于 new mq.Chain(v),参见 Chain + * - 路由对象,等同于 new mq.Routing(v),参见 Routing + * + * 无返回或者其他的返回结果将结束消息处理。 + * @param hdlr 内置消息处理器,处理函数,链式处理数组,路由对象 + * @return 返回封装了处理函数的处理器 + * + * + * + */ + export class Handler extends Class_Handler {} + + + /** + * + * @brief 创建一个消息处理器链处理对象,参见 Chain + * + * + */ + export class Chain extends Class_Chain {} + + + /** + * + * @brief 创建一个消息处理器路由对象,参见 Routing + * + * + */ + export class Routing extends Class_Routing {} + + + + + /** + * + * @brief 创建一个空处理器对象,次处理对象不做任何处理直接返回 + * @return 返回空处理函数 + * + * + * + */ + export function nullHandler(): Class_Handler; + + /** + * + * @brief 使用给定的处理器处理一个消息或对象 + * + * 不同于处理器的 invoke 方法,此方法将循环调用每个处理器的返回处理器,直到处理器返回 null 为止。 + * @param hdlr 指定使用的处理器 + * @param v 指定要处理的消息或对象 + * + * + * @async + */ + export function invoke(hdlr: Class_Handler, v: Class__object): void; + + } /** end of `module mq` */ + export = mq +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/net.d.ts b/types/fibjs/declare/net.d.ts new file mode 100644 index 0000000000..dcf90e72eb --- /dev/null +++ b/types/fibjs/declare/net.d.ts @@ -0,0 +1,396 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 网络访问模块 + * @detail 基础模块。可用于创建和操作网络资源,引用方式:,```JavaScript,var net = require('net');,``` + */ +declare module "net" { + + + module net { + + /** + * + * @brief 地址集常量,指定 ipv4 + * + * + */ + export const AF_INET = 2; + + /** + * + * @brief 地址集常量,指定 ipv6 + * + * + */ + export const AF_INET6 = 10; + + /** + * + * @brief 协议族常量,指定 tcp + * + * + */ + export const SOCK_STREAM = 1; + + /** + * + * @brief 协议族常量,指定 udp + * + * + */ + export const SOCK_DGRAM = 2; + + + + /** + * + * @brief 创建一个 Socket 对象,参见 Socket + * + * + */ + export class Socket extends Class_Socket {} + + + /** + * + * @brief 创建一个 Smtp 对象,参见 Smtp + * + * + */ + export class Smtp extends Class_Smtp {} + + + /** + * + * @brief 创建一个 TcpServer 对象,参见 TcpServer + * + * + */ + export class TcpServer extends Class_TcpServer {} + + + /** + * + * @brief 创建一个 UrlObject 对象,参见 UrlObject + * + * + */ + export class UrlObject extends Class_UrlObject {} + + + + + /** + * + * @brief 查询当前运行环境网络信息 + * @return 返回网卡信息 + * + * + * + */ + export function info(): Object; + + /** + * + * @brief 查询给定的主机名的地址 + * @param name 指定主机名 + * @param family 指定查询返回类型,缺省为 AF_INET + * @return 返回查询的 ip 字符串 + * + * + * @async + */ + export function resolve(name: string, family?: number/** = undefined*/): string; + + /** + * + * @brief 快速查询的主机地址,等效与 resolve(name) + * @param name 指定主机名 + * @return 返回查询的 ip 字符串 + * + * + * @async + */ + export function ip(name: string): string; + + /** + * + * @brief 快速查询的主机 ipv6 地址,等效与 resolve(name, net.AF_INET6) + * @param name 指定主机名 + * @return 返回查询的 ipv6 字符串 + * + * + * @async + */ + export function ipv6(name: string): string; + + /** + * + * @brief 创建一个 Socket 或 SslSocket 对象并建立连接 + * @param url 指定连接的协议,可以是:tcp://host:port 或者 ssl://host:port + * @param timeout 指定超时时间,单位是毫秒,默认为0 + * @return 返回连接成功的 Socket 或者 SslSocket 对象 + * + * + * @async + */ + export function connect(url: string, timeout?: number/** = 0*/): Class_Stream; + + /** + * + * @brief 创建一个 Smtp 对象并建立连接,参见 Smtp + * @param url 指定连接的协议,可以是:tcp://host:port 或者 ssl://host:port + * @param timeout 指定超时时间,单位是毫秒,默认为0 + * @return 返回连接成功的 Smtp 对象 + * + * + * @async + */ + export function openSmtp(url: string, timeout?: number/** = 0*/): Class_Smtp; + + /** + * + * @brief 查询当前系统异步网络引擎 + * @return 返回网络引擎名称 + * + * + * + */ + export function backend(): string; + + /** + * + * @brief 检测输入是否是 IP 地址 + * @param ip 指定要检测的字符串 + * @return 非合法的 IP 地址,返回 0, 如果是 IPv4 则返回 4,如果是 IPv6 则返回 6 + * + * + * + */ + export function isIP(ip?: string/** = ""*/): number; + + /** + * + * @brief 检测输入是否是 IPv4 地址 + * @param ip 指定要检测的字符串 + * @return 如果是 IPv4 则返回 true.否则返回 false + * + * + * + */ + export function isIPv4(ip?: string/** = ""*/): boolean; + + /** + * + * @brief 检测输入是否是 IPv6 地址 + * @param ip 指定要检测的字符串 + * @return 如果是 IPv6 则返回 true.否则返回 false + * + * + * + */ + export function isIPv6(ip?: string/** = ""*/): boolean; + + } /** end of `module net` */ + export = net +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/object.d.ts b/types/fibjs/declare/object.d.ts new file mode 100644 index 0000000000..c6f46e8ec9 --- /dev/null +++ b/types/fibjs/declare/object.d.ts @@ -0,0 +1,54 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/** module Or Internal Object */ +/** + * @brief 基础对象,所有对象均继承于此 + * @detail + */ + +declare class Class__object { + + + + /** + * + * @brief 返回对象的字符串表示,一般返回 "[Native Object]",对象可以根据自己的特性重新实现 + * @return 返回对象的字符串表示 + * + * + * + */ + toString(): string; + + /** + * + * @brief 返回对象的 JSON 格式表示,一般返回对象定义的可读属性集合 + * @param key 未使用 + * @return 返回包含可 JSON 序列化的值 + * + * + * + */ + toJSON(key?: string/** = ""*/): any; + +} /** endof class */ + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/os.d.ts b/types/fibjs/declare/os.d.ts new file mode 100644 index 0000000000..bf8244203e --- /dev/null +++ b/types/fibjs/declare/os.d.ts @@ -0,0 +1,457 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 操作系统与文件系统处理模块 + * @detail 使用方法:,```JavaScript,var os = require('os');,``` + */ +declare module "os" { + + + module os { + + + + /** + * + * @brief Service 构造函数,参见 Service + * + * + */ + export class Service extends Class_Service {} + + + + + /** + * + * @brief 查询当前运行环境主机名 + * @return 返回主机名 + * + * + * + */ + export function hostname(): string; + + /** + * + * @brief 查询当前 CPU 的字节顺序 + * @return 返回字节顺序 + * + * + * + */ + export function endianness(): string; + + /** + * + * @brief 查询当前运行环境操作系统名称 + * @return 返回系统名称 + * + * + * + */ + export function type(): string; + + /** + * + * @brief 查询当前运行环境操作系统版本 + * @return 返回版本信息 + * + * + * + */ + export function release(): string; + + /** + * + * @brief 查询当前用户目录 + * @return 返回目录字符串 + * + * + * + */ + export function homedir(): string; + + /** + * + * @brief 查询当前 cpu 环境 + * @return 返回 cpu 类型,可能的结果为 'amd64', 'arm', 'arm64', 'ia32' + * + * + * + */ + export function arch(): string; + + /** + * + * @brief 查询运行环境运行时间,以秒为单位 + * @return 返回表示时间的数值 + * + * + * + */ + export function uptime(): number; + + /** + * + * @brief 查询运行环境 1分钟,5分钟,15分钟平均负载 + * @return 返回包含三个负载数据的数组 + * + * + * + */ + export function loadavg(): any[]; + + /** + * + * @brief 查询运行环境总内存,以字节为单位 + * @return 返回内存数据 + * + * + * + */ + export function totalmem(): number; + + /** + * + * @brief 查询运行环境可用内存,以字节为单位 + * @return 返回内存数据 + * + * + * + */ + export function freemem(): number; + + /** + * + * @brief 查询当前运行环境 cpu 个数和参数 + * @return 返回包含 cpu 参数的数组,每一项对应一个 cpu + * + * + * + */ + export function cpus(): any[]; + + /** + * + * @brief 查询当前运行环境 cpu 个数 + * @return 返回 cpu 个数 + * + * + * + */ + export function cpuNumbers(): number; + + /** + * + * @brief 查询当前运行环境临时文件目录 + * @return 返回临时文件目录 + * + * + * + */ + export function tmpdir(): string; + + /** + * + * @brief 返回当前有效执行用户信息 + * @param options 用于解释结果字符串的字符编码 + * @return 当前有效执行用户信息 + * + * + * + */ + export function userInfo(options?: Object/** = v8::Object::New(isolate)*/): Object; + + /** + * + * @brief 查询当前运行环境网络信息 + * @return 返回网卡信息 + * + * + * + */ + export function networkInterfaces(): Object; + + /** + * + * @brief 查询当前主机的打印机信息 + * @return 返回打印机信息 + * + * + * + */ + export function printerInfo(): any[]; + + /** + * + * @brief 创建一个打印机输出对象 + * @param name 打印机名称 + * @return 返回打印机输出对象 + * + * + * @async + */ + export function openPrinter(name: string): Class_BufferedStream; + + /** + * + * @brief 查询当前平台名称 + * @return 返回平台名称,可能的结果为 'darwin', 'freebsd', 'linux', 或 'win32' + * + * + * + */ + export function platform(): string; + + /** + * + * @brief 解析时间字符串或查询运行环境当前时间 + * @param tmString 时间字符串,缺省则查询当前时间 + * @return 返回 javascript Date 对象 + * + * + * + */ + export function time(tmString?: string/** = ""*/): Date; + + /** + * + * @brief 时间计算函数,根据 part 指定计算时间 + * @param d 指定用于计算 Date 对象 + * @param num 指定运算的数值 + * @param part 指定运算的时间部位,接收值为:"year", "month", "day", "hour", "minute", "second" + * @return 返回 javascript Date 对象 + * + * + * + */ + export function dateAdd(d: Date, num: number, part: string): Date; + + /** + * + * @brief 查询当前进程内存使用报告 + * + * 内存报告生成类似以下结果: + * ```JavaScript + * { + * "rss": 8622080, + * "heapTotal": 4083456, + * "heapUsed": 1621800, + * "nativeObjects": 122 + * } + * ``` + * 其中: + * - rss 返回进程当前占用物理内存大小 + * - heapTotal 返回 v8 引擎堆内存大小 + * - heapUsed 返回 v8 引擎正在使用堆内存大小 + * - nativeObjects 返回当前有效内置对象数 + * @return 返回包含内存报告 + * + * + * + */ + export function memoryUsage(): Object; + + } /** end of `module os` */ + export = os +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/path.d.ts b/types/fibjs/declare/path.d.ts new file mode 100644 index 0000000000..ac33e6db2c --- /dev/null +++ b/types/fibjs/declare/path.d.ts @@ -0,0 +1,326 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 文件路径处理模块 + * @detail 引用方法:,```JavaScript,var path = require('path');,``` + */ +declare module "path" { + + + module path { + + + + + + /** + * + * @brief 标准化路径,处理路径中父目录等信息 + * + * @param path 给定的未处理的路径 + * @return 返回经过处理的路径 + * + * + * + */ + export function normalize(path: string): string; + + /** + * + * @brief 查询路径中的文件名称,若指定扩展名,则自动取消匹配的扩展名 + * + * @param path 给定查询的路径 + * @param ext 指定扩展名,若文件名中有符合条件的扩展名,将自动取消 + * @return 返回文件名称 + * + * + * + */ + export function basename(path: string, ext?: string/** = ""*/): string; + + /** + * + * @brief 查询路径中的文件扩展名 + * + * @param path 给定查询的路径 + * @return 返回得到的扩展名 + * + * + * + */ + export function extname(path: string): string; + + /** + * + * @brief 查询路径中的目录路径 + * + * @param path 给定查询的路径 + * @return 返回得到的目录的路径 + * + * + * + */ + export function dirname(path: string): string; + + /** + * + * @brief 转换给定路径为全路径 + * + * @param path 给定转换的路径 + * @return 返回转换的全路径 + * + * + * + */ + export function fullpath(path: string): string; + + /** + * + * @brief 识别给定的路径是否是绝对路径 + * + * @param path 给定需要识别的路径 + * @return 是绝对路径则返回 true + * + * + * + */ + export function isAbsolute(path: string): boolean; + + /** + * + * @brief 合并一系列路径成为一个单一路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function join(...ps: any[]): string; + + /** + * + * @brief 合并一系列路径成为一个绝对路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function resolve(...ps: any[]): string; + + /** + * + * @brief 转换成 namespace-prefixed 路径。只在 windows 有效,其他系统直接返回。 + * see: https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + * @param path 给定的路径。 + * @return 返回得到的新路径 + * + * + * + */ + export function toNamespacedPath(path?: any/** = v8::Undefined(isolate)*/): any; + + } /** end of `module path` */ + export = path +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/path_posix.d.ts b/types/fibjs/declare/path_posix.d.ts new file mode 100644 index 0000000000..afc2cf132b --- /dev/null +++ b/types/fibjs/declare/path_posix.d.ts @@ -0,0 +1,326 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 文件路径处理模块 + * @detail 引用方法:,```JavaScript,var path = require('path').posix;,``` + */ +declare module "path_posix" { + + + module path_posix { + + + + + + /** + * + * @brief 标准化路径,处理路径中父目录等信息 + * + * @param path 给定的未处理的路径 + * @return 返回经过处理的路径 + * + * + * + */ + export function normalize(path: string): string; + + /** + * + * @brief 查询路径中的文件名称,若指定扩展名,则自动取消匹配的扩展名 + * + * @param path 给定查询的路径 + * @param ext 指定扩展名,若文件名中有符合条件的扩展名,将自动取消 + * @return 返回文件名称 + * + * + * + */ + export function basename(path: string, ext?: string/** = ""*/): string; + + /** + * + * @brief 查询路径中的文件扩展名 + * + * @param path 给定查询的路径 + * @return 返回得到的扩展名 + * + * + * + */ + export function extname(path: string): string; + + /** + * + * @brief 查询路径中的目录路径 + * + * @param path 给定查询的路径 + * @return 返回得到的目录的路径 + * + * + * + */ + export function dirname(path: string): string; + + /** + * + * @brief 转换给定路径为全路径 + * + * @param path 给定转换的路径 + * @return 返回转换的全路径 + * + * + * + */ + export function fullpath(path: string): string; + + /** + * + * @brief 识别给定的路径是否是绝对路径 + * + * @param path 给定需要识别的路径 + * @return 是绝对路径则返回 true + * + * + * + */ + export function isAbsolute(path: string): boolean; + + /** + * + * @brief 合并一系列路径成为一个单一路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function join(...ps: any[]): string; + + /** + * + * @brief 合并一系列路径成为一个绝对路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function resolve(...ps: any[]): string; + + /** + * + * @brief 转换成 namespace-prefixed 路径。只在 windows 有效,其他系统直接返回。 + * see: https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + * @param path 给定的路径。 + * @return 返回得到的新路径 + * + * + * + */ + export function toNamespacedPath(path?: any/** = v8::Undefined(isolate)*/): any; + + } /** end of `module path_posix` */ + export = path_posix +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/path_win32.d.ts b/types/fibjs/declare/path_win32.d.ts new file mode 100644 index 0000000000..8cb0812a0e --- /dev/null +++ b/types/fibjs/declare/path_win32.d.ts @@ -0,0 +1,326 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 文件路径处理模块 + * @detail 引用方法:,```JavaScript,var path = require('path').win32;,``` + */ +declare module "path_win32" { + + + module path_win32 { + + + + + + /** + * + * @brief 标准化路径,处理路径中父目录等信息 + * + * @param path 给定的未处理的路径 + * @return 返回经过处理的路径 + * + * + * + */ + export function normalize(path: string): string; + + /** + * + * @brief 查询路径中的文件名称,若指定扩展名,则自动取消匹配的扩展名 + * + * @param path 给定查询的路径 + * @param ext 指定扩展名,若文件名中有符合条件的扩展名,将自动取消 + * @return 返回文件名称 + * + * + * + */ + export function basename(path: string, ext?: string/** = ""*/): string; + + /** + * + * @brief 查询路径中的文件扩展名 + * + * @param path 给定查询的路径 + * @return 返回得到的扩展名 + * + * + * + */ + export function extname(path: string): string; + + /** + * + * @brief 查询路径中的目录路径 + * + * @param path 给定查询的路径 + * @return 返回得到的目录的路径 + * + * + * + */ + export function dirname(path: string): string; + + /** + * + * @brief 转换给定路径为全路径 + * + * @param path 给定转换的路径 + * @return 返回转换的全路径 + * + * + * + */ + export function fullpath(path: string): string; + + /** + * + * @brief 识别给定的路径是否是绝对路径 + * + * @param path 给定需要识别的路径 + * @return 是绝对路径则返回 true + * + * + * + */ + export function isAbsolute(path: string): boolean; + + /** + * + * @brief 合并一系列路径成为一个单一路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function join(...ps: any[]): string; + + /** + * + * @brief 合并一系列路径成为一个绝对路径 + * + * @param ps 一个或多个相关的路径 + * @return 返回得到的新路径 + * + * + * + */ + export function resolve(...ps: any[]): string; + + /** + * + * @brief 转换成 namespace-prefixed 路径。只在 windows 有效,其他系统直接返回。 + * see: https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + * @param path 给定的路径。 + * @return 返回得到的新路径 + * + * + * + */ + export function toNamespacedPath(path?: any/** = v8::Undefined(isolate)*/): any; + + } /** end of `module path_win32` */ + export = path_win32 +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/process.d.ts b/types/fibjs/declare/process.d.ts new file mode 100644 index 0000000000..eebbf49c2c --- /dev/null +++ b/types/fibjs/declare/process.d.ts @@ -0,0 +1,465 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 进程处理模块,用以管理当前进程的资源 + * @detail 引用方法:,```JavaScript,var process = require('process');,```,,## 进程事件,process 模块对象是 EventEmitter 的实例,可以通过注册事件监听器响应进程级别的事件。,,### beforeExit 事件,**当 fibjs 的任务已经为空,并且没有额外的工作被添加进来,事件 `beforeExit` 会被触发**,```JavaScript,process.on('beforeExit', exitCode => {});,```,正常情况下,如果没有额外的工作被添加到任务队列,fibjs 进程会结束。但是如果 `beforeExit` 事件绑定的监听器的回调函数中,启动了一个新的任务,比如开启一个 fiber,那么 fibjs 进程会继续运行。,,process.exitCode 作为唯一的参数值传递给 `beforeExit` 事件监听器的回调函数。如果进程由于显式的原因而将要终止,例如直接调用 process.exit 或抛出未捕获的异常,`beforeExit`事件不会被触发。,,### exit 事件,**当 fibjs 退出时,事件 `exit` 会被触发,一旦所有与 `exit` 事件绑定的监听器执行完成,进程会终止**,```JavaScript,process.on('exit', exitCode => {});,```,`exit` 事件监听器的回调函数,只有一个入参,这个参数的值可以是 process.exitCode 的属性值,或者是调用 process.exit 方法时传入的 `exitCode` 值。,,### Signal 事件,**当 fibjs 进程接收到一个信号时,会触发信号事件,目前支持的信号有 SIGINT 和 SIGTERM。每个事件名称,以信号名称的大写表示 (比如事件'SIGINT' 对应信号 SIGINT)。**,,信号事件不同于其它进程事件,信号事件是抢占的,当信号发生时,无论当前在 io 操作,还是 JavaScript 运算,都会尽快触发相应事件。比如你可以用下面的代码,中断当前应用,并输出运行状态:,```JavaScript,var coroutine = require('coroutine');,,process.on('SIGINT', () => {, coroutine.fibers.forEach(f => console.error("Fiber %d:\n%s", f.id, f.stack));, process.exit();,});,```,信号名称及其意义如下:,* SIGINT:在终端运行时,可以被所有平台支持,通常可以通过 CTRL+C 触发。,* SIGTERM:当进程被 kill 时触发此信号。Windows 下不支持。 + */ +declare module "process" { + + + module process { + + + + + + /** + * + * @brief 改变当前的 umask,Windows 不支持此方法 + * @param mask 指定新的掩码 + * @return 返回之前的 mask + * + * + * + */ + export function umask(mask: number): number; + + /** + * + * @brief 改变当前的 umask,Windows 不支持此方法 + * @param mask 指定新的掩码, 字符串类型八进制(e.g: "0664") + * @return 返回之前的 mask + * + * + * + */ + export function umask(mask: string): number; + + /** + * + * @brief 返回当前的 umask,Windows 不支持此方法 + * @return 返回当前的 mask 值 + * + * + * + */ + export function umask(): number; + + /** + * + * @brief 返回系统高精度时间,此时间与当前时间无关,仅用于高精度计时 + * @param diff 用于比较的初始时间 + * @return 返回计时时间,格式为 [seconds, nanoseconds] + * + * + * + */ + export function hrtime(diff?: any[]/** = v8::Array::New(isolate)*/): any[]; + + /** + * + * @brief 退出当前进程,并返回 exitCode 作为进程结果 + * + * + */ + export function exit(): void; + + /** + * + * @brief 退出当前进程,并返回结果 + * @param code 返回进程结果 + * + * + * + */ + export function exit(code: number): void; + + /** + * + * @brief 返回操作系统当前工作路径 + * @return 返回当前系统路径 + * + * + * + */ + export function cwd(): string; + + /** + * + * @brief 修改操作系统当前工作路径 + * @param directory 指定设定的新路径 + * + * + * + */ + export function chdir(directory: string): void; + + /** + * + * @brief 查询运行环境运行时间,以秒为单位 + * @return 返回表示时间的数值 + * + * + * + */ + export function uptime(): number; + + /** + * + * @brief 查询当前进程内存使用报告 + * + * 内存报告生成类似以下结果: + * ```JavaScript + * { + * "rss": 8622080, + * "heapTotal": 4083456, + * "heapUsed": 1621800 + * } + * ``` + * 其中: + * - rss 返回进程当前占用物理内存大小 + * - heapTotal 返回 v8 引擎堆内存大小 + * - heapUsed 返回 v8 引擎正在使用堆内存大小 + * @return 返回包含内存报告 + * + * + * + */ + export function memoryUsage(): Object; + + /** + * + * @brief 启动一个纤程 + * @param func 制定纤程执行的函数 + * @param args 可变参数序列,此序列会在纤程内传递给函数 + * + * + * + */ + export function nextTick(func: Function, ...args: any[]): void; + + /** + * + * @brief 运行指定的命令行,接管进程输入输出流,并返回进程对象 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param args 指定运行的参数列表 + * @param opts 指定运行的选项 + * @return 返回包含运行结果的进程对象 + * + * + * + */ + export function open(command: string, args: any[], opts?: Object/** = v8::Object::New(isolate)*/): Class_SubProcess; + + /** + * + * @brief 运行指定的命令行,接管进程输入输出流,并返回进程对象 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param opts 指定运行的选项 + * @return 返回包含运行结果的进程对象 + * + * + * + */ + export function open(command: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_SubProcess; + + /** + * + * @brief 运行指定的命令行,并返回进程对象 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param args 指定运行的参数列表 + * @param opts 指定运行的选项 + * @return 返回包含运行结果的进程对象 + * + * + * + */ + export function start(command: string, args: any[], opts?: Object/** = v8::Object::New(isolate)*/): Class_SubProcess; + + /** + * + * @brief 运行指定的命令行,并返回进程对象 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param opts 指定运行的选项 + * @return 返回包含运行结果的进程对象 + * + * + * + */ + export function start(command: string, opts?: Object/** = v8::Object::New(isolate)*/): Class_SubProcess; + + /** + * + * @brief 运行指定的命令行,并返回进程的结束代码 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param args 指定运行的参数列表 + * @param opts 指定运行的选项 + * @return 返回命令的运行结果 + * + * + * + */ + export function run(command: string, args: any[], opts?: Object/** = v8::Object::New(isolate)*/): number; + + /** + * + * @brief 运行指定的命令行,并返回进程的结束代码 + * + * opts 支持的选项如下: + * ```JavaScript + * { + * "timeout": 100, // 单位为 ms + * "envs": [] // 进程环境变量 + * } + * ``` + * @param command 指定运行的命令行 + * @param opts 指定运行的选项 + * @return 返回命令的运行结果 + * + * + * + */ + export function run(command: string, opts?: Object/** = v8::Object::New(isolate)*/): number; + + } /** end of `module process` */ + export = process +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/profiler.d.ts b/types/fibjs/declare/profiler.d.ts new file mode 100644 index 0000000000..e6f7345927 --- /dev/null +++ b/types/fibjs/declare/profiler.d.ts @@ -0,0 +1,440 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 内存 profiler 模块 + * @detail 使用方法:,```JavaScript,var profiler = require('profiler');,``` + */ +declare module "profiler" { + + + module profiler { + + /** + * + * @brief 隐藏节点,当显示给用户时可以被过滤掉 + * + * + */ + export const Node_Hidden = 0; + + /** + * + * @brief 数组 + * + * + */ + export const Node_Array = 1; + + /** + * + * @brief 字符串 + * + * + */ + export const Node_String = 2; + + /** + * + * @brief JS对象(字符串和数组除外) + * + * + */ + export const Node_Object = 3; + + /** + * + * @brief 编译后的代码 + * + * + */ + export const Node_Code = 4; + + /** + * + * @brief 函数闭包 + * + * + */ + export const Node_Closure = 5; + + /** + * + * @brief 正则表达式 + * + * + */ + export const Node_RegExp = 6; + + /** + * + * @brief 堆中排好序的数字 + * + * + */ + export const Node_HeapNumber = 7; + + /** + * + * @brief Native对象(非v8堆上的) + * + * + */ + export const Node_Native = 8; + + /** + * + * @brief Synthetic对象 + * + * + */ + export const Node_Synthetic = 9; + + /** + * + * @brief 拼接的字符串 + * + * + */ + export const Node_ConsString = 10; + + /** + * + * @brief 分割的字符串 + * + * + */ + export const Node_SlicedString = 11; + + /** + * + * @brief 符号(ES6) + * + * + */ + export const Node_Symbol = 12; + + /** + * + * @brief 堆中排好序的SIMD值(ES7) + * + * + */ + export const Node_SimdValue = 13; + + /** + * + * @brief 函数中的变量 + * + * + */ + export const Edge_ContextVariable = 0; + + /** + * + * @brief 数组中的元素 + * + * + */ + export const Edge_Element = 1; + + /** + * + * @brief 有名对象的属性 + * + * + */ + export const Edge_Property = 2; + + /** + * + * @brief JS无法进入的链接 + * + * + */ + export const Edge_Internal = 3; + + /** + * + * @brief 指向需要事先计算出空间大小的节点 + * + * + */ + export const Edge_Hidden = 4; + + /** + * + * @brief 指向无法事先计算出空间大小的节点 + * + * + */ + export const Edge_Shortcut = 5; + + /** + * + * @brief 一个弱引用(被GC忽视) + * + * + */ + export const Edge_Weak = 6; + + + + + + /** + * + * @brief 根据指定名称保存一个堆快照 + * @param fname 堆快照名称 + * + * + * + */ + export function saveSnapshot(fname: string): void; + + /** + * + * @brief 根据指定名称读取一个堆快照 + * @param fname 堆快照名称 + * @return 返回读取到的堆快照 + * + * + * + */ + export function loadSnapshot(fname: string): Class_HeapSnapshot; + + /** + * + * @brief 获取当前时间节点的堆快照,堆快照记录了当前时刻JS堆的状态 + * @return 返回获取到的堆信息快照 + * + * + * + */ + export function takeSnapshot(): Class_HeapSnapshot; + + /** + * + * @brief 执行给定的函数,并对比执行前后 v8 堆的变化 + * @param test 给定要测试的函数 + * @return 返回对比的结果 + * + * + * + */ + export function diff(test: Function): Object; + + /** + * + * @brief 启动一次运行状态采样日志 + * @param fname 给定日志存储文件名 + * @param time 指定采样时间,缺省 1 分钟 + * @param interval 指定间隔时间,缺省 100 毫秒 + * @return 返回采样定时器,可以通过 clear 方法提前停止采样 + * + * + * + */ + export function start(fname: string, time?: number/** = 60000*/, interval?: number/** = 100*/): Class_Timer; + + } /** end of `module profiler` */ + export = profiler +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/punycode.d.ts b/types/fibjs/declare/punycode.d.ts new file mode 100644 index 0000000000..c33938dd48 --- /dev/null +++ b/types/fibjs/declare/punycode.d.ts @@ -0,0 +1,261 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief punycode 国际化域名转换模块 + * @detail Punycode 是由 RFC 3492 定义的主要用于国际化域名的字符编码方案。因为 URL 中主机名限制只能是 ASCII 字符,包括非 ASCII 字符的主机名必须使用 punycode 算法转化为ASCII。,,使用方法:,```JavaScript,var punycode = require('punycode');,``` + */ +declare module "punycode" { + + + module punycode { + + + + + + /** + * + * @brief 将一个 Unicode 字符串转化为等价的只含有 ASCII 字符的 Punycode 字符串 + * @param domain 给定Unicode 字符串 + * @return 返回编码后的只含有 ASCII 字符的 Punycode 字符串 + * + * + * + */ + export function encode(domain: string): string; + + /** + * + * @brief 将一个 Punycode 字符串转化为等价的 Unicode 字符串 + * @param domain 给定Unicode 字符串 + * @return 返回解码后的 Unicode 字符串 + * + * + * + */ + export function decode(domain: string): string; + + /** + * + * @brief 转换一个代表了一个域名的Unicode字符串为一个只含有 ASCII 字符的字符串。只有代表了域名的部分的非 ASCII 字符串会被转换。也就是说,如果你调用了一个已经被转换为ASCII的字符串,也是没有问题的。 + * @param domain 给定Unicode 字符串 + * @return 返回编码后的 ASCII 字符串 + * + * + * + */ + export function toASCII(domain: string): string; + + /** + * + * @brief 转换一个代表了一个域名的Punycode字符串为一个Unicode字符串。只有代表了域名的部分的Punycode字符串会被转换。也就是说,如果你调用了一个已经被转换为Unicode的字符串,也是没有问题的。 + * @param domain 给定 ASCII 字符串 + * @return 返回解码后的 Unicode 字符串 + * + * + * + */ + export function toUnicode(domain: string): string; + + } /** end of `module punycode` */ + export = punycode +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/querystring.d.ts b/types/fibjs/declare/querystring.d.ts new file mode 100644 index 0000000000..c2a9e0284f --- /dev/null +++ b/types/fibjs/declare/querystring.d.ts @@ -0,0 +1,267 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief http query 处理模块 + * @detail 引用方法:,```JavaScript,var querystring = require('querystring');,``` + */ +declare module "querystring" { + + + module querystring { + + + + + + /** + * + * @brief url 部件字符串安全编码 + * @param str 要编码的 url + * @return 返回编码的字符串 + * + * + * + */ + export function escape(str: string): string; + + /** + * + * @brief url 安全字符串解码 + * @param str 要解码的 url + * @return 返回解码的字符串 + * + * + * + */ + export function unescape(str: string): string; + + /** + * + * @brief 解析 query 字符串 + * @param str 要解析的字符串 + * @param sep 解析时使用的分割字符串,缺省为 & + * @param eq 解析时使用的赋值字符串,缺省为 = + * @param opt 解析参数,暂未支持 + * @return 返回解码的对象 + * + * + * + */ + export function parse(str: string, sep?: string/** = "&"*/, eq?: string/** = "="*/, opt?: Object/** = v8::Object::New(isolate)*/): Class_HttpCollection; + + /** + * + * @brief 序列化一个对象为 query 字符串 + * @param obj 要序列化的对象 + * @param sep 序列化时使用的分割字符串,缺省为 & + * @param eq 序列化时使用的赋值字符串,缺省为 = + * @param opt 解析参数,暂未支持 + * @return 返回序列化后的字符串 + * + * + * + */ + export function stringify(obj: Object, sep?: string/** = "&"*/, eq?: string/** = "="*/, opt?: Object/** = v8::Object::New(isolate)*/): string; + + } /** end of `module querystring` */ + export = querystring +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/registry.d.ts b/types/fibjs/declare/registry.d.ts new file mode 100644 index 0000000000..99e9cf7bb7 --- /dev/null +++ b/types/fibjs/declare/registry.d.ts @@ -0,0 +1,386 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief Windows 注册表访问模块 + * @detail 引用方式:,```JavaScript,var registry = require('registry');,var value = registry.get(registry.CLASSES_ROOT, "\node1\node2\value");,``` + */ +declare module "registry" { + + + module registry { + + /** + * + * @brief 注册表根,存储Windows可识别的文件类型的详细列表,以及相关联的程序 + * + * + */ + export const CLASSES_ROOT = 0; + + /** + * + * @brief 注册表根,存储当前用户设置的信息 + * + * + */ + export const CURRENT_USER = 1; + + /** + * + * @brief 注册表根,包括安装在计算机上的硬件和软件的信息 + * + * + */ + export const LOCAL_MACHINE = 2; + + /** + * + * @brief 注册表根,包含使用计算机的用户的信息 + * + * + */ + export const USERS = 3; + + /** + * + * @brief 注册表根,这个分支包含计算机当前的硬件配置信息 + * + * + */ + export const CURRENT_CONFIG = 5; + + /** + * + * @brief 注册表数据类型,字符串 + * + * + */ + export const SZ = 1; + + /** + * + * @brief 注册表数据类型,扩展字符串 + * + * + */ + export const EXPAND_SZ = 2; + + /** + * + * @brief 注册表数据类型,32 位数值 + * + * + */ + export const DWORD = 4; + + /** + * + * @brief 注册表数据类型,64 位数值 + * + * + */ + export const QWORD = 11; + + + + + + /** + * + * @brief 返回指定键值下的所有子健 + * @param root 指定注册表根 + * @param key 指定键值 + * @return 返回该键值下所有子健 + * + * + * + */ + export function listSubKey(root: number, key: string): any[]; + + /** + * + * @brief 返回指定键值下的所有数据的健 + * @param root 指定注册表根 + * @param key 指定键值 + * @return 返回该键值下所有数据的健 + * + * + * + */ + export function listValue(root: number, key: string): any[]; + + /** + * + * @brief 查询指定键值的数值 + * @param root 指定注册表根 + * @param key 指定键值 + * @return 返回指定键值的数值 + * + * + * + */ + export function get(root: number, key: string): any; + + /** + * + * @brief 设置指定键值为数字 + * @param root 指定注册表根 + * @param key 指定键值 + * @param value 指定数字 + * @param type 指定类型,允许的类型为 DWORD 和 QWORD,缺省为 DWORD + * + * + * + */ + export function set(root: number, key: string, value: number, type?: number/** = undefined*/): void; + + /** + * + * @brief 设置指定键值为字符串 + * @param root 指定注册表根 + * @param key 指定键值 + * @param value 指定字符串 + * @param type 指定类型,允许的类型为 SZ 和 EXPAND_SZ,缺省为 SZ + * + * + * + */ + export function set(root: number, key: string, value: string, type?: number/** = undefined*/): void; + + /** + * + * @brief 设置指定键值为多字符串 + * @param root 指定注册表根 + * @param key 指定键值 + * @param value 指定多字符串数组 + * + * + * + */ + export function set(root: number, key: string, value: any[]): void; + + /** + * + * @brief 设置指定键值为二进制 + * @param root 指定注册表根 + * @param key 指定键值 + * @param value 指定二进制数据 + * + * + * + */ + export function set(root: number, key: string, value: Class_Buffer): void; + + /** + * + * @brief 删除指定键值的数值 + * @param root 指定注册表根 + * @param key 指定键值 + * + * + * + */ + export function del(root: number, key: string): void; + + } /** end of `module registry` */ + export = registry +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/ssl.d.ts b/types/fibjs/declare/ssl.d.ts new file mode 100644 index 0000000000..befed4f19a --- /dev/null +++ b/types/fibjs/declare/ssl.d.ts @@ -0,0 +1,376 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief ssl/tls 模块 + * @detail + */ +declare module "ssl" { + + + module ssl { + + /** + * + * @brief 证书验证模式,不验证 + * + * + */ + export const VERIFY_NONE = 0; + + /** + * + * @brief 证书验证模式,可选验证,允许验证不通过 + * + * + */ + export const VERIFY_OPTIONAL = 1; + + /** + * + * @brief 证书验证模式,要求验证,验证不通过则中断 + * + * + */ + export const VERIFY_REQUIRED = 2; + + /** + * + * @brief 证书验证结果,证书超时 + * + * + */ + export const BADCERT_EXPIRED = 1; + + /** + * + * @brief 证书验证结果,证书被撤销 + * + * + */ + export const BADCERT_REVOKED = 2; + + /** + * + * @brief 证书验证结果,证书名错误 + * + * + */ + export const BADCERT_CN_MISMATCH = 4; + + /** + * + * @brief 证书验证结果,证书不可信 + * + * + */ + export const BADCERT_NOT_TRUSTED = 8; + + /** + * + * @brief ssl 协议版本 ssl 3.0 + * + * + */ + export const ssl3 = 0; + + /** + * + * @brief ssl 协议版本 tls 1.0 + * + * + */ + export const tls1 = 1; + + /** + * + * @brief ssl 协议版本 tls 1.1 + * + * + */ + export const tls1_1 = 2; + + /** + * + * @brief ssl 协议版本 tls 1.2 + * + * + */ + export const tls1_2 = 3; + + + + /** + * + * @brief 创建一个 SslSocket 对象,参见 SslSocket + * + * + */ + export class SslSocket extends Class_SslSocket {} + + + /** + * + * @brief 创建一个 SslHandler 对象,参见 SslHandler + * + * + */ + export class SslHandler extends Class_SslHandler {} + + + /** + * + * @brief 创建一个 SslServer 对象,参见 SslServer + * + * + */ + export class SslServer extends Class_SslServer {} + + + + + /** + * + * @brief 创建一个 SslSocket 对象并建立连接 + * @param url 指定连接的协议,可以是:ssl://host:port + * @param timeout 指定超时时间,单位是毫秒,默认为0 + * @return 返回连接成功的 SslSocket 对象 + * + * + * @async + */ + export function connect(url: string, timeout?: number/** = 0*/): Class_Stream; + + /** + * + * @brief 设定缺省客户端证书 + * @param crt X509Cert 证书,用于客户端验证服务器 + * @param key PKey 私钥,用于与客户端会话 + * + * + * + */ + export function setClientCert(crt: Class_X509Cert, key: Class_PKey): void; + + /** + * + * @brief 从文件中加载缺省客户端证书 + * @param crtFile X509Cert 证书文件,用于客户端验证服务器 + * @param keyFile PKey 私钥文件,用于与客户端会话 + * @param password 解密密码 + * + * + * + */ + export function loadClientCertFile(crtFile: string, keyFile: string, password?: string/** = ""*/): void; + + /** + * + * @brief 加载自带的缺省根证书,等同于 ssl.ca.loadRootCerts + * 此证书内容源自:http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt + * + * + */ + export function loadRootCerts(): void; + + } /** end of `module ssl` */ + export = ssl +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/string_decoder.d.ts b/types/fibjs/declare/string_decoder.d.ts new file mode 100644 index 0000000000..233ab0c76e --- /dev/null +++ b/types/fibjs/declare/string_decoder.d.ts @@ -0,0 +1,226 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 解码 Buffer 到字符串 + * @detail 使用方法:,```JavaScript, const { StringDecoder } = require('string_decoder');, const decoder = new StringDecoder('utf8');,, const cent = Buffer.from([0xC2, 0xA2]);, console.log(decoder.write(cent));,, const euro = Buffer.from([0xE2, 0x82, 0xAC]);, console.log(decoder.write(euro));,``` + */ +declare module "string_decoder" { + + + module string_decoder { + + + + /** + * + * @brief 创建一个解码对象,参见 StringDecoder + * + * + */ + export class StringDecoder extends Class_StringDecoder {} + + + + + } /** end of `module string_decoder` */ + export = string_decoder +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/test.d.ts b/types/fibjs/declare/test.d.ts new file mode 100644 index 0000000000..5c4b539a14 --- /dev/null +++ b/types/fibjs/declare/test.d.ts @@ -0,0 +1,357 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 测试套件模块,用以定义管理测试套件 + * @detail 使用方法 :,,```JavaScript,var test = require('test');,test.setup();,,describe('test', () => {, before(() => {, // setup before the whole test, });,, beforeEach(() => {, // setup before each test, });,, after(() => {, // cleanup after the whole test, });,, afterEach(() => {, // cleanup after each test, });,, it('case', () => {, assert.ok(true);, });,, // ignored test case, xit('case', () => {, assert.ok(true);, });,, // ignored test case, it.skip('case', () => {, assert.ok(true);, });,, // only test case, oit('case', () => {, assert.ok(true);, });,, // only test case, it.only('case', () => {, assert.ok(true);, });,});,,// async function test,describe('test async', () => {,it('pass case', async() => {, assert.ok(true);,});,,it('error case', async() => {, throw new Error('some thing wrong!');,});,});,,// callback function test,// cannot use callback mode in jsc,describe('test callback', () => {,it('pass case', done => {, setTimeout(() => {, assert.ok(true);, done();, }, 0);,});,,it('error case', done => {, setTimeout(() => {, done(new Error('some thing wrong!'));, }, 0);,});,});,,process.exit(-test.run(console.DEBUG));,``` + */ +declare module "test" { + + import consoleNS = require('console') + import assertNS = require('assert') + + module test { + + + + /** + * + * @brief 断言测试模块,如果测试值为假,则报错,报错行为可设定继续运行或者错误抛出 + * + * + */ + + export const assert: typeof assertNS + + + + /** + * + * @brief 定义一个测试模块,可嵌套定义 + * @param name 定义模块名称 + * @param block 模块初始化代码 + * + * + * + */ + export function describe(name: string, block: Function): void; + + /** + * + * @brief 暂停测试的模块定义,test.setup 后可使用 describe.skip 调用 + * @param name 定义模块名称 + * @param block 模块初始化代码 + * + * + * + */ + export function xdescribe(name: string, block: Function): void; + + /** + * + * @brief 独立测试的模块定义,test.setup 后可使用 describe.only 调用 + * @param name 定义模块名称 + * @param block 模块初始化代码 + * + * + * + */ + export function odescribe(name: string, block: Function): void; + + /** + * + * @brief 定义一个测试项目 + * @param name 定义项目名称 + * @param block 测试内容 + * + * + * + */ + export function it(name: string, block: Function): void; + + /** + * + * @brief 暂停测试的项目定义,test.setup 后可使用 it.skip 调用 + * @param name 定义项目名称 + * @param block 测试内容 + * + * + * + */ + export function xit(name: string, block: Function): void; + + /** + * + * @brief 独立测试的项目定义,test.setup 后可使用 it.only 调用 + * @param name 定义项目名称 + * @param block 测试内容 + * + * + * + */ + export function oit(name: string, block: Function): void; + + /** + * + * @brief 定义当前测试模块进入事件 + * @param func 事件函数 + * + * + * + */ + export function before(func: Function): void; + + /** + * + * @brief 定义当前测试模块退出事件 + * @param func 事件函数 + * + * + * + */ + export function after(func: Function): void; + + /** + * + * @brief 定义当前测试模块测试项目进入事件 + * @param func 事件函数 + * + * + * + */ + export function beforeEach(func: Function): void; + + /** + * + * @brief 定义当前测试模块测试项目退出事件 + * @param func 事件函数 + * + * + * + */ + export function afterEach(func: Function): void; + + /** + * + * @brief 开始执行定义的测试模块 + * @param loglevel 指定进行测试时的日志输出级别,ERROR 时,项目报错信息集中在报告后显示,低于 ERROR 时,输出信息随时显示,高于 ERROR 时,只显示报告 + * @return 返回测试用例统计结果,正确则返回 0,错误则返回错误个数 + * + * + * + */ + export function run(loglevel?: number/** = undefined*/): number; + + /** + * + * @brief 初始化当前脚本的测试环境,将 test 模块方法复制为当前脚本全局变量 + * + * + */ + export function setup(): void; + + } /** end of `module test` */ + export = test +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/timers.d.ts b/types/fibjs/declare/timers.d.ts new file mode 100644 index 0000000000..158dcc8f84 --- /dev/null +++ b/types/fibjs/declare/timers.d.ts @@ -0,0 +1,322 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief timers 模块 + * @detail + */ +declare module "timers" { + + + module timers { + + + + + + /** + * + * @brief 在指定的时间后调用函数 + * @param callback 指定回调函数 + * @param timeout 指定延时的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setTimeout(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearTimeout(t: any): void; + + /** + * + * @brief 每间隔指定的时间后调用函数 + * @param callback 指定回调函数 + * @param timeout 指定间隔的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setInterval(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearInterval(t: any): void; + + /** + * + * @brief 每间隔指定的时间后调用函数,这是个高精度定时器,会主动打断正在运行的 JavaScript 脚本执行定时器 + * 由于 setHrInterval 的定时器会中断正在运行的代码执行回调,因此不要在回调函数内修改可能影响其它模块的数据,或者在回调中调用任何标记为 async 的 api 函数,否则将会产生不可预知的结果。例如: + * ```JavaScript + * var timers = require('timers'); + * + * var cnt = 0; + * timers.setHrInterval(() => { + * cnt++; + * }, 100); + * + * while (cnt < 10); + * + * console.error("===============================> done"); + * ``` + * 这段代码中,第 8 行的循环并不会因为 cnt 的改变而结束,因为 JavaScript 在优化代码时会认定在这个循环过程中 cnt 不会被改变。 + * @param callback 指定回调函数 + * @param timeout 指定间隔的时间,以毫秒为单位。超过 2^31 的话,立即执行。 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setHrInterval(callback: Function, timeout: number, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearHrInterval(t: any): void; + + /** + * + * @brief 下一个空闲时间立即执行回调函数 + * @param callback 指定回调函数 + * @param args 额外的参数,传入到指定的 callback 内,可选。 + * @return 返回定时器对象 + * + * + * + */ + export function setImmediate(callback: Function, ...args: any[]): Class_Timer; + + /** + * + * @brief 清除指定的定时器 + * @param t 指定要清除的定时器 + * + * + * + */ + export function clearImmediate(t: any): void; + + } /** end of `module timers` */ + export = timers +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/tty.d.ts b/types/fibjs/declare/tty.d.ts new file mode 100644 index 0000000000..bb35dc9195 --- /dev/null +++ b/types/fibjs/declare/tty.d.ts @@ -0,0 +1,228 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief tty 模块 + * @detail 使用方法:,```JavaScript,const tty = require('tty');,``` + */ +declare module "tty" { + + + module tty { + + + + + + /** + * + * @brief 查询是否是命令交互窗口 + * @param fd 文件描述符 + * @return 如果文件描述符同一个终端窗口关联则返回 true ,否则返回 false + * + * + * + */ + export function isatty(fd: number): boolean; + + } /** end of `module tty` */ + export = tty +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/url.d.ts b/types/fibjs/declare/url.d.ts new file mode 100644 index 0000000000..5a2706abfd --- /dev/null +++ b/types/fibjs/declare/url.d.ts @@ -0,0 +1,241 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief url 处理模块 + * @detail + */ +declare module "url" { + + + module url { + + + + + + /** + * + * @brief 参数构造 UrlObject 对象 + * @param args 指定构造参数的字典对象,支持的字段有:protocol, slashes, username, password, hostname, port, pathname, query, hash + * @return 返回构造成功的字符串 + * + * + * + */ + export function format(args: Object): string; + + /** + * + * @brief 解析一个 url 字符串 + * @param url 指定需要解析的 url 字符串 + * @param parseQueryString 指定是否解析 query + * @param slashesDenoteHost 默认为false, 如果设置为true,则从字符串'//'之后到下一个'/'之前的字符串会被解析为host,例如'//foo/bar', 结果应该是{host: 'foo', pathname: '/bar'}而不是{pathname: '//foo/bar'} + * @return 返回包含解析数据的对象 + * + * + * + */ + export function parse(url: string, parseQueryString?: boolean/** = false*/, slashesDenoteHost?: boolean/** = false*/): Class_UrlObject; + + } /** end of `module url` */ + export = url +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/util.d.ts b/types/fibjs/declare/util.d.ts new file mode 100644 index 0000000000..e49ae9feae --- /dev/null +++ b/types/fibjs/declare/util.d.ts @@ -0,0 +1,974 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 常用工具模块 + * @detail + */ +declare module "util" { + + + module util { + + + + /** + * + * @brief 数据统计对象,用以构建应用运行时数据收集,参见 Stats 对象。 + * + * + */ + export class Stats extends Class_Stats {} + + + /** + * + * @brief LRU(least recently used) 缓存对象,参见 LruCache 对象。 + * + * + */ + export class LruCache extends Class_LruCache {} + + + + + /** + * + * @brief 按照指定的格式格式化变量 + * + * @param fmt 格式化字符串 + * @param args 可选参数列表 + * @return 返回格式化后的字符串 + * + * + * + */ + export function format(fmt: string, ...args: any[]): string; + + /** + * + * @brief 格式格式化变量 + * + * @param args 可选参数列表 + * @return 返回格式化后的字符串 + * + * + * + */ + export function format(...args: any[]): string; + + /** + * + * @brief 从一个构造函数 constructor 继承原型方法到另一个。构造函数的原型将被设置为一个新的从超类(superConstructor)创建的对象。 + * + * @param constructor 初始的构造函数 + * @param superConstructor 被继承的超类 + * + * + * + */ + export function inherits(constructor: any, superConstructor: any): void; + + /** + * + * @brief 方法返回 obj 的字符串表示,主要用于调试。 附加的 options 可用于改变格式化字符串的某些方面。 + * + * @param obj 指定需要处理的对象 + * @param options 指定格式控制选项 + * @return 返回格式化后的字符串 + * + * + * + */ + export function inspect(obj: Object, options?: Object/** = v8::Object::New(isolate)*/): string; + + /** + * + * @brief 检测给定的变量是否不包含任何值(没有可枚举的属性) + * + * @param v 给定需要检测的变量 + * @return 如果为空则返回 True + * + * + * + */ + export function isEmpty(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是数组 + * + * @param v 给定需要检测的变量 + * @return 如果是数组则返回 True + * + * + * + */ + export function isArray(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Boolean + * + * @param v 给定需要检测的变量 + * @return 如果是 Boolean 则返回 True + * + * + * + */ + export function isBoolean(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Null + * + * @param v 给定需要检测的变量 + * @return 如果是 Null 则返回 True + * + * + * + */ + export function isNull(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Null 或者 Undefined + * + * @param v 给定需要检测的变量 + * @return 如果是 Null 或者 Undefined 则返回 True + * + * + * + */ + export function isNullOrUndefined(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是数字 + * + * @param v 给定需要检测的变量 + * @return 如果是数字则返回 True + * + * + * + */ + export function isNumber(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是字符串 + * + * @param v 给定需要检测的变量 + * @return 如果是字符串则返回 True + * + * + * + */ + export function isString(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Undefined + * + * @param v 给定需要检测的变量 + * @return 如果是 Undefined 则返回 True + * + * + * + */ + export function isUndefined(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是正则对象 + * + * @param v 给定需要检测的变量 + * @return 如果是正则对象则返回 True + * + * + * + */ + export function isRegExp(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是对象 + * + * @param v 给定需要检测的变量 + * @return 如果是对象则返回 True + * + * + * + */ + export function isObject(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是日期对象 + * + * @param v 给定需要检测的变量 + * @return 如果是日期对象则返回 True + * + * + * + */ + export function isDate(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是错误对象 + * + * @param v 给定需要检测的变量 + * @return 如果是错误对象则返回 True + * + * + * + */ + export function isNativeError(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是原始类型 + * + * @param v 给定需要检测的变量 + * @return 如果是原始类型则返回 True + * + * + * + */ + export function isPrimitive(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是Symbol类型 + * + * @param v 给定需要检测的变量 + * @return 如果是Symbol类型则返回 True + * + * + * + */ + export function isSymbol(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 DataView 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 DataView 类型则返回 True + * + * + * + */ + export function isDataView(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 External 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 External 类型则返回 True + * + * + * + */ + export function isExternal(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Map 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 Map 类型则返回 True + * + * + * + */ + export function isMap(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 MapIterator 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 MapIterator 类型则返回 True + * + * + * + */ + export function isMapIterator(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Promise 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 Promise 类型则返回 True + * + * + * + */ + export function isPromise(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 AsyncFunction 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 AsyncFunction 类型则返回 True + * + * + * + */ + export function isAsyncFunction(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Set 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 Set 类型则返回 True + * + * + * + */ + export function isSet(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 SetIterator 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 SetIterator 类型则返回 True + * + * + * + */ + export function isSetIterator(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 TypedArray 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 TypedArray 类型则返回 True + * + * + * + */ + export function isTypedArray(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是 Uint8Array 类型 + * + * @param v 给定需要检测的变量 + * @return 如果是 Uint8Array 类型则返回 True + * + * + * + */ + export function isUint8Array(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是函数对象 + * + * @param v 给定需要检测的变量 + * @return 如果是函数对象则返回 True + * + * + * + */ + export function isFunction(v: any): boolean; + + /** + * + * @brief 检测给定的变量是否是函数 Buffer 对象 + * + * @param v 给定需要检测的变量 + * @return 如果是函数 Buffer 对象则返回 True + * + * + * + */ + export function isBuffer(v: any): boolean; + + /** + * + * @brief 查询指定对象是否包含给定的键 + * + * @param v 给定需要查询的对象 + * @param key 指定需要查询的键 + * @return 返回对象的全部键数组 + * + * + * + */ + export function has(v: any, key: string): boolean; + + /** + * + * @brief 查询指定对象的全部键数组 + * + * @param v 给定需要查询的对象 + * @return 返回对象的全部键数组 + * + * + * + */ + export function keys(v: any): any[]; + + /** + * + * @brief 查询指定对象的全部值数组 + * + * @param v 给定需要查询的对象 + * @return 返回对象的全部值数组 + * + * + * + */ + export function values(v: any): any[]; + + /** + * + * @brief 克隆给定变量,如果是对象或数组,则复制内容到新对象 + * + * @param v 给定要克隆的变量 + * @return 返回克隆结果 + * + * + * + */ + export function clone(v: any): any; + + /** + * + * @brief 将一个或者多个对象的键值扩展到指定对象 + * + * @param v 指定要扩展的对象 + * @param objs 指定一个或者多个用于扩展的对象 + * @return 返回扩展的结果 + * + * + * + */ + export function extend(v: any, ...objs: any[]): any; + + /** + * + * @brief 将一个或者多个对象的键值扩展到指定对象,是 extend 的别名 + * + * @param v 指定要扩展的对象 + * @param objs 指定一个或者多个用于扩展的对象 + * @return 返回扩展的结果 + * + * + * + */ + export function _extend(v: any, ...objs: any[]): any; + + /** + * + * @brief 返回一个object副本,只过滤出指定键的属性值 + * + * @param v 指定要过滤的对象 + * @param objs 指定一个或者多个用于选择的键 + * @return 返回过滤的结果 + * + * + * + */ + export function pick(v: any, ...objs: any[]): Object; + + /** + * + * @brief 返回一个object副本,只过排除指定键的属性值 + * + * @param v 指定要过滤的对象 + * @param keys 指定一个或者多个用于排除的键 + * @return 返回排除的结果 + * + * + * + */ + export function omit(v: any, ...keys: any[]): Object; + + /** + * + * @brief 获取数组的第一个元素 + * + * @param v 给定要获取的数组 + * @return 返回获取的元素 + * + * + * + */ + export function first(v: any): any; + + /** + * + * @brief 获取数组的开始多个元素 + * + * @param v 给定要获取的数组 + * @param n 指定要获取的元素个数 + * @return 返回获取的元素数组 + * + * + * + */ + export function first(v: any, n: number): any; + + /** + * + * @brief 获取数组的第后一个元素 + * + * @param v 给定要获取的数组 + * @return 返回获取的元素 + * + * + * + */ + export function last(v: any): any; + + /** + * + * @brief 获取数组的结尾多个元素 + * + * @param v 给定要获取的数组 + * @param n 指定要获取的元素个数 + * @return 返回获取的元素数组 + * + * + * + */ + export function last(v: any, n: number): any; + + /** + * + * @brief 获取数组的元素去重后的副本 + * + * @param v 给定要去重的数组 + * @param sorted 指定数组是否排序,如果指定数组排序,将使用快速算法 + * @return 返回去重元素后的数组 + * + * + * + */ + export function unique(v: any, sorted?: boolean/** = false*/): any[]; + + /** + * + * @brief 将一个或者多个数组的值合并成一个值唯一的数组 + * + * @param arrs 指定一个或者多个用于合并的数组 + * @return 返回合并的结果 + * + * + * + */ + export function union(...arrs: any[]): any[]; + + /** + * + * @brief 返回一个包含 arr 数组中排除一个或者多个数组元素的交集 + * + * @param arrs 指定一个或者多个用于计算交集的数组 + * @return 返回计算交集的结果 + * + * + * + */ + export function intersection(...arrs: any[]): any[]; + + /** + * + * @brief 将一个嵌套多层的数组(嵌套可以是任何层数)转换为只有一层的数组。 如果你传递 shallow 参数,数组将只减少一维的嵌套。 + * + * @param arr 指定需要转换的数组 + * @param shallow 指定是否只减少一维的嵌套,缺省为 false + * @return 返回转换的结果 + * + * + * + */ + export function flatten(arr: any, shallow?: boolean/** = false*/): any[]; + + /** + * + * @brief 返回一个包含 arr 数组中排除一个或者多个元素后的数组 + * + * @param arr 指定需要排除的数组 + * @param els 指定一个或者多个用于排除的元素 + * @return 返回排除的结果 + * + * + * + */ + export function without(arr: any, ...els: any[]): any[]; + + /** + * + * @brief 返回一个包含 arr 数组中排除 without 数组元素之后的数组 + * + * @param list 指定需要排除的数组 + * @param arrs 指定用于排除的一个或者多个数组 + * @return 返回排除的结果 + * + * + * + */ + export function difference(list: any[], ...arrs: any[]): any[]; + + /** + * + * @brief 遍历 list 中的所有元素,按顺序用遍历输出每个元素。如果传递了 context 参数,则把 iterator 绑定到 context 对象上。每次调用 iterator 都会传递三个参数:(element, index, list) + * + * @param list 指定需要遍历的列表或对象 + * @param iterator 指定用于遍历的回调函数 + * @param context 指定调用 iterator 时绑定的 context 对象 + * @return 返回 list 本身 + * + * + * + */ + export function each(list: any, iterator: Function, context?: any/** = v8::Undefined(isolate)*/): any; + + /** + * + * @brief 通过变换函数(iterator迭代器)把 list 中的每个值映射到一个新的数组中。如果传递了 context 参数,则把 iterator 绑定到 context 对象上。每次调用 iterator 都会传递三个参数:(element, index, list) + * + * @param list 指定需要变换的列表或对象 + * @param iterator 指定用于变换的回调函数 + * @param context 指定调用 iterator 时绑定的 context 对象 + * @return 返回变换的结果 + * + * + * + */ + export function map(list: any, iterator: Function, context?: any/** = v8::Undefined(isolate)*/): any[]; + + /** + * + * @brief 把 list中 元素归结为一个单独的数值。如果传递了 context 参数,则把 iterator 绑定到 context 对象上。每次调用 iterator 都会传递三个参数:(memo, element, index, list) + * + * @param list 指定需要归结的列表或对象 + * @param iterator 指定用于归结的回调函数 + * @param memo 指定归结的初始值 + * @param context 指定调用 iterator 时绑定的 context 对象 + * @return 返回归结的结果 + * + * + * + */ + export function reduce(list: any, iterator: Function, memo: any, context?: any/** = v8::Undefined(isolate)*/): any; + + /** + * + * @brief 编译脚本为二进制代码 + * util.compile 可以将脚本编译为 v8 内部运行数据块(非机器执行代码)。编译以后的代码,保存为 *.jsc 后,可以由 run 和 require 直接加载执行。 + * + * 由于编译之后,目标代码将不能逆向获取源代码,依赖于 Function.toString 的程序将不能正常运行。 + * + * @param srcname 指定要添加的脚本名称 + * @param script 指定要编译的脚本代码 + * @param mode 编译模式,0: module, 1: script, 2: worker,缺省为 0 + * @return 返回编译出的二进制代码 + * + * + * + */ + export function compile(srcname: string, script: string, mode?: number/** = 0*/): Class_Buffer; + + /** + * + * @brief 包裹 callback 或 async 方法为同步调用 + * + * util.sync 将 callback 方法或者 async 方法处理为 sync 方法,以方便调用。 + * + * callback 示例如下: + * ```JavaScript + * // callback + * var util = require('util'); + * + * function cb_test(a, b, cb) { + * setTimeout(() => { + * cb(null, a + b); + * }, 100); + * } + * + * var fn_sync = util.sync(cb_test); + * console.log(fn_sync(100, 200)); + * ``` + * async 示例如下: + * ```JavaScript + * // async/await + * var util = require('util'); + * + * async function async_test(a, b) { + * return a + b; + * } + * + * var fn_sync = util.sync(async_test); + * console.log(fn_sync(100, 200)); + * ``` + * 对于未标记为 async 的返回 promise 的函数,可以手动指定 sync 模式: + * ```JavaScript + * // async/await + * var util = require('util'); + * + * function async_test(a, b) { + * return new Promise(function (resolve, reject) { + * resolve(a + b); + * }); + * } + * + * var fn_sync = util.sync(async_test, true); + * console.log(fn_sync(100, 200)); + * ``` + * + * @param func 给定需要包裹的方法 + * @param async_func 指定以 async 函数方式处理 func,为 false 则自动判断 + * @return 返回同步运行的方法 + * + * + * + */ + export function sync(func: Function, async_func?: boolean/** = false*/): Function; + + /** + * + * @brief 查询当前引擎及各组件版本信息 + * + * ```JavaScript + * { + * "fibjs": "0.1.0", + * "svn": 1753, + * "build": "Dec 10 2013 21:44:17", + * "vender": { + * "ev": "4.11", + * "exif": "0.6.21", + * "gd": "2.1.0-alpha", + * "jpeg": "8.3", + * "log4cpp": "1.0", + * "mongo": "0.7", + * "pcre": "8.21", + * "png": "1.5.4", + * "sqlite": "3.8.1", + * "tiff": "3.9.5", + * "uuid": "1.6.2", + * "v8": "3.23.17 (candidate)", + * "zlib": "1.2.7", + * "zmq": "3.1" + * } + * } + * ``` + * @return 返回组件版本对象 + * + * + * + */ + export function buildInfo(): Object; + + } /** end of `module util` */ + export = util +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/uuid.d.ts b/types/fibjs/declare/uuid.d.ts new file mode 100644 index 0000000000..7300b8f875 --- /dev/null +++ b/types/fibjs/declare/uuid.d.ts @@ -0,0 +1,303 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief uuid 唯一 id 模块 + * @detail 基础模块。提供唯一 id 的创建于操作,```JavaScript,var uuid = require('uuid');,``` + */ +declare module "uuid" { + + + module uuid { + + /** + * + * @brief md5 与 sha1 创建 uuid 时指定 name 命名为域名 + * + * + */ + export const DNS = 0; + + /** + * + * @brief md5 与 sha1 创建 uuid 时指定 name 命名为 url 地址 + * + * + */ + export const URL = 1; + + /** + * + * @brief md5 与 sha1 创建 uuid 时指定 name 命名为 ISO OID + * + * + */ + export const OID = 2; + + /** + * + * @brief md5 与 sha1 创建 uuid 时指定 name 命名为 X.500 DN + * + * + */ + export const X509 = 3; + + + + + + /** + * + * @brief 使用时间和主机名创建 uuid + * @return 返回一个生成的二进制 id + * + * + * + */ + export function node(): Class_Buffer; + + /** + * + * @brief 使用特定命名的 md5 创建 uuid + * @param ns 指定命名空间,可以为 uuid.DNS, uuid.URL, uuid.OID, uuid.X509 + * @param name 指定名称 + * @return 返回一个生成的二进制 id + * + * + * + */ + export function md5(ns: number, name: string): Class_Buffer; + + /** + * + * @brief 使用随机数创建 uuid + * @return 返回一个生成的二进制 id + * + * + * + */ + export function random(): Class_Buffer; + + /** + * + * @brief 使用特定命名的 sha1 创建 uuid + * @param ns 指定命名空间,可以为 uuid.DNS, uuid.URL, uuid.OID, uuid.X509 + * @param name 指定名称 + * @return 返回一个生成的二进制 id + * + * + * + */ + export function sha1(ns: number, name: string): Class_Buffer; + + /** + * + * @brief 使用 Snowflake 算法创建 uuid + * @return 返回一个生成的二进制 id + * + * + * + */ + export function snowflake(): Class_Buffer; + + } /** end of `module uuid` */ + export = uuid +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/vm.d.ts b/types/fibjs/declare/vm.d.ts new file mode 100644 index 0000000000..b9615198d5 --- /dev/null +++ b/types/fibjs/declare/vm.d.ts @@ -0,0 +1,226 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief 安全沙箱模块,用于隔离不同安全等级的运行环境 + * @detail 通过建立安全沙箱,可以限制脚本运行时可以接触的资源,隔离不同脚本执行环境,并可以为不同的环境定制基础模块,以保障整体运行环境的安全。,,下面的示例创建一个沙箱,限制只允许访问全局基础模块中的 assert 模块,并添加 a 和 b 两个定制模块:,```JavaScript,var vm = require('vm');,var sbox = new vm.SandBox({, a: 100,, b: 200,, assert: require('assert'),});,,var mod_in_sbox = sbox.require('./path/to/mod');,``` + */ +declare module "vm" { + + + module vm { + + + + /** + * + * @brief 创建一个 SandBox 对象,参见 SandBox + * + * + */ + export class SandBox extends Class_SandBox {} + + + + + } /** end of `module vm` */ + export = vm +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/ws.d.ts b/types/fibjs/declare/ws.d.ts new file mode 100644 index 0000000000..d5402ad972 --- /dev/null +++ b/types/fibjs/declare/ws.d.ts @@ -0,0 +1,327 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief websocket 支持模块 + * @detail 使用方法:,```JavaScript,var ws = require('ws');,```,创建一个服务器:,```JavaScript,var ws = require('ws');,var http = require('http');,,var svr = new http.Server(80, {, '/ws': ws.upgrade((conn, req) => {, conn.onmessage = e => console.log(e.data);, }),});,svr.run();,```,使用 WebSocket 客户端:,```JavaScript,var ws = require('ws');,,var conn = new ws.Socket('ws://127.0.0.1/ws');,conn.ommessage = e => console.log(e.data);,``` + */ +declare module "ws" { + + + module ws { + + /** + * + * @brief 指定 websocket 消息类型 0,代表一个继续帧 + * + * + */ + export const CONTINUE = 0; + + /** + * + * @brief 指定 websocket 消息类型 1,代表一个文本帧 + * + * + */ + export const TEXT = 1; + + /** + * + * @brief 指定 websocket 消息类型 2,代表一个二进制帧 + * + * + */ + export const BINARY = 2; + + /** + * + * @brief 指定 websocket 消息类型 8,连接关闭 + * + * + */ + export const CLOSE = 8; + + /** + * + * @brief 指定 websocket 消息类型 9,代表一个 ping 帧 + * + * + */ + export const PING = 9; + + /** + * + * @brief 指定 websocket 消息类型 10,代表一个 pong 帧 + * + * + */ + export const PONG = 10; + + /** + * + * @brief 指定 WebSocket 状态,表示正在连接中 + * + * + */ + export const CONNECTING = 0; + + /** + * + * @brief 指定 WebSocket 状态,表示打开状态 + * + * + */ + export const OPEN = 1; + + /** + * + * @brief 指定 WebSocket 状态,表示已发送 CLOSE 消息,等待关闭中 + * + * + */ + export const CLOSING = 2; + + /** + * + * @brief 指定 WebSocket 状态,表示已经关闭 + * + * + */ + export const CLOSED = 3; + + + + /** + * + * @brief 创建一个 websocket 消息对象,参见 WebSocketMessage + * + * + */ + export class WebSocketMessage extends Class_WebSocketMessage {} + + + /** + * + * @brief WebSocket 对象,参见 WebSocket + * + * + */ + export class WebSocket extends Class_WebSocket {} + + + + + /** + * + * @brief 创建一个 websocket 协议处理器,从 http 接收 upgrade 请求并握手,生成 WebSocket 对象 + * accept 函数调用时,将传递两个参数,第一个参数为接收到的 WebSocket 对象,第二个参数为握手时的 HttpRequest 对象。 + * @param accept 连接成功处理函数 + * @return 返回协议处理器,可与 HttpServer, Chain, Routing 等对接 + * + * + * + */ + export function upgrade(accept: Function): Class_Handler; + + } /** end of `module ws` */ + export = ws +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/xml.d.ts b/types/fibjs/declare/xml.d.ts new file mode 100644 index 0000000000..4dbb477dc1 --- /dev/null +++ b/types/fibjs/declare/xml.d.ts @@ -0,0 +1,333 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief xml 处理模块 + * @detail + */ +declare module "xml" { + + + module xml { + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlElement 对象 + * + * + * + */ + export const ELEMENT_NODE = 1; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlAttr 对象 + * + * + * + */ + export const ATTRIBUTE_NODE = 2; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlText 对象 + * + * + * + */ + export const TEXT_NODE = 3; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlCDATASection 对象 + * + * + * + */ + export const CDATA_SECTION_NODE = 4; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlProcessingInstruction 对象 + * + * + * + */ + export const PROCESSING_INSTRUCTION_NODE = 7; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlComment 对象 + * + * + * + */ + export const COMMENT_NODE = 8; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlDocument 对象 + * + * + * + */ + export const DOCUMENT_NODE = 9; + + /** + * + * @brief XmlNode 的 nodeType 属性常量,表示节点为 XmlDocumentType 对象 + * + * + * + */ + export const DOCUMENT_TYPE_NODE = 10; + + + + /** + * + * @brief xml 文档对象,参见 XmlDocument 对象 + * + * + */ + export class XmlDocument extends Class_XmlDocument {} + + + + + /** + * + * @brief 解析 xml/html 文本,并创建 XmlDocument 对象,不支持多语种 + * @param source 指定需要解析的 xml/html 文本 + * @param type 指定文本类型,缺省为 text/xml,也可指定为 text/html + * @return 返回创建的 XmlDocument 对象 + * + * + * + */ + export function parse(source: string, type?: string/** = "text/xml"*/): Class_XmlDocument; + + /** + * + * @brief 解析 xml/html,并创建 XmlDocument 对象,解析时会根据指定的语种转换 + * @param source 指定需要解析的 xml/html 二进制数据 + * @param type 指定文本类型,缺省为 text/xml,也可指定为 text/html + * @return 返回创建的 XmlDocument 对象 + * + * + * + */ + export function parse(source: Class_Buffer, type?: string/** = "text/xml"*/): Class_XmlDocument; + + /** + * + * @brief 序列化 XmlNode 为字符串 + * @param node 指定需要序列化的 XmlNode + * @return 返回序列化的字符串 + * + * + * + */ + export function serialize(node: Class_XmlNode): string; + + } /** end of `module xml` */ + export = xml +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/zip.d.ts b/types/fibjs/declare/zip.d.ts new file mode 100644 index 0000000000..0aa19eaed4 --- /dev/null +++ b/types/fibjs/declare/zip.d.ts @@ -0,0 +1,283 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief zip 格式文件压缩解压模块 + * @detail 使用方法:,```JavaScript,var zip = require('zip');,``` + */ +declare module "zip" { + + + module zip { + + /** + * + * @brief 压缩类型常量, 不压缩, 仅存储 + * + * + */ + export const ZIP_STORED = 0; + + /** + * + * @brief 压缩类型常量, 需要依赖zlib库进行压缩 + * + * + */ + export const ZIP_DEFLATED = 1; + + + + + + /** + * + * @brief 判断文件是否是zip格式 + * @param filename 文件名 + * @return 返回true代表文件是zip文件 + * + * + * @async + */ + export function isZipFile(filename: string): boolean; + + /** + * + * @brief 打开一个zip文件 + * @param path 文件路径 + * @param mod 打开文件模式, "r"代表读取, "w"代表创建, "a"代表在zip文件后追加 + * @param compress_type 压缩类型, ZIP_STORED 代表不压缩, 仅存储。 默认使用ZIP_DEFLATED 代表使用zlib库进行压缩。 + * @return 返回zip文件对象 + * + * + * @async + */ + export function open(path: string, mod?: string/** = "r"*/, compress_type?: number/** = undefined*/): Class_ZipFile; + + /** + * + * @brief 打开一个zip文件 + * @param data zip文件数据 + * @param mod 打开文件模式, "r"代表读取, "w"代表创建, "a"代表在zip文件后追加 + * @param compress_type 压缩类型, ZIP_STORED 代表不压缩, 仅存储。 默认使用ZIP_DEFLATED 代表使用zlib库进行压缩。 + * @return 返回zip文件对象 + * + * + * @async + */ + export function open(data: Class_Buffer, mod?: string/** = "r"*/, compress_type?: number/** = undefined*/): Class_ZipFile; + + /** + * + * @brief 打开一个zip文件 + * @param strm zip文件流 + * @param mod 打开文件模式, "r"代表读取, "w"代表创建, "a"代表在zip文件后追加 + * @param compress_type 压缩类型, ZIP_STORED 代表不压缩, 仅存储。 默认使用ZIP_DEFLATED 代表使用zlib库进行压缩。 + * @return 返回zip文件对象 + * + * + * @async + */ + export function open(strm: Class_SeekableStream, mod?: string/** = "r"*/, compress_type?: number/** = undefined*/): Class_ZipFile; + + } /** end of `module zip` */ + export = zip +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/zlib.d.ts b/types/fibjs/declare/zlib.d.ts new file mode 100644 index 0000000000..42e7236f5e --- /dev/null +++ b/types/fibjs/declare/zlib.d.ts @@ -0,0 +1,513 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief zlib 压缩解压模块 + * @detail 使用方法:,```JavaScript,var zlib = require('zlib');,``` + */ +declare module "zlib" { + + + module zlib { + + /** + * + * @brief deflate 压缩级别,设定不压缩 + * + * + */ + export const NO_COMPRESSION = 0; + + /** + * + * @brief deflate 压缩级别,设定最快压缩 + * + * + */ + export const BEST_SPEED = 1; + + /** + * + * @brief deflate 压缩级别,设定最高压缩 + * + * + */ + export const BEST_COMPRESSION = 9; + + /** + * + * @brief deflate 压缩级别,设定缺省设置 + * + * + */ + export const DEFAULT_COMPRESSION = -1; + + + + + + /** + * + * @brief 创建一个 deflate 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createDeflate(to: Class_Stream): Class_Stream; + + /** + * + * @brief 创建一个 deflateRaw 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createDeflateRaw(to: Class_Stream): Class_Stream; + + /** + * + * @brief 创建一个 gunzip 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createGunzip(to: Class_Stream): Class_Stream; + + /** + * + * @brief 创建一个 gzip 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createGzip(to: Class_Stream): Class_Stream; + + /** + * + * @brief 创建一个 inflate 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createInflate(to: Class_Stream): Class_Stream; + + /** + * + * @brief 创建一个 inflateRaw 流对象 + * @param to 用于存储处理结果的流 + * @return 返回封装过的流对象 + * + * + */ + export function createInflateRaw(to: Class_Stream): Class_Stream; + + /** + * + * @brief 使用 deflate 算法压缩数据(zlib格式) + * @param data 给定要压缩的数据 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * @return 返回压缩后的二进制数据 + * + * + * @async + */ + export function deflate(data: Class_Buffer, level?: number/** = undefined*/): Class_Buffer; + + /** + * + * @brief 使用 deflate 算法压缩数据到流对象中(zlib格式) + * @param data 给定要压缩的数据 + * @param stm 指定存储压缩数据的流 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * + * + * @async + */ + export function deflateTo(data: Class_Buffer, stm: Class_Stream, level?: number/** = undefined*/): void; + + /** + * + * @brief 使用 deflate 算法压缩源流中的数据到流对象中(zlib格式) + * @param src 给定要压缩的数据所在的流 + * @param stm 指定存储压缩数据的流 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * + * + * @async + */ + export function deflateTo(src: Class_Stream, stm: Class_Stream, level?: number/** = undefined*/): void; + + /** + * + * @brief 解压缩 deflate 算法压缩的数据(zlib格式) + * @param data 给定压缩后的数据 + * @return 返回解压缩后的二进制数据 + * + * + * @async + */ + export function inflate(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 解压缩 deflate 算法压缩的数据到流对象中(zlib格式) + * @param data 给定要解压缩的数据 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function inflateTo(data: Class_Buffer, stm: Class_Stream): void; + + /** + * + * @brief 解压缩源流中 deflate 算法压缩的数据到流对象中(zlib格式) + * @param src 给定要解压缩的数据所在的流 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function inflateTo(src: Class_Stream, stm: Class_Stream): void; + + /** + * + * @brief 使用 gzip 算法压缩数据 + * @param data 给定要压缩的数据 + * @return 返回压缩后的二进制数据 + * + * + * @async + */ + export function gzip(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 使用 gzip 算法压缩数据到流对象中 + * @param data 给定要压缩的数据 + * @param stm 指定存储压缩数据的流 + * + * + * @async + */ + export function gzipTo(data: Class_Buffer, stm: Class_Stream): void; + + /** + * + * @brief 使用 gzip 算法压缩源流中的数据到流对象中 + * @param src 给定要压缩的数据所在的流 + * @param stm 指定存储压缩数据的流 + * + * + * @async + */ + export function gzipTo(src: Class_Stream, stm: Class_Stream): void; + + /** + * + * @brief 解压缩 gzip 算法压缩的数据 + * @param data 给定压缩后的数据 + * @return 返回解压缩后的二进制数据 + * + * + * @async + */ + export function gunzip(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 解压缩 gzip 算法压缩的数据到流对象中 + * @param data 给定要解压缩的数据 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function gunzipTo(data: Class_Buffer, stm: Class_Stream): void; + + /** + * + * @brief 解压缩源流中 gzip 算法压缩的数据到流对象中 + * @param src 给定要解压缩的数据所在的流 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function gunzipTo(src: Class_Stream, stm: Class_Stream): void; + + /** + * + * @brief 使用 deflate 算法压缩数据(deflateRaw) + * @param data 给定要压缩的数据 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * @return 返回压缩后的二进制数据 + * + * + * @async + */ + export function deflateRaw(data: Class_Buffer, level?: number/** = undefined*/): Class_Buffer; + + /** + * + * @brief 使用 deflate 算法压缩数据到流对象中(deflateRaw) + * @param data 给定要压缩的数据 + * @param stm 指定存储压缩数据的流 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * + * + * @async + */ + export function deflateRawTo(data: Class_Buffer, stm: Class_Stream, level?: number/** = undefined*/): void; + + /** + * + * @brief 使用 deflate 算法压缩源流中的数据到流对象中(deflateRaw) + * @param src 给定要压缩的数据所在的流 + * @param stm 指定存储压缩数据的流 + * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION + * + * + * @async + */ + export function deflateRawTo(src: Class_Stream, stm: Class_Stream, level?: number/** = undefined*/): void; + + /** + * + * @brief 解压缩 deflate 算法压缩的数据(inflateRaw) + * @param data 给定压缩后的数据 + * @return 返回解压缩后的二进制数据 + * + * + * @async + */ + export function inflateRaw(data: Class_Buffer): Class_Buffer; + + /** + * + * @brief 解压缩 deflate 算法压缩的数据到流对象中(inflateRaw) + * @param data 给定要解压缩的数据 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function inflateRawTo(data: Class_Buffer, stm: Class_Stream): void; + + /** + * + * @brief 解压缩源流中 deflate 算法压缩的数据到流对象中(inflateRaw) + * @param src 给定要解压缩的数据所在的流 + * @param stm 指定存储解压缩数据的流 + * + * + * @async + */ + export function inflateRawTo(src: Class_Stream, stm: Class_Stream): void; + + } /** end of `module zlib` */ + export = zlib +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/declare/zmq.d.ts b/types/fibjs/declare/zmq.d.ts new file mode 100644 index 0000000000..04f7b59815 --- /dev/null +++ b/types/fibjs/declare/zmq.d.ts @@ -0,0 +1,314 @@ +/*************************************************************************** + * * + * This file was automatically generated with idlc.js * + * build info: * + * - fibjs : 0.25.0 * + * - date : Jun 11 2018 14:17:22 * + * * + ***************************************************************************/ + +/** + * @author Richard + * + */ + + + + + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + +/// + + + +/** module Or Internal Object */ +/** + * @brief zeroMQ 消息队列模块 + * @detail 基础模块。提供 zeroMQ 消息队列支撑。,```JavaScript,var zmq = require('zmq');,``` + */ +declare module "zmq" { + + + module zmq { + + /** + * + * + * + * + */ + export const PAIR = 0; + + /** + * + * @brief 发布类型,所发送的消息将会分发给所有订阅者。 + * + * + */ + export const PUB = 1; + + /** + * + * @brief 订阅类型,用于接收 PUB 分发的消息。 + * + * + */ + export const SUB = 2; + + /** + * + * @brief 请求类型,此类型的接口只允许交替进行 send 和 recv 消息,每一个接受的消息都是最后一次发送请求的响应。 + * + * + */ + export const REQ = 3; + + /** + * + * @brief 响应类型,此类型的接口只允许交替进行 recv 和 send 消息,每一个发送的消息都会作为最后一次接受的请求的回应。 + * + * + */ + export const REP = 4; + + /** + * + * + * + * + */ + export const DEALER = 5; + + /** + * + * + * + * + */ + export const ROUTER = 6; + + /** + * + * @brief 获取消息类型,上游推送的消息将被公平的分发到此类接口。 + * + * + */ + export const PULL = 7; + + /** + * + * @brief 推送类型,推送的消息将均衡发送到下游接口。 + * + * + */ + export const PUSH = 8; + + /** + * + * + * + * + */ + export const XPUB = 9; + + /** + * + * + * + * + */ + export const XSUB = 10; + + + + /** + * + * @brief ZmqSocket 对象,参见 ZmqSocket + * + * + */ + export class ZmqSocket extends Class_ZmqSocket {} + + + + + } /** end of `module zmq` */ + export = zmq +} + +/** } /** endof `module Or Internal Object` */ + + diff --git a/types/fibjs/fibjs-tests.ts b/types/fibjs/fibjs-tests.ts new file mode 100644 index 0000000000..90b5f5ff6c --- /dev/null +++ b/types/fibjs/fibjs-tests.ts @@ -0,0 +1,48 @@ +import assert = require('assert'); +import base32 = require('base32'); +import base64 = require('base64'); +import base64vlq = require('base64vlq'); +import bson = require('bson'); +import console = require('console'); +import constants = require('constants'); +import coroutine = require('coroutine'); +import crypto = require('crypto'); +import db = require('db'); +import dgram = require('dgram'); +import dns = require('dns'); +// import encoding = require('encoding'); +import fs = require('fs'); +import gd = require('gd'); +// import global = require('global'); +import gui = require('gui'); +import hash = require('hash'); +import hex = require('hex'); +import http = require('http'); +import iconv = require('iconv'); +import io = require('io'); +import json = require('json'); +import mq = require('mq'); +import net = require('net'); +import os = require('os'); +import path = require('path'); +import path_posix = require('path_posix'); +import path_win32 = require('path_win32'); +import process = require('process'); +import profiler = require('profiler'); +import punycode = require('punycode'); +import querystring = require('querystring'); +import registry = require('registry'); +import ssl = require('ssl'); +import string_decoder = require('string_decoder'); +// import test = require('test'); +import timers = require('timers'); +import tty = require('tty'); +import url = require('url'); +import util = require('util'); +import uuid = require('uuid'); +import vm = require('vm'); +import ws = require('ws'); +import xml = require('xml'); +import zip = require('zip'); +import zlib = require('zlib'); +import zmq = require('zmq'); diff --git a/types/fibjs/index.d.ts b/types/fibjs/index.d.ts new file mode 100644 index 0000000000..67bc9f3a4e --- /dev/null +++ b/types/fibjs/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for fibjs 0.25 +// Project: https://github.com/fibjs/fibjs +// Definitions by: Richard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// diff --git a/types/fibjs/tsconfig.json b/types/fibjs/tsconfig.json new file mode 100644 index 0000000000..c42204e812 --- /dev/null +++ b/types/fibjs/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fibjs-tests.ts" + ] +} diff --git a/types/fibjs/tslint.json b/types/fibjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fibjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/flatbuffers/index.d.ts b/types/flatbuffers/index.d.ts index b95741200b..bd74387bf2 100644 --- a/types/flatbuffers/index.d.ts +++ b/types/flatbuffers/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for flatbuffers 1.6 +// Type definitions for flatbuffers 1.9 // Project: http://google.github.io/flatbuffers/index.html // Definitions by: Kamil Rojewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ declare global { type Offset = number; interface Table { - bb: ByteBuffer; + bb: ByteBuffer|null; bb_pos: number; } @@ -241,6 +241,8 @@ declare global { writeFloat32(offset: number, value: number): void; writeFloat64(offset: number, value: number): void; + getBufferIdentifier(): string; + /** * Look up a field in the vtable, return an offset into the object, or 0 if the * field is not present. diff --git a/types/flight/flight-tests.ts b/types/flight/flight-tests.ts index bd2f22d1c3..dd21f32f48 100644 --- a/types/flight/flight-tests.ts +++ b/types/flight/flight-tests.ts @@ -1,6 +1,6 @@ declare var el: Element; -declare var els: Element[]; +declare var els: HTMLElement[]; declare var mixinFn: Function; function TestComponent() { diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index ac1bf84e99..93f66d3f27 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -80,7 +80,7 @@ export interface GeometryObject extends GeoJsonObject { * Union of geometry objects. * https://tools.ietf.org/html/rfc7946#section-3 */ -export type Geometry = Point | MultiPoint | LineString | Polygon | MultiPolygon | GeometryCollection; +export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; /** * Point geometry object. diff --git a/types/google-adwords-scripts/index.d.ts b/types/google-adwords-scripts/index.d.ts index 3e64730056..adf58cb4a4 100644 --- a/types/google-adwords-scripts/index.d.ts +++ b/types/google-adwords-scripts/index.d.ts @@ -1387,7 +1387,7 @@ interface hasStartAndEndDateBuilder { } interface hasStats { - getStatsFor(dateRange: DayOfWeekString): AdWordsStats; + getStatsFor(dateRange: DateRange): AdWordsStats; getStatsFor(dateFrom: AdWordsDate | string, dateTo: AdWordsDate | string): AdWordsStats; } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts index 62d497eb4f..d879d30091 100644 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -82,6 +82,10 @@ declare namespace GoogleAppsScript { * Sets the URL to navigate to when the action is activated. */ setOpenLink(openLink: OpenLink): ActionResponseBuilder; + /** + * Sets a flag to indicate that this action changed the existing data state. + */ + setStateChanged(stateChanged: boolean): ActionResponseBuilder; } export interface AuthorizationAction { diff --git a/types/googlemaps/googlemaps-tests.ts b/types/googlemaps/googlemaps-tests.ts index 561e53f91a..99d5902a88 100644 --- a/types/googlemaps/googlemaps-tests.ts +++ b/types/googlemaps/googlemaps-tests.ts @@ -60,6 +60,33 @@ map.fitBounds({ top: 50 }); +/***** Pan map to bounds *****/ +map.panToBounds({ + north: 10, + east: 10, + west: 10, + south: 10 +}) + +map.panToBounds({ + north: 10, + east: 10, + west: 10, + south: 10 +}, 50) + +map.panToBounds({ + east: 10, + north: 10, + south: 10, + west: 10 +}, { + bottom: 100, + left: 150, + right: 150, + top: 50 +}); + /***** Data *****/ diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 9430698fe6..a8de5810ec 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -51,7 +51,7 @@ declare namespace google.maps { getZoom(): number; panBy(x: number, y: number): void; panTo(latLng: LatLng|LatLngLiteral): void; - panToBounds(latLngBounds: LatLngBounds|LatLngBoundsLiteral): void; + panToBounds(latLngBounds: LatLngBounds|LatLngBoundsLiteral, padding?: number|Padding): void; setCenter(latlng: LatLng|LatLngLiteral): void; setHeading(heading: number): void; setMapTypeId(mapTypeId: MapTypeId|string): void; diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index f1da1b35b4..288836d6b3 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -4,8 +4,10 @@ const params: ReCaptchaV2.Parameters = { type: "image", size: "normal", tabindex: 5, + isolated: false, callback: (response: string) => { }, "expired-callback": () => { }, + "error-callback": () => { }, }; const size1: ReCaptchaV2.Size = "compact"; @@ -25,6 +27,7 @@ const id1: number = grecaptcha.render("foo"); const id2: number = grecaptcha.render("foo", params); const id3: number = grecaptcha.render(document.getElementById("foo")); const id4: number = grecaptcha.render(document.getElementById("foo"), params); +const id5: number = grecaptcha.render(document.getElementById("foo"), params, true); // response takes a number and returns a string const response1: string = grecaptcha.getResponse(id1); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index 067139e6c9..c9dedbfb74 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -1,19 +1,24 @@ // Type definitions for Google Recaptcha 2.0 // Project: https://www.google.com/recaptcha -// Definitions by: Kristof Mattei , Martin Costello , Ruslan Arkhipau +// Definitions by: Kristof Mattei +// Martin Costello +// Ruslan Arkhipau +// Rafael Tavares // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var grecaptcha: ReCaptchaV2.ReCaptcha; declare namespace ReCaptchaV2 { - class ReCaptcha { + interface ReCaptcha { /** * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @param inherit Invisible reCAPTCHA only. Use existing data-* attributes on the element if the corresponding parameter is not specified. + * The values in parameters will take precedence over the attributes. * @return the ID of the newly created widget. */ - render(container: (string | HTMLElement), parameters?: Parameters): number; + render(container: (string | HTMLElement), parameters?: Parameters, inherit?: boolean): number; /** * Resets the reCAPTCHA widget. * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. @@ -65,11 +70,6 @@ declare namespace ReCaptchaV2 { * If other elements in your page use tabindex, it should be set to make user navigation easier. */ tabindex?: number; - /** - * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. - * The user's response, g-recaptcha-response, will be the input for your callback function. - */ - callback?(response: string): void; /** * Optional. The badge location for g-recaptcha with size of "invisible". * @@ -77,10 +77,29 @@ declare namespace ReCaptchaV2 { */ badge?: Badge; /** - * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + * Optional. Invisible reCAPTCHA only. For plugin owners to not interfere with existing reCAPTCHA installations on a page. + * If true, this reCAPTCHA instance will be part of a separate ID space. + * + * @default false + */ + isolated?: boolean; + /** + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + */ + callback?(response: string): void; + /** + * Optional. Your callback function that's executed when the reCAPTCHA response expires and the user needs to solve a new CAPTCHA. */ // Notice to the reader // I need to surround this object with quotes, this will however break intellisense in VS 2013. "expired-callback"?(): void; + /** + * Optional. Your callback function that's executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. + * If you specify this function, you are responsible for informing the user that they should retry. + */ + // Notice to the reader + // I need to surround this object with quotes, this will however break intellisense in VS 2013. + "error-callback"?(): void; } } diff --git a/types/http-link-header/index.d.ts b/types/http-link-header/index.d.ts index a8dca563d2..cbcb4cbfdb 100644 --- a/types/http-link-header/index.d.ts +++ b/types/http-link-header/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for http-link-header 0.6 // Project: https://github.com/jhermsmeier/node-http-link-header -// Definitions by: Christian Rackerseder +// Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface Reference { diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 3858cab780..6e67a5b592 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -32,6 +32,11 @@ export interface IFrameOptions { * CSS margin attribute, for example '8px 3em'. A number value is converted into px. */ bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; /** * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. * If your iFrame navigates between different domains, ports or protocols; then you will need to diff --git a/types/inboxsdk/inboxsdk-tests.ts b/types/inboxsdk/inboxsdk-tests.ts new file mode 100644 index 0000000000..a763674c73 --- /dev/null +++ b/types/inboxsdk/inboxsdk-tests.ts @@ -0,0 +1,815 @@ +import ComposeView = InboxSDK.Compose.ComposeView; +import Contact = InboxSDK.Common.Contact; +import ThreadRowView = InboxSDK.Lists.ThreadRowView; +import ThreadView = InboxSDK.Conversations.ThreadView; +import SimpleElementView = InboxSDK.Common.SimpleElementView; +import ContentPanelView = InboxSDK.Conversations.ContentPanelView; +import MessageView = InboxSDK.Conversations.MessageView; +import AttachmentCardView = InboxSDK.Conversations.AttachmentCardView; +import AttachmentCardClickEvent = InboxSDK.Conversations.AttachmentCardClickEvent; +import MessageViewLinkDescriptor = InboxSDK.Conversations.MessageViewLinkDescriptor; +import SectionDescriptor = InboxSDK.Router.SectionDescriptor; +import NavItemDescriptor = InboxSDK.NavMenu.NavItemDescriptor; + +InboxSDK.load(1, '1234').then((_sdk: InboxSDK.InboxSDKInstance) => { + _sdk.ButterBar.hideGmailMessage(); +}); + +InboxSDK.load(1, '1234', {}).then(() => console.log('done')); +InboxSDK.load(1, '1234', { + appIconUrl: 'url', + appName: 'name', + suppressAddonTitle: 'su' +}).then(() => console.log('done')); + +InboxSDK.loadScript('https://google.com').then(() => console.log('done')); +InboxSDK.loadScript('https://google.com', {}).then(() => console.log('done')); +InboxSDK.loadScript('https://google.com', {nowrap: true}).then(() => console.log('done')); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + sdk.ButterBar.showMessage({ + text: 'text', + }); + + sdk.ButterBar.showMessage({ + text: 'text', + className: 'c', + hideOnViewChanged: true, + persistent: true, + priority: 1, + time: 1, + messageKey: '1' + }); + + const el: HTMLElement = new HTMLElement(); + + sdk.ButterBar.showMessage({ + el, + }); + + sdk.ButterBar.showMessage({ + el, + className: 'c', + hideOnViewChanged: true, + persistent: true, + priority: 1, + time: 1, + messageKey: '1' + }); + + sdk.ButterBar.showMessage({ + html: '

', + }); + + sdk.ButterBar.showMessage({ + html: '

', + className: 'c', + hideOnViewChanged: true, + persistent: true, + priority: 1, + time: 1, + messageKey: '1' + }); + + sdk.ButterBar.showLoading(); + + sdk.ButterBar.showError({ + text: 'error' + }); + + sdk.ButterBar.showSaving({ + text: 'saving' + }); + + sdk.ButterBar.hideMessage('key'); + sdk.ButterBar.hideGmailMessage(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Compose.registerComposeViewHandler((composeView: ComposeView) => { + composeView.addButton({ + title: 'button title', + onClick: e => { + const eq = e.composeView === composeView; + const dropdownDestroyed = e.dropdown.destroyed; + + e.dropdown.close(); + + const el: HTMLElement = e.dropdown.el; + + e.dropdown.setPlacementOptions({}); + e.dropdown.setPlacementOptions({ + bottomBuffer: 1, + buffer: 1, + forceHAlign: true, + forcePosition: true, + forceVAlign: true, + hAlign: 'center', + position: 'middle', + rightBuffer: 1, + topBuffer: 1, + vAlign: 'top', + leftBuffer: 1 + }); + } + }); + + const statusBarView = composeView.addStatusBar({}); + statusBarView.setHeight(1); + + composeView.addStatusBar({ + height: 1, + orderHint: 1 + }); + + composeView.close(); + + composeView.send(); + composeView.send({sendAndArchive: true}); + + const element: HTMLElement = composeView.getBodyElement(); + const msgId: string = composeView.getInitialMessageID(); + const threadId: string = composeView.getThreadID(); + composeView.getDraftID().then(draftId => { + const id: string = draftId.toLowerCase(); + }); + composeView.getCurrentDraftID().then(draftId => { + if (draftId) { + const id: string = draftId.toLowerCase(); + } + }); + + const html: string = composeView.getHTMLContent(); + const bodyHtml: string = composeView.getSelectedBodyHTML(); + const bodyText: string = composeView.getSelectedBodyText(); + const subject: string = composeView.getSubject(); + const textContent: string = composeView.getTextContent(); + const contacts: Contact[] = composeView.getToRecipients(); + const contactsCC: Contact[] = composeView.getCcRecipients(); + const contactsBCC: Contact[] = composeView.getBccRecipients(); + + composeView.insertTextIntoBodyAtCursor('text'); + const el1: HTMLElement = composeView.insertHTMLIntoBodyAtCursor(new HTMLElement()); + const el2: HTMLElement = composeView.insertHTMLIntoBodyAtCursor('html'); + + const el3: HTMLElement = composeView.insertLinkChipIntoBodyAtCursor('text', 'http://url.com', 'http://url.com/favicon.ico'); + const el4: HTMLElement = composeView.insertLinkIntoBodyAtCursor('text', 'http://url.com'); + + const inline: boolean = composeView.isInlineReplyForm(); + const fullScreen: boolean = composeView.isFullscreen(); + const minimized: boolean = composeView.isMinimized(); + composeView.setFullscreen(true); + composeView.setMinimized(true); + composeView.popOut().then(view => view === composeView); + + const removeColor = composeView.setTitleBarColor('red'); + removeColor(); + + const isReply: boolean = composeView.isReply(); + + composeView.setToRecipients(['a@a.com', 'b@b.com']); + composeView.setCcRecipients(['a@a.com', 'b@b.com']); + composeView.setBccRecipients(['a@a.com', 'b@b.com']); + + const fromContact: InboxSDK.Common.Contact = composeView.getFromContact(); + const fromContacts: InboxSDK.Common.Contact[] = composeView.getFromContactChoices(); + + composeView.setFromEmail('a@a.com'); + composeView.setSubject('subject'); + composeView.setBodyHTML('

'); + composeView.setBodyText('text'); + composeView.attachFiles([new Blob()]).then(() => console.log()); + composeView.attachInlineFiles([new Blob()]).then(() => console.log()); + + composeView.on('destroy', event => { + const msgId: string = event.messageID; + const byInbox: boolean = event.closedByInboxSDK; + }); + + composeView.on('fullscreenChanged', event => { + const fs: boolean = event.fullscreen; + }); + + composeView.on('fromContactChanged', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('toContactAdded', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('toContactRemoved', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('ccContactAdded', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('ccContactRemoved', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('bccContactAdded', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('bccContactRemoved', event => { + const c: InboxSDK.Common.Contact = event.contact; + }); + + composeView.on('recipientsChanged', event => { + let c: InboxSDK.Common.Contact; + c = event.to.added[0]; + c = event.to.removed[0]; + c = event.cc.added[0]; + c = event.cc.removed[0]; + c = event.bcc.added[0]; + c = event.bcc.removed[0]; + }); + + composeView.on('presending', event => { + event.cancel(); + }); + + composeView.on('sent', event => { + event.getMessageID().then(msgId => msgId.toLowerCase()); + event.getThreadID().then(threadId => threadId.toLowerCase()); + }); + + composeView.on('discard', () => { + console.log(); + }); + composeView.on('sendCanceled', () => { + console.log(); + }); + composeView.on('sending', () => { + console.log(); + }); + composeView.on('bodyChanged', () => { + console.log(); + }); + composeView.on('minimized', () => { + console.log(); + }); + composeView.on('restored', () => { + console.log(); + }); + + const destroyed: boolean = composeView.destroyed; + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Lists.registerThreadRowViewHandler((threadRowView: ThreadRowView) => { + threadRowView.addLabel({ + title: 'title', + iconUrl: 'http://url.com' + }); + + threadRowView.addLabel({ + title: 'title', + iconUrl: 'http://url.com', + backgroundColor: 'red', + foregroundColor: 'blue', + iconBackgroundColor: 'yellow', + iconClass: 'big' + }); + + threadRowView.addImage({ + imageUrl: 'http://url.com' + }); + + threadRowView.addImage({ + imageUrl: 'http://url.com', + imageClass: 'big', + tooltip: 'tooltip', + orderHint: 1 + }); + + threadRowView.addButton({ + title: 'title', + iconUrl: 'http://url.com', + onClick: event => { + const eq = event.threadRowView === threadRowView; + if (event.dropdown) { + event.dropdown.close(); + } + }, + hasDropdown: true + }); + + threadRowView.addButton({ + title: 'title', + iconUrl: 'http://url.com', + onClick: event => { + }, + hasDropdown: false, + iconClass: 'big' + }); + + threadRowView.addActionButton({ + type: 'LINK', + title: 'title', + className: 'big', + url: 'http://url.com', + onClick: () => { + } + }); + + threadRowView.addAttachmentIcon({}); + threadRowView.addAttachmentIcon({ + tooltip: 'tooltip', + iconClass: 'big', + iconUrl: 'http://url.com' + }); + + threadRowView.replaceDate({ + text: '1/1/2000' + }); + threadRowView.replaceDate({ + text: '1/1/2000', + textColor: 'red', + tooltip: 'tooltip' + }); + + threadRowView.replaceDraftLabel({ + text: 'my draft' + }); + threadRowView.replaceDraftLabel({ + text: 'my draft', + count: '2' + }); + + const subject: string = threadRowView.getSubject(); + const date: string = threadRowView.getDateString(); + threadRowView.getThreadIDAsync().then(threadId => threadId.toLowerCase()); + threadRowView.getThreadIDIfStableAsync().then(threadId => { + if (threadId) { + threadId.toLowerCase(); + } + }); + threadRowView.getDraftID().then(draftId => draftId.toLowerCase()); + + const count1: number = threadRowView.getVisibleDraftCount(); + const count2: number = threadRowView.getVisibleMessageCount(); + + const contacts: InboxSDK.Common.Contact[] = threadRowView.getContacts(); + + threadRowView.on('destroyed', () => console.log()); + + const destroyed: boolean = threadRowView.destroyed; + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Conversations.registerThreadViewHandler((threadView: ThreadView) => { + const noticeBar: SimpleElementView = threadView.addNoticeBar(); + noticeBar.destroy(); + + const contentPanel: ContentPanelView = threadView.addSidebarContentPanel({ + el: new HTMLElement(), + title: 'title', + iconUrl: 'http://url.com', + }); + + contentPanel.remove(); + const destroyed: boolean = contentPanel.destroyed; + contentPanel.on('destroy', () => console.log()); + contentPanel.on('deactivate', () => console.log()); + contentPanel.on('activate', () => console.log()); + + threadView.addSidebarContentPanel({ + el: new HTMLElement(), + title: 'title', + iconUrl: 'http://url.com', + appIconUrl: 'http://url.com', + appName: 'app name', + id: '1', + orderHint: 1, + hideTitleBar: true + }); + + const messageViews: MessageView[] = threadView.getMessageViews(); + const allMessageViews: MessageView[] = threadView.getMessageViewsAll(); + const subject: string = threadView.getSubject(); + threadView.getThreadIDAsync().then(threadId => threadId.toLowerCase()); + + threadView.on('contactHover', event => { + const contact: Contact = event.contact; + const eq1 = event.messageView === messageViews[0]; + const eq2 = event.threadView === threadView; + const isSender: boolean = event.contactType === 'sender'; + }); + + threadView.on('destroy', () => console.log()); + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Conversations.registerMessageViewHandler((messageView: MessageView) => { + const attachmentCardView: AttachmentCardView = messageView.addAttachmentCardView({ + title: 'title', + description: 'desc', + previewUrl: 'http://url.com', + previewThumbnailUrl: 'http://url.com', + failoverPreviewIconUrl: 'http://url.com', + previewOnClick: event => { + const eq = event.attachmentCardView === attachmentCardView; + event.preventDefault(); + }, + fileIconImageUrl: 'http://url.com', + buttons: [ + { + downloadUrl: 'http://url.com', + downloadFilename: 'file.txt', + openInNewTab: true, + onClick: () => { + } + }, + { + iconUrl: 'http://url.com', + tooltip: 'tooltip', + onClick: (event: AttachmentCardClickEvent) => event.getDownloadURL().then(url => url.toLowerCase()) + } + ], + foldColor: 'red', + mimeType: 'text' + }); + + const attachmentType: string = attachmentCardView.getAttachmentType(); + const title: string = attachmentCardView.getTitle(); + const msgView: MessageView | null = attachmentCardView.getMessageView(); + attachmentCardView.addButton({ + iconUrl: 'http://url.com', + tooltip: 'tooltip', + onClick: (event: AttachmentCardClickEvent) => event.getDownloadURL().then(url => url.toLowerCase()) + }); + + attachmentCardView.on('destroy', () => console.log()); + const destroyed: boolean = attachmentCardView.destroyed; + + messageView.addAttachmentsToolbarButton({ + iconUrl: 'http://url.com', + tooltip: 'tooltip', + onClick: event => { + const attType: string = event.attachmentCardViews[0].getAttachmentType(); + } + }); + + messageView.addToolbarButton({ + section: 'MORE', + title: 'title', + iconUrl: 'http://url.com', + iconClass: 'big', + onClick: () => { + }, + orderHint: 1 + }); + + const el: HTMLElement = messageView.getBodyElement(); + messageView.getMessageIDAsync().then(msgId => msgId.toLowerCase()); + const attCardViews: AttachmentCardView[] = messageView.getFileAttachmentCardViews(); + const isQuotedArea = messageView.isElementInQuotedArea(); + const isLoaded = messageView.isLoaded(); + const links: MessageViewLinkDescriptor[] = messageView.getLinksInBody(); + links[0].text.toLowerCase(); + links[0].element.click(); + links[0].html.toLowerCase(); + const isInQuotedArea: boolean = links[0].isInQuotedArea; + links[0].href.toLowerCase(); + + const contact: Contact = messageView.getSender(); + const add: string[] = messageView.getRecipientEmailAddresses(); + messageView.getRecipientsFull().then(contacts => { + const c: Contact = contacts[0]; + }); + + const threadView: ThreadView = messageView.getThreadView(); + const date: string = messageView.getDateString(); + messageView.addAttachmentIcon({ + iconUrl: 'http://url.com', + iconClass: 'big', + onClick: () => { + }, + tooltip: 'tooltip' + }); + + const eq = messageView.getViewState() === 'HIDDEN'; + + messageView.on('viewStateChange', event => { + const eq1 = event.newViewState === 'COLLAPSED'; + const eq2 = event.oldViewState === 'EXPANDED'; + const eq3 = event.messageView === messageView; + }); + + messageView.on('contactHover', event => { + event.contact.name.toLowerCase(); + }); + + messageView.on('load', () => console.log()); + messageView.on('destroy', () => console.log()); + + const destroyed1: boolean = messageView.destroyed; + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Conversations.registerMessageViewHandlerAll((messageView: MessageView) => { + const isLoaded: boolean = messageView.isLoaded(); + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Conversations.registerFileAttachmentCardViewHandler((attachmentCardView: AttachmentCardView) => { + const messageView: MessageView | null = attachmentCardView.getMessageView(); + }); + + unregister(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const unregister = sdk.Toolbars.registerThreadButton({ + hasDropdown: true, + hideFor: (routeView => routeView.getParams()), + iconClass: 'big', + iconUrl: 'http://url.com', + keyboardShortcutHandle: { + remove: () => { + } + }, + listSection: 'INBOX_STATE', + onClick: event => event.position === 'LIST', + orderHint: 1, + positions: ['LIST', 'ROW'], + threadSection: 'METADATA_STATE', + title: 'title' + }); + + unregister(); + + sdk.Toolbars.addToolbarButtonForApp({ + iconClass: 'big', + arrowColor: 'red', + iconUrl: 'http://url.com', + onClick: event => event.dropdown.close(), + title: 'title', + titleClass: 'big' + }); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + sdk.Router.createLink('1234', {p1: 1, 0: 1}).toLowerCase(); + sdk.Router.goto('1234', {p1: 1, 0: 1}); + + const unregister1 = sdk.Router.handleCustomRoute('1234', customRouteView => { + customRouteView.getParams(); + customRouteView.setFullWidth(true); + customRouteView.getElement().click(); + }); + + unregister1(); + + const unregister2 = sdk.Router.handleAllRoutes(routeView => { + routeView.getParams(); + routeView.getRouteID(); + routeView.getRouteType(); + routeView.on('destroy', () => { + }); + const destroyed: boolean = routeView.destroyed; + }); + + unregister2(); + + const unregister3 = sdk.Router.handleListRoute('ALL_MAIL', listRouteView => { + const sectionDescriptor: SectionDescriptor = { + contentElement: new HTMLElement(), + footerLinkText: 'text', + hasDropdown: true, + onDropdownClick: event => event.dropdown.close(), + onFooterLinkClick: event => { + }, + onTitleLinkClick: () => { + }, + subtitle: 'title', + tableRows: [{ + body: 'body', + iconClass: 'big', + iconUrl: 'http://url.com', + isRead: 'true', + labels: [{ + iconClass: 'big', + iconBackgroundColor: 'red', + foregroundColor: 'green', + backgroundColor: 'blue', + iconUrl: 'http://url.com', + title: 'title' + }], + onClick: () => { + }, + routeID: '1234', + routeParams: ['p1'], + shortDetailText: 'text', + title: 'title' + }], + title: 'title', + titleLinkText: 'text' + }; + + listRouteView.addCollapsibleSection(sectionDescriptor); + listRouteView.addSection(sectionDescriptor); + + listRouteView.refresh(); + }); + + unregister3(); + + const unregister4 = sdk.Router.handleCustomListRoute('1234', (offset, max) => { + return { + threads: [ + { + rfcMessageId: 'id', + gmailThreadId: 'id' + }, + 'id' + ], + total: 1, + hasMore: true, + }; + }); + + unregister4(); + + sdk.Router.getCurrentRouteView().getRouteID().toLowerCase(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const navItemDescriptor: NavItemDescriptor = { + accessory: { + type: 'CREATE', + onClick: () => { + } + }, + backgroundColor: 'red', + expanderForegroundColor: 'green', + iconClass: 'big', + iconUrl: 'http://url.com', + name: 'name', + onClick: event => event.preventDefault(), + orderHint: 1, + routeID: '1234', + routeParams: {p: 1}, + type: 'MANAGE' + }; + + const navItem = sdk.NavMenu.addNavItem(navItemDescriptor); + const navItem1 = navItem.addNavItem(navItemDescriptor); + navItem.remove(); + navItem1.remove(); + + const isCollapsed: boolean = navItem.isCollapsed(); + navItem.setCollapsed(true); + + navItem.on('destroy', () => { + }); + const destroyed: boolean = navItem.destroyed; +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const modalView = sdk.Widgets.showModalView({ + buttons: [{ + color: 'red', + onClick: () => { + }, + orderHint: 1, + text: 'text', + title: 'title', + type: 'PRIMARY_ACTION' + }], + chrome: true, + constrainTitleWidth: true, + el: new HTMLElement(), + showCloseButton: true, + title: 'title' + }); + + modalView.close(); + modalView.on('destroyed', () => { + }); + const destroyed: boolean = modalView.destroyed; + + const moleView = sdk.Widgets.showMoleView({ + chrome: true, + className: 'big', + el: new HTMLElement(), + minimizedTitleEl: new HTMLElement(), + title: 'title', + titleEl: new HTMLElement(), + titleButtons: [{ + iconClass: 'big', + iconUrl: 'http://url.com', + onClick: () => { + }, + title: 'title' + }] + }); + + moleView.close(); + const minimized: boolean = moleView.getMinimized(); + moleView.setMinimized(true); + moleView.setTitle('title'); + moleView.on('destroyed', () => { + }); + moleView.on('minimize', () => { + }); + moleView.on('restore', () => { + }); + + const drawerView = sdk.Widgets.showDrawerView({ + chrome: true, + closeWithCompose: true, + el: new HTMLElement(), + title: 'title' + }); + + drawerView.close(); + drawerView.disassociateComposeView(); + const destroyed1: boolean = drawerView.destroyed; + drawerView.on('destroyed', () => { + }); + drawerView.on('slideAnimationDone', () => { + }); + drawerView.on('closing', () => { + }); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const searchResults = [{ + iconUrl: 'http://url.com', + onClick: () => { + }, + description: 'desc', + externalURL: 'http://url.com', + name: 'name', + routeName: 'name', + routeParams: ['a', 'b'] + }, { + iconUrl: 'http://url.com', + onClick: () => { + }, + descriptionHTML: 'desc', + externalURL: 'http://url.com', + nameHTML: 'name', + routeName: 'name', + routeParams: ['a', 'b'] + }]; + + sdk.Search.registerSearchSuggestionsProvider(query => searchResults); + sdk.Search.registerSearchSuggestionsProvider(query => Promise.resolve(searchResults)); + + sdk.Search.registerSearchQueryRewriter({ + term: 'a', + termReplacer: () => 'b' + }); + + sdk.Search.registerSearchQueryRewriter({ + term: 'a', + termReplacer: () => Promise.resolve('b') + }); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + sdk.User.getEmailAddress().toLowerCase(); + const isConversationViewDisabled: boolean = sdk.User.isConversationViewDisabled(); + const isUsingGmailMaterialUI: boolean = sdk.User.isUsingGmailMaterialUI(); + sdk.User.getLanguage().toLowerCase(); + sdk.User.getAccountSwitcherContactList()[0].name.toLowerCase(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const panel = sdk.Global.addSidebarContentPanel({ + el: new HTMLElement(), + title: 'title', + iconUrl: 'http://url.com' + }); + panel.remove(); +}); + +InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { + const handler = sdk.Keyboard.createShortcutHandle({ + chord: 'a', + description: 'b' + }); + + handler.remove(); +}); diff --git a/types/inboxsdk/index.d.ts b/types/inboxsdk/index.d.ts new file mode 100644 index 0000000000..66b696e05a --- /dev/null +++ b/types/inboxsdk/index.d.ts @@ -0,0 +1,1073 @@ +// Type definitions for InboxSDK 2.0 +// Project: https://www.inboxsdk.com/ +// Definitions by: Raphaël Doursenaud +// Amiram Korach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/* + * Copyright (c) 2016 GPC.solutions + * Copyright (c) 2018 https://propelmypr.com + */ + +// tslint:disable-next-line:export-just-namespace +export = InboxSDK; +export as namespace InboxSDK; + +declare namespace InboxSDK { + function load(version: number, appId?: string, opts?: LoadOptions): Promise; + + function loadScript(url: string, options?: LoadScriptOptions): Promise; + +// // Undocummented +// var IMPL_VERSION: string; +// var LOADER_VERSION: string; +// var destroyed: boolean; //: false +// var Logger: { +// error: () => any; +// event: () => any; +// }; + + interface LoadOptions { + appName?: string; + appIconUrl?: string; + suppressAddonTitle?: string; + } + + interface LoadScriptOptions { + nowrap?: boolean; + } + + interface InboxSDKInstance { + Compose: Compose.ComposeInstance; + Lists: Lists.ListsInstance; + Conversations: Conversations.ConversationsInstance; + Toolbars: Toolbars.ToolbarsInstance; + Router: Router.RouterInstance; + NavMenu: NavMenu.NavMenuInstance; + Widgets: Widgets.WidgetsInstance; + ButterBar: ButterBar.ButterBarInstance; + Search: Search.SearchInstance; + User: User.UserInstance; + Keyboard: Keyboard.KeyboardInstance; + Global: Global.GlobalInstance; + } + + namespace Common { + interface Contact { + name: string; + emailAddress: string; + } + + interface DropdownView { + setPlacementOptions(options: PositionOptions): void; + + close(): void; + + reposition(): void; + + el: HTMLElement; + destroyed: boolean; + + on(name: 'destroy', cb: () => void): void; + + on(name: 'preautoclose', cb: (event: PreAutoCloseEvent) => void): void; + } + + interface PreAutoCloseEvent { + type: 'outsideInteraction' | 'escape'; + cause: Event; + + cancel(): void; + } + + interface PositionOptions { + position?: string; + forcePosition?: boolean; + hAlign?: string; + forceHAlign?: boolean; + vAlign?: string; + forceVAlign?: boolean; + buffer?: number; + topBuffer?: number; + bottomBuffer?: number; + leftBuffer?: number; + rightBuffer?: number; + } + + interface SimpleElementView { + destroy(): void; + + el: HTMLElement; + destroyed: boolean; + + on(name: 'destroy', cb: () => void): void; + } + } + + export namespace Compose { + interface ComposeInstance { + registerComposeViewHandler(handler: (composeView: ComposeView) => void): () => void; + + openNewComposeView(): Promise; + } + + interface ComposeView { + addButton(buttonDescriptor: ComposeButtonDescriptor): void; + + addStatusBar(statusBarDescriptor: StatusBarDescriptor): StatusBarView; + + close(): void; + + send(options?: SendOptions): void; + + getBodyElement(): HTMLElement; + + getInitialMessageID(): string; + + getThreadID(): string; + + getDraftID(): Promise; + + getCurrentDraftID(): Promise; + + getHTMLContent(): string; + + getSelectedBodyHTML(): string; + + getSelectedBodyText(): string; + + getSubject(): string; + + getTextContent(): string; + + getToRecipients(): Common.Contact[]; + + getCcRecipients(): Common.Contact[]; + + getBccRecipients(): Common.Contact[]; + + insertTextIntoBodyAtCursor(text: string): void; + + insertHTMLIntoBodyAtCursor(html: string | HTMLElement): HTMLElement; + + insertLinkChipIntoBodyAtCursor(text: string, url: string, iconUrl: string): HTMLElement; + + insertLinkIntoBodyAtCursor(text: string, url: string): HTMLElement; + + isInlineReplyForm(): boolean; + + isFullscreen(): boolean; + + setFullscreen(minimized: boolean): void; + + isMinimized(): boolean; + + setMinimized(minimized: boolean): void; + + popOut(): Promise; + + setTitleBarColor(color: string): () => void; + + isReply(): boolean; + + setToRecipients(emails: string[]): void; + + setCcRecipients(emails: string[]): void; + + setBccRecipients(emails: string[]): void; + + getFromContact(): Common.Contact; + + getFromContactChoices(): Common.Contact[]; + + setFromEmail(email: string): void; + + setSubject(text: string): void; + + setBodyHTML(html: string): void; + + setBodyText(text: string): void; + + attachFiles(files: Blob[]): Promise; + + attachInlineFiles(Files: Blob[]): Promise; + + on(name: 'destroy', cb: (event: { messageID: string, closedByInboxSDK: boolean }) => void): void; + + on(name: 'fullscreenChanged', cb: (event: { fullscreen: boolean }) => void): void; + + on(name: 'fromContactChanged' | 'toContactAdded' | 'toContactRemoved' | 'ccContactAdded' | 'ccContactRemoved' | 'bccContactAdded' | 'bccContactRemoved', + cb: (event: { contact: Common.Contact }) => void): void; + + on(name: 'recipientsChanged', cb: (event: RecipientsChangedEvent) => void): void; + + on(name: 'presending', cb: (event: { cancel: () => void }) => void): void; + + on(name: 'sent', cb: (event: { getThreadID: () => Promise, getMessageID: () => Promise }) => void): void; + + on(name: 'discard' | 'sendCanceled' | 'sending' | 'bodyChanged' | 'minimized' | 'restored', cb: () => void): void; + + destroyed: boolean; + } + + interface RecipientsChangedEvent { + to: { + added: Common.Contact[]; + removed: Common.Contact[]; + }; + cc: { + added: Common.Contact[]; + removed: Common.Contact[]; + }; + bcc: { + added: Common.Contact[]; + removed: Common.Contact[]; + }; + } + + interface ComposeButtonDescriptor { + title: string; + iconUrl?: string; + iconClass?: string; + onClick: (event: ComposeButtonClickEvent) => void; + hasDropdown?: boolean; + type?: 'MODIFIER' | 'SEND_ACTION'; + orderHint?: number; + enabled?: boolean; + } + + interface ComposeButtonClickEvent { + composeView: ComposeView; + dropdown: Common.DropdownView; + } + + interface StatusBarDescriptor { + height?: number; + orderHint?: number; + } + + interface StatusBarView extends Common.SimpleElementView { + setHeight(height: number): void; + } + + interface SendOptions { + sendAndArchive?: boolean; + } + } + + export namespace Lists { + interface ListsInstance { + registerThreadRowViewHandler(handler: (threadRowView: ThreadRowView) => any): () => void; + } + + interface ThreadRowView { + addLabel(labelDescriptor: LabelDescriptor): void; + + // addLabel(labelDescriptor: Stream): void; + + addImage(imageDescriptor: ImageDescriptor): void; + + // addImage(imageDescriptor: Stream): void; + + addButton(buttonDescriptor: ThreadRowButtonDescriptor): void; + + // addButton(buttonDescriptor: Stream): void; + + addActionButton(buttonDescriptor: ThreadRowActionButtonDescriptor): void; + + // addActionButton(buttonDescriptor: Stream): void; + + addAttachmentIcon(threadRowAttachmentIconDescriptor: ThreadRowAttachmentIconDescriptor): void; + + // addAttachmentIcon(threadRowAttachmentIconDescriptor: stream): void + + replaceDate(threadRowDateDescriptor: ThreadRowDateDescriptor): void; + + // replaceDate(threadRowDateDescriptor: Stream): void; + + replaceDraftLabel(draftLabelDescriptor: ThreadRowDraftLabelDescriptor): void; + + // replaceDraftLabel(draftLabelDescriptor: Stream): void; + + getSubject(): string; + + getDateString(): string; + + getThreadIDAsync(): Promise; + + getThreadIDIfStableAsync(): Promise; + + getDraftID(): Promise; + + getVisibleDraftCount(): number; + + getVisibleMessageCount(): number; + + getContacts(): Common.Contact[]; + + on(name: 'destroyed', cb: () => void): void; + + destroyed: boolean; + } + + interface ThreadRowButtonDescriptor { + title: string; + iconUrl: string; + iconClass?: string; + onClick: (event: ThreadRowButtonClickEvent) => void; + hasDropdown?: boolean; + } + + interface ThreadRowButtonClickEvent { + threadRowView: ThreadRowView; + dropdown?: Common.DropdownView; + } + + interface ThreadRowActionButtonDescriptor { + type: 'LINK'; + title: string; + className?: string; + onClick?: (event: any) => void; + url: string; + } + + interface LabelDescriptor { + title: string; + foregroundColor?: string; + backgroundColor?: string; + iconUrl: string; + iconClass?: string; + iconBackgroundColor?: string; + } + + interface ImageDescriptor { + imageUrl: string; + imageClass?: string; + tooltip?: string; + orderHint?: number; + } + + interface ThreadRowDateDescriptor { + text: string; + textColor?: string; + tooltip?: string; + } + + interface ThreadRowAttachmentIconDescriptor { + iconUrl?: string; + iconClass?: string; + tooltip?: string; + } + + interface ThreadRowDraftLabelDescriptor { + text: string; + count?: string; + } + } + + export namespace Conversations { + interface ConversationsInstance { + registerThreadViewHandler(handler: (threadView: ThreadView) => void): () => void; + + registerMessageViewHandler(handler: (messageView: MessageView) => void): () => void; + + registerMessageViewHandlerAll(handler: (messageView: MessageView) => void): () => void; + + registerFileAttachmentCardViewHandler(handler: (attachmentCardView: AttachmentCardView) => void): () => void; + } + + interface ThreadView { + addNoticeBar(): Common.SimpleElementView; + + addSidebarContentPanel(contentPanelDescriptor: ContentPanelDescriptor): ContentPanelView; + + getMessageViews(): MessageView[]; + + getMessageViewsAll(): MessageView[]; + + getSubject(): string; + + getThreadIDAsync(): Promise; + + on(name: 'contactHover', cb: (event: ContactHoverEvent) => void): void; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + interface ContactHoverEvent { + contact: Common.Contact; + contactType: 'sender' | 'recipient'; + messageView: MessageView; + threadView: ThreadView; + } + + interface MessageView { + addAttachmentCardView(cardOptions: AttachmentCardOptions | AttachmentCardNoPreviewOptions): AttachmentCardView; + + addAttachmentsToolbarButton(buttonOptions: AttachmentsToolbarButtonDescriptor): void; + + addToolbarButton(options: MessageViewToolbarButtonDescriptor): void; + + getBodyElement(): HTMLElement; + + getMessageIDAsync(): Promise; + + getFileAttachmentCardViews(): AttachmentCardView[]; + + isElementInQuotedArea(): boolean; + + isLoaded(): boolean; + + getLinksInBody(): MessageViewLinkDescriptor[]; + + getSender(): Common.Contact; + + getRecipientEmailAddresses(): string[]; + + getRecipientsFull(): Promise; + + getThreadView(): ThreadView; + + getDateString(): string; + + addAttachmentIcon(iconDescriptor: MessageAttachmentIconDescriptor): void; + + // addAttachmentIcon(iconDescriptor: Stream): void; + + getViewState(): MessageViewViewStates; + + on(name: 'viewStateChange', cb: (event: { newViewState: MessageViewViewStates, oldViewState: MessageViewViewStates, messageView: MessageView }) => void): void; + + on(name: 'contactHover', cb: (event: ContactHoverEvent) => void): void; + + on(name: 'destroy' | 'load', cb: () => void): void; + + destroyed: boolean; + } + + type MessageViewViewStates = 'HIDDEN' | 'COLLAPSED' | 'EXPANDED'; + + interface ContentPanelView { + remove(): void; + + on(name: 'destroy' | 'activate' | 'deactivate', cb: () => void): void; + + destroyed: boolean; + } + + interface AttachmentCardView { + getAttachmentType(): string; + + addButton(buttonDescriptor: CustomButtonDescriptor): void; + + getTitle(): string; + + /** + * @deprecated. Use AttachmentCardClickEvent.getDownloadURL() instead + */ + getDownloadURL(): Promise; + + getMessageView(): MessageView | null; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + // ConversationsDescriptors + + interface AttachmentCardOptions { + title: string; + description: string; + previewUrl: string; + previewThumbnailUrl: string; + failoverPreviewIconUrl: string; + previewOnClick: (event: PreviewClickEvent) => void; + fileIconImageUrl: string; + buttons: Array; + foldColor?: string; + mimeType?: string; + } + + interface AttachmentCardNoPreviewOptions { + title: string; + description: string; + previewUrl: string; + iconThumbnailUrl: string; + previewOnClick: (event: PreviewClickEvent) => void; + fileIconImageUrl: string; + buttons: Array; + foldColor?: string; + } + + interface PreviewClickEvent { + attachmentCardView: AttachmentCardView; + + preventDefault(): void; + } + + interface ContentPanelDescriptor { + el: HTMLElement; + title: string; + iconUrl: string; + appName?: string; + appIconUrl?: string; + id?: string; + hideTitleBar?: boolean; + orderHint?: number; + } + + interface DownloadButtonDescriptor { + downloadUrl: string; + downloadFilename?: string; + onClick: (event: any) => void; + openInNewTab?: boolean; + } + + interface CustomButtonDescriptor { + iconUrl: string; + tooltip: string; + onClick: (event: AttachmentCardClickEvent) => void; + } + + interface AttachmentCardClickEvent { + getDownloadURL(): Promise; + } + + interface AttachmentsToolbarButtonDescriptor { + tooltip: string; + iconUrl: string; + onClick: (event: AttachmentsToolbarButtonEvent) => void; + } + + interface AttachmentsToolbarButtonEvent { + attachmentCardViews: AttachmentCardView[]; + } + + interface MessageViewLinkDescriptor { + text: string; + html: string; + element: HTMLElement; + href: string; + isInQuotedArea: boolean; + } + + interface MessageAttachmentIconDescriptor { + iconUrl: string; + iconClass?: string; + tooltip: string; + onClick?: () => void; + } + + interface MessageViewToolbarButtonDescriptor { + section: 'MORE'; + title: string; + iconUrl: string; + onClick: () => void; + iconClass?: string; + orderHint: number; + } + } + + export namespace Toolbars { + interface ToolbarsInstance { + registerThreadButton(toolbarButtonDescriptor: ToolbarButtonDescriptor): () => void; + + /** + * @deprecated. use registerThreadButton + * @param toolbarButtonDescriptor + */ + registerToolbarButtonForList(toolbarButtonDescriptor: ToolbarButtonDescriptor): () => void; + + /** + * @deprecated. use registerThreadButton + * @param toolbarButtonDescriptor + */ + registerToolbarButtonForThreadView(toolbarButtonDescriptor: ToolbarButtonDescriptor): () => void; + + addToolbarButtonForApp(appToolbarButtonDescriptor: AppToolbarButtonDescriptor): AppToolbarButtonView; + } + + interface ToolbarButtonDescriptor { + title: string; + onClick: (event: ToolbarButtonEvent) => void; + iconUrl?: string; + iconClass?: string; + positions?: ToolbarButtonPosition[]; + threadSection?: SectionNames; + listSection?: SectionNames; + hasDropdown?: boolean; + hideFor?: (routeView: Router.RouteView) => void; + orderHint?: number; + keyboardShortcutHandle?: Keyboard.KeyboardShortcutHandle; + } + + type ToolbarButtonPosition = 'THREAD' | 'ROW' | 'LIST'; + + interface ToolbarButtonEvent { + position: ToolbarButtonPosition; + selectedThreadRowViews: Lists.ThreadRowView[]; + selectedThreadViews: Conversations.ThreadView[]; + dropdown?: Common.DropdownView; + } + + interface AppToolbarButtonDescriptor { + title: string; + titleClass?: string; + iconUrl: string; + iconClass?: string; + onClick: (event: AppToolbarButtonEvent) => void; + arrowColor?: string; + } + + interface AppToolbarButtonView { + open(): void; + + close(): void; + + remove(): void; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + interface AppToolbarButtonEvent { + dropdown: Common.DropdownView; + } + + type SectionNames = 'INBOX_STATE' | 'METADATA_STATE' | 'OTHER'; + } + + export namespace Router { + interface RouterInstance { + createLink(routeID: string | NativeRouteIDs, params: RouteParams): string; + + goto(routeID: string | NativeRouteIDs, params: RouteParams): void; + + handleCustomRoute(routeID: string, handler: (customRouteView: CustomRouteView) => void): () => void; + + handleAllRoutes(handler: (routeView: RouteView) => void): () => void; + + handleListRoute(routeID: NativeListRouteIDs, handler: (listRouteView: ListRouteView) => void): () => void; + + handleCustomListRoute(routeID: string, handler: (offset: number, max: number) => CustomListDescriptor | Promise): () => void; + + getCurrentRouteView(): RouteView; + } + + interface CustomListDescriptor { + threads: Array; + total?: number; + hasMore?: boolean; + } + + interface ThreadDescriptor { + rfcMessageId?: string; + gmailThreadId?: string; + } + + interface RouteParams { + [key: number]: string | number; + + [key: string]: string | number; + } + + interface RouteView { + getRouteID(): string; + + getRouteType(): RouteTypes; + + getParams(): RouteParams; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + type RouteTypes = 'LIST' | 'THREAD' | 'SETTINGS' | 'CHAT' | 'CUSTOM' | 'UNKNOWN'; + + interface CustomRouteView extends RouteView { + getElement(): HTMLElement; + + setFullWidth(fullWidth: boolean): void; + } + + interface ListRouteView extends RouteView { + addCollapsibleSection(options: SectionDescriptor): CollapsibleSectionView; + + // addCollapsibleSection(options: Stream): CollapsibleSectionView; + + addSection(options: SectionDescriptor): SectionView; + + // addSection(options: Stream): SectionView; + + refresh(): void; + } + + interface SectionView { + remove(): void; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + interface CollapsibleSectionView extends SectionView { + setCollapsed(value: boolean): void; + + remove(): void; + + on(name: 'destroy' | 'expanded' | 'collapsed', cb: () => void): void; + } + + interface SectionDescriptor { + title: string; + subtitle?: string; + titleLinkText?: string; + onTitleLinkClick?: () => void; + hasDropdown?: boolean; + onDropdownClick?: (event: SectionDropdownClickEvent) => void; + tableRows?: RowDescriptor[]; + contentElement?: HTMLElement; + footerLinkText?: string; + onFooterLinkClick?: (event: any) => void; + } + + interface SectionDropdownClickEvent { + dropdown: Common.DropdownView; + } + + interface RowDescriptor { + title: string; + body: string; + shortDetailText: string; + isRead: string; + labels: Lists.LabelDescriptor[]; + iconUrl?: string; + iconClass?: string; + routeID?: string; + routeParams?: string[]; + onClick?: () => void; + } + + type NativeRouteIDs = + 'INBOX' | + 'ALL_MAIL' | + 'SENT' | + 'STARRED' | + 'DRAFTS' | + 'SNOOZED' | + 'DONE' | + 'REMINDERS' | + 'LABEL' | + 'TRASH' | + 'SPAM' | + 'IMPORTANT' | + 'SEARCH' | + 'THREAD' | + 'CHATS' | + 'CHAT' | + 'CONTACTS' | + 'CONTACT' | + 'SETTINGS' | + 'ANY_LIST'; + + type NativeListRouteIDs = + 'INBOX' + | 'ALL_MAIL' + | 'SENT' + | 'STARRED' + | 'DRAFTS' + | 'SNOOZED' + | 'DONE' + | 'REMINDERS' + | 'LABEL' + | 'TRASH' + | 'SPAM' + | 'IMPORTANT' + | 'SEARCH' + | 'ANY_LIST'; + } + + export namespace NavMenu { + interface NavMenuInstance { + addNavItem(navItemDescriptor: NavItemDescriptor): NavItemView; + } + + interface NavItemView { + addNavItem(navItemDescriptor: NavItemDescriptor): NavItemView; + + remove(): void; + + isCollapsed(): boolean; + + setCollapsed(collapseValue: boolean): void; + + on(name: 'destroy', cb: () => void): void; + + destroyed: boolean; + } + + interface NavItemDescriptor { + name: string; + routeID?: string; + routeParams?: object; + + onClick?: (event: { preventDefault(): void }) => void; + + orderHint?: number; + accessory?: CreateAccessoryDescriptor | IconButtonAccessoryDescriptor | DropdownButtonAccessoryDescriptor; + iconUrl?: string; + iconClass?: string; + backgroundColor?: string; + expanderForegroundColor?: string; + type?: NavItemTypes; + } + + interface CreateAccessoryDescriptor { + type: 'CREATE'; + onClick: () => void; + } + + interface IconButtonAccessoryDescriptor { + type: 'ICON_BUTTON'; + onClick: () => void; + iconUrl: string; + iconClass?: string; + } + + interface DropdownButtonAccessoryDescriptor { + type: 'DROPDOWN_BUTTON'; + buttonBackgroundColor: string; + buttonForegroundColor: string; + onClick: (event: DropdownButtonClickEvent) => void; + } + + interface DropdownButtonClickEvent { + dropdown: Common.DropdownView; + } + + type NavItemTypes = 'MANAGE' | 'NAVIGATION'; + } + + export namespace Widgets { + interface WidgetsInstance { + showModalView(options: ModalOptions): ModalView; + + showMoleView(options: MoleOptions): MoleView; + + showDrawerView(options: DrawerOptions): DrawerView; + } + + interface ModalOptions { + el: HTMLElement; + chrome?: boolean; + constrainTitleWidth?: boolean; + showCloseButton?: boolean; + title?: string; + buttons?: ModalButtonDescriptor[]; + } + + interface ModalButtonDescriptor { + text: string; + title: string; + onClick: () => void; + type?: 'PRIMARY_ACTION' | 'SECONDARY_ACTION'; + color?: string; + orderHint?: number; + } + + interface MoleOptions { + el: HTMLElement; + title?: string; + titleEl?: HTMLElement; + minimizedTitleEl?: HTMLElement; + className?: string; + titleButtons?: MoleButtonDescriptor[]; + chrome?: boolean; + } + + interface MoleButtonDescriptor { + title: string; + iconUrl: string; + iconClass?: string; + onClick: () => void; + } + + interface DrawerOptions { + el: HTMLElement; + chrome?: boolean; + title?: string; + composeView?: Compose.ComposeView; + closeWithCompose?: boolean; + } + + interface ModalView { + close(): void; + + on(name: 'destroyed', cb: () => void): void; + + destroyed: boolean; + } + + interface MoleView { + close(): void; + + setTitle(text: string): void; + + setMinimized(minimized: boolean): void; + + getMinimized(): boolean; + + on(name: 'destroyed' | 'minimize' | 'restore', cb: () => void): void; + + destroyed: boolean; + } + + interface DrawerView { + close(): void; + + associateComposeView(composeView: Compose.ComposeView, closeWithCompose: boolean): void; + + disassociateComposeView(): void; + + on(name: 'destroyed' | 'slideAnimationDone' | 'closing', cb: () => void): void; + + destroyed: boolean; + } + } + + export namespace ButterBar { + interface ButterBarInstance { + showMessage(options: MessageDescriptor): object; + + showLoading(): object; + + showError(options: MessageDescriptor): object; + + showSaving(options: SavingMessageDescriptor): object; + + hideMessage(messageKey: object | string): void; + + hideGmailMessage(): void; + } + + interface MessageDescriptorBase { + className?: string; + priority?: number; + time?: number; + hideOnViewChanged?: boolean; + persistent?: boolean; + messageKey?: object | string; + } + + interface MessageDescriptorText extends MessageDescriptorBase { + text: string; + } + + interface MessageDescriptorHtml extends MessageDescriptorBase { + html: string; + } + + interface MessageDescriptorHtmlElement extends MessageDescriptorBase { + el: HTMLElement; + } + + type MessageDescriptor = MessageDescriptorText | MessageDescriptorHtml | MessageDescriptorHtmlElement; + + interface SavingMessageDescriptorBase extends MessageDescriptorBase { + confirmationText?: string; + confirmationTime?: number; + showConfirmation?: boolean; + } + + interface SavingMessageDescriptorText extends SavingMessageDescriptorBase { + text: string; + } + + interface SavingMessageDescriptorHtml extends SavingMessageDescriptorBase { + html: string; + } + + interface SavingMessageDescriptorHtmlElement extends SavingMessageDescriptorBase { + el: HTMLElement; + } + + type SavingMessageDescriptor = + SavingMessageDescriptorText + | SavingMessageDescriptorHtml + | SavingMessageDescriptorHtmlElement; + } + + export namespace Search { + interface SearchInstance { + registerSearchSuggestionsProvider(handler: (query: string) => AutocompleteSearchResult[] | Promise): void; + + registerSearchQueryRewriter(rewriter: SearchQueryRewriter): void; + } + + interface AutocompleteSearchResultBase { + iconUrl?: string; + routeName?: string; + routeParams?: string[]; + externalURL?: string; + onClick?: () => void; + } + + interface AutocompleteSearchResultText extends AutocompleteSearchResultBase { + name: string; + description: string; + } + + interface AutocompleteSearchResultHtml extends AutocompleteSearchResultBase { + nameHTML: string; + descriptionHTML: string; + } + + type AutocompleteSearchResult = AutocompleteSearchResultText | AutocompleteSearchResultHtml; + + interface SearchQueryRewriter { + term: string; + termReplacer: () => string | Promise; + } + } + + export namespace User { + interface UserInstance { + getEmailAddress(): string; + + isUsingGmailMaterialUI(): boolean; + + isConversationViewDisabled(): boolean; + + getLanguage(): string; + + getAccountSwitcherContactList(): Common.Contact[]; + } + } + + export namespace Keyboard { + interface KeyboardInstance { + createShortcutHandle(keyboardShortcutDescriptor: KeyboardShortcutDescriptor): KeyboardShortcutHandle; + } + + interface KeyboardShortcutHandle { + remove(): void; + } + + interface KeyboardShortcutDescriptor { + chord: string; + description: string; + } + } + + export namespace Global { + interface GlobalInstance { + addSidebarContentPanel(contentPanelDescriptor: Conversations.ContentPanelDescriptor): Conversations.ContentPanelView; + } + } +} diff --git a/types/ion.rangeslider/tsconfig.json b/types/inboxsdk/tsconfig.json similarity index 86% rename from types/ion.rangeslider/tsconfig.json rename to types/inboxsdk/tsconfig.json index 1affa9f527..846443ce68 100644 --- a/types/ion.rangeslider/tsconfig.json +++ b/types/inboxsdk/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "ion.rangeslider-tests.ts" + "inboxsdk-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/inboxsdk/tslint.json b/types/inboxsdk/tslint.json new file mode 100644 index 0000000000..99ea174f67 --- /dev/null +++ b/types/inboxsdk/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } +} diff --git a/types/inquirer/index.d.ts b/types/inquirer/index.d.ts index d9258f7a48..d00c037c71 100644 --- a/types/inquirer/index.d.ts +++ b/types/inquirer/index.d.ts @@ -7,6 +7,7 @@ // Jason Dreyzehner // Synarque // Justin Rockwood +// Keith Kelly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -21,6 +22,13 @@ declare namespace inquirer { | Question | ReadonlyArray> | Rx.Observable>; + interface OutputStreamOption { + output: NodeJS.WriteStream + } + interface InputStreamOption { + input: NodeJS.ReadStream + } + type StreamOptions = InputStreamOption | OutputStreamOption | (InputStreamOption & OutputStreamOption); interface Inquirer { restoreDefaultPrompts(): void; @@ -32,8 +40,9 @@ declare namespace inquirer { registerPrompt(name: string, prompt: PromptModule): void; /** * Create a new self-contained prompt module. + * @param opt Object specifying input and output streams for the prompt */ - createPromptModule(): PromptModule; + createPromptModule(opt?: StreamOptions): PromptModule; /** * Public CLI helper interface * @param questions Questions settings array diff --git a/types/inquirer/inquirer-tests.ts b/types/inquirer/inquirer-tests.ts index aa545adae0..85a81d761e 100644 --- a/types/inquirer/inquirer-tests.ts +++ b/types/inquirer/inquirer-tests.ts @@ -626,3 +626,47 @@ async function testAsyncPrompt(): Promise { } testAsyncPrompt(); + +/** + * Different prompt output example + */ + +"use strict"; +//var inquirer = require("../lib/inquirer"); + +var questions = [ + { + type: "input", + name: "first_name", + message: "What's your first name", + prefix: "1 - " + }, + { + type: "input", + name: "last_name", + message: "What's your last name", + default: function() { + return "Doe"; + }, + suffix: "!!" + }, + { + type: "input", + name: "phone", + message: "What's your phone number", + validate: function(value: string): string | boolean { + var pass = value.match( + /^([01]{1})?[\-\.\s]?\(?(\d{3})\)?[\-\.\s]?(\d{3})[\-\.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i + ); + if (pass) { + return true; + } else { + return "Please enter a valid phone number"; + } + } + } +]; + +inquirer.createPromptModule({ output: process.stderr })(questions, function(answers) { + console.log(JSON.stringify(answers, null, " ")); +}); diff --git a/types/intercom-client/Scroll.d.ts b/types/intercom-client/Scroll.d.ts new file mode 100644 index 0000000000..2704a4cfbe --- /dev/null +++ b/types/intercom-client/Scroll.d.ts @@ -0,0 +1,3 @@ +export declare class Scroll { + +} \ No newline at end of file diff --git a/types/intercom-client/User.d.ts b/types/intercom-client/User.d.ts new file mode 100644 index 0000000000..880b8b5681 --- /dev/null +++ b/types/intercom-client/User.d.ts @@ -0,0 +1,85 @@ +import {Company} from "intercom-client"; + +export type UserIdentifier = { "id": string } | { "user_id": string } | { "email": string } + +export interface Avatar { + "type": "avatar", + "image_url": string | null +} + +export interface SocialProfile { + "name": "Twitter", + readonly "id": string | null, + "username": string | null, + "url": string | null +} + +export interface Segment { + readonly "id": string +} + +export interface Tag { + readonly "id": string +} + +export interface LocationData { + "type": "location_data", + "city_name": string | null, + "continent_code": string | null, + "country_code": string | null, + "country_name": string | null, + "latitude": number | null, + "longitude": number | null, + "postal_code": string | null, + "region_name": string | null, + "timezone": string | null +} + +export interface User { + "type": "user" | "contact", + readonly "id": string, + "user_id": string | null, + "email": string | null, + "app_id"?: string, + "phone": string | null, + "name": string | null, + readonly "updated_at": number, + "last_seen_ip": string | null, + "unsubscribed_from_emails": boolean, + "last_request_at": number | null, + "signed_up_at": number | null, + readonly "created_at": number, + "session_count": number, + "user_agent_data": string | null, + "pseudonym": string | null, + "anonymous": boolean, + "custom_attributes": { + [key: string]: any + }, + "avatar": Avatar, + "location_data": LocationData | {}, + "social_profiles": { + "type": "social_profile.list", + "social_profiles": SocialProfile[] + }, + "companies": { + "type": "company.list", + "companies": Company[] + }, + "segments": { + "type": "segment.list", + "segments": Segment[] + + }, + "tags": { + "type": "tag.list", + "tags": Tag[] + } +} + +export interface List { + "type": "user.list", + "total_count": number, + "users": User[], + "pages": { "next"?: string, "page": number, "per_page": number, "total_pages": number } +} \ No newline at end of file diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts index b68dc87e71..4d9e572da0 100644 --- a/types/intercom-client/index.d.ts +++ b/types/intercom-client/index.d.ts @@ -1,7 +1,10 @@ // Type definitions for intercom-client 2.9 // Project: https://github.com/intercom/intercom-node -// Definitions by: Jinesh Shah +// Definitions by: Jinesh Shah , Josef Hornych // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +import { List as UserList, User, UserIdentifier } from './User'; +import { Scroll } from './Scroll'; export interface IdentityVerificationOptions { secretKey: string; @@ -11,3 +14,32 @@ export interface IdentityVerificationOptions { export const IdentityVerification: { userHash(opts: IdentityVerificationOptions): string; }; + +export class Client { + constructor(auth: { token: string } | { appId: string, appApiKey: string }); + constructor(username: string, password: string); + + users: Users; +} + +export interface Company { + readonly "id": string; +} + +export class Users { + create(user: Partial): Promise; + + update(user: UserIdentifier & Partial): Promise; + + find(identifier: UserIdentifier): Promise; + + list(): Promise; + + listBy(params: {tag_id: string, segment_id: string}): Promise; + + scroll: Scroll; + + archive(): Promise; + + requestPermanentDeletion(): Promise<{id: number}>; +} diff --git a/types/intercom-web/index.d.ts b/types/intercom-web/index.d.ts index 563d241c31..eb2157d7c7 100755 --- a/types/intercom-web/index.d.ts +++ b/types/intercom-web/index.d.ts @@ -21,7 +21,7 @@ declare namespace Intercom_ { activator?: string; }; company?: { - id: string|number, + id: string | number, name: string, created_at: number, plan?: string, @@ -33,16 +33,17 @@ declare namespace Intercom_ { } type IntercomCommand = 'boot' - |'shutdown' - |'update' - |'hide' - |'show' - |'showMessages' - |'showNewMessage' - |'onHide' - |'onShow' - |'onActivatorClick' - |'trackEvent'; + | 'shutdown' + | 'update' + | 'hide' + | 'show' + | 'showMessages' + | 'showNewMessage' + | 'onHide' + | 'onShow' + | 'onUnreadCountChange' + | 'onActivatorClick' + | 'trackEvent'; interface IntercomStatic { (command: 'boot', param: IntercomSettings): void; @@ -51,6 +52,7 @@ declare namespace Intercom_ { (command: 'showNewMessage', param?: string): void; (command: 'onHide' | 'onShow' | 'onActivatorClick', param?: () => void): void; (command: 'trackEvent', tag?: string, metadata?: any): void; + (command: 'onUnreadCountChange', cb: (unreadCount: number) => void): void; (command: IntercomCommand, param1?: any, param2?: any): void; } } diff --git a/types/intercom-web/intercom-web-tests.ts b/types/intercom-web/intercom-web-tests.ts index b07013322d..425aa74be4 100755 --- a/types/intercom-web/intercom-web-tests.ts +++ b/types/intercom-web/intercom-web-tests.ts @@ -23,6 +23,7 @@ Intercom('showMessages'); Intercom('showNewMessage'); Intercom('showNewMessage', 'pre-populated content'); Intercom('onHide', () => { /* Do stuff */ }); +Intercom('onUnreadCountChange', (unreadCount: number) => { /* Do stuff */ }); Intercom('onActivatorClick', () => { /* Do stuff */ }); Intercom('trackEvent', 'invited-friend'); diff --git a/types/intl-locales-supported/index.d.ts b/types/intl-locales-supported/index.d.ts new file mode 100644 index 0000000000..62d88c0e54 --- /dev/null +++ b/types/intl-locales-supported/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for intl-locales-supported 1.0 +// Project: https://github.com/yahoo/intl-locales-supported +// Definitions by: Edward Sammut Alessi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = areIntlLocalesSupported; + +declare function areIntlLocalesSupported(locales: string | string[]): boolean; diff --git a/types/intl-locales-supported/intl-locales-supported-tests.ts b/types/intl-locales-supported/intl-locales-supported-tests.ts new file mode 100644 index 0000000000..9d63d0e9ec --- /dev/null +++ b/types/intl-locales-supported/intl-locales-supported-tests.ts @@ -0,0 +1,4 @@ +import areIntlLocalesSupported = require("intl-locales-supported"); + +areIntlLocalesSupported("en-GB"); +areIntlLocalesSupported([ "en-GB", "en-US" ]); diff --git a/types/intl-locales-supported/tsconfig.json b/types/intl-locales-supported/tsconfig.json new file mode 100644 index 0000000000..f528331ae4 --- /dev/null +++ b/types/intl-locales-supported/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "intl-locales-supported-tests.ts" + ] +} diff --git a/types/intl-locales-supported/tslint.json b/types/intl-locales-supported/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/intl-locales-supported/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ion-rangeslider/index.d.ts b/types/ion-rangeslider/index.d.ts new file mode 100644 index 0000000000..9788741b77 --- /dev/null +++ b/types/ion-rangeslider/index.d.ts @@ -0,0 +1,81 @@ +// Type definitions for ion-rangeslider 2.2 +// Project: https://github.com/IonDen/ion.rangeSlider/ +// Definitions by: Karel van de Plassche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html +// Parsed using https://github.com/Karel-van-de-Plassche/ion-rangeslider-parser.git +// Based on global-modifying module template file + +declare global { + interface JQuery { + destroy(): void; + ionRangeSlider(options?: IonRangeSliderOptions): JQuery; + reset(): void; + update(option: IonRangeSliderOptions): void; + } +} + +export interface IonRangeSliderOptions { + type?: string; // Choose slider type, could be `single` - for one handle, or `double` for two handles [Default: single] + min?: number; // Set slider minimum value [Default: 10] + max?: number; // Set slider maximum value [Default: 100] + from?: number; // Set start position for left handle (or for single handle) [Default: min] + to?: number; // Set start position for right handle [Default: max] + step?: number; // Set sliders step. Always > 0. Could be fractional [Default: 1] + min_interval?: number; // Set minimum diapason between sliders. Only for **double** type [Default: -] + max_interval?: number; // Set minimum maximum between sliders. Only for **double** type [Default: -] + drag_interval?: boolean; // Allow user to drag whole range. Only for **double** type [Default: false] + values?: any[]; // Set up your own array of possible slider values. They could be numbers or strings. If the values array is set up, min, max and step param, can no longer be changed [Default: []] + from_fixed?: boolean; // Fix position of left (or single) handle [Default: false] + from_min?: number; // Set minimum limit for left (or single) handle [Default: min] + from_max?: number; // Set maximum limit for left (or single) handle [Default: max] + from_shadow?: boolean; // Highlight the limits for left handle [Default: false] + to_fixed?: boolean; // Fix position of right handle [Default: false] + to_min?: number; // Set minimum limit for right handle [Default: min] + to_max?: number; // Set maximum limit for right handle [Default: max] + to_shadow?: boolean; // Highlight the right handle [Default: false] + prettify_enabled?: boolean; // Improve readability of long numbers: 10000000 → 10 000 000 [Default: true] + prettify_separator?: string; // Set up your own separator for long numbers: 10000000 → 10,000,000 etc. [Default: ] + prettify?: (num: number) => string; // Set up your own prettify function. Can be anything. For example, you can set up unix time as slider values and than transform them to cool looking dates [Default: null] + force_edges?: boolean; // Sliders handles and tooltips will be always inside it's container [Default: false] + keyboard?: boolean; // Activates keyboard controls. Move left: ←, ↓, A, S. Move right: →, ↑, W, D. [Default: true] + grid?: boolean; // Enables grid of values above the slider [Default: true] + grid_margin?: boolean; // Set left and right grid gaps [Default: true] + grid_num?: number; // Number of grid units [Default: 4] + grid_snap?: boolean; // Snap grid to sliders step (step param). If activated, grid_num will not be used. Max steps = 50 [Default: false] + hide_min_max?: boolean; // Hides **min** and **max** labels [Default: false] + hide_from_to?: boolean; // Hides **from** and **to** labels [Default: false] + prefix?: string; // Set prefix for values. Will be set up right before the number: **$**100 [Default: ] + postfix?: string; // Set postfix for values. Will be set up right after the number: 100**k** [Default: ] + max_postfix?: string; // Special postfix, used only for maximum value. Will be showed after handle will reach maximum right position. For example **0 — 100+** [Default: ] + decorate_both?: boolean; // Used for **double** type and only if prefix or postfix was set up. Determine how to decorate close values. For example: **$10k — $100k** or **$10 — 100k** [Default: true] + values_separator?: string; // Set your own separator for close values. Used for **double** type. Default: **10 — 100**. Or you may set: **10 to 100, 10 + 100, 10 → 100** etc. [Default: - ] + input_values_separator?: string; // Separator for **double** values in input value property. ` [Default: ; ] + disable?: boolean; // Locks slider and makes it inactive. Input is disabled too. Invisible to forms [Default: false] + block?: boolean; // Locks slider and makes it inactive. Input is NOT disabled. Can be send with forms [Default: false] + extra_classes?: string; // Traverse extra CSS-classes to sliders container [Default: —] + scope?: any; // Scope for callbacks. Pass any object [Default: null] + onStart?: (obj: IonRangeSliderEvent) => void; // Callback. Is called on slider start. Gets all slider data as a 1st attribute [Default: null] + onChange?: (obj: IonRangeSliderEvent) => void; // Callback. IS called on each values change. Gets all slider data as a 1st attribute [Default: null] + onFinish?: (obj: IonRangeSliderEvent) => void; // Callback. Is called when user releases handle. Gets all slider data as a 1st attribute [Default: null] + onUpdate?: (obj: IonRangeSliderEvent) => void; // Callback. Is called when slider is modified by external methods `update` or `reset [Default: null] +} + +export interface IonRangeSliderEvent { + input: JQuery; // jQuery-link to input + slider: JQuery; // jQuery-link to sliders container + min: number; // MIN value + max: number; // MAX values + from: number; // FROM value + from_percent: number; // FROM value in percents + from_value: number; // FROM index in values array (if used) + to: number; // TO value + to_percent: number; // TO value in percents + to_value: number; // TO index in values array (if used) + min_pretty: string; // MIN prettified (if used) + max_pretty: string; // MAX prettified (if used) + from_pretty: string; // FROM prettified (if used) + to_pretty: string; // TO prettified (if used) +} diff --git a/types/ion.rangeslider/ion.rangeslider-tests.ts b/types/ion-rangeslider/ion-rangeslider-tests.ts similarity index 67% rename from types/ion.rangeslider/ion.rangeslider-tests.ts rename to types/ion-rangeslider/ion-rangeslider-tests.ts index e60287feb3..e3bffdd4b6 100644 --- a/types/ion.rangeslider/ion.rangeslider-tests.ts +++ b/types/ion-rangeslider/ion-rangeslider-tests.ts @@ -1,6 +1,5 @@ /// - -var sliderInputElement = $(''); +let sliderInputElement = $(''); sliderInputElement.ionRangeSlider({ decorate_both: true, disable: false, @@ -18,29 +17,18 @@ sliderInputElement.ionRangeSlider({ hide_from_to: false, hide_min_max: false, keyboard: true, - keyboard_step: 1, max: 100, max_interval: 5, max_postfix: "+", min: 10, min_interval: 5, - onChange: function (obj) { - console.log(obj); - }, - onFinish: function (obj) { - console.log(obj); - }, - onStart: function (obj) { - console.log(obj); - }, - onUpdate: function (obj) { - console.log(obj); - }, + onChange: obj => console.log(obj), + onFinish: obj => console.log(obj), + onStart: obj => console.log(obj), + onUpdate: obj => console.log(obj), postfix: ".00", prefix: "$", - prettify: function(num) { - return String(num); - }, + prettify: (num: number) => (String(num)), prettify_enabled: true, prettify_separator: ",", step: 10, @@ -48,8 +36,7 @@ sliderInputElement.ionRangeSlider({ to_fixed: false, to_max: 100, to_min: 60, - to_shadowed: false, - type: "double", + type: "double", values: ["a", "b", "c"], values_separator: "," }); diff --git a/types/ion-rangeslider/tsconfig.json b/types/ion-rangeslider/tsconfig.json new file mode 100644 index 0000000000..2c77a196bd --- /dev/null +++ b/types/ion-rangeslider/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ion-rangeslider-tests.ts" + ], + "exclude": [ + "util/**/*", + ".gitignore" + ] +} diff --git a/types/ion-rangeslider/tslint.json b/types/ion-rangeslider/tslint.json new file mode 100644 index 0000000000..64aace11d6 --- /dev/null +++ b/types/ion-rangeslider/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": false + } +} diff --git a/types/ion.rangeslider/v1/index.d.ts b/types/ion-rangeslider/v1/index.d.ts similarity index 91% rename from types/ion.rangeslider/v1/index.d.ts rename to types/ion-rangeslider/v1/index.d.ts index d819f46964..2ce88db6d4 100644 --- a/types/ion.rangeslider/v1/index.d.ts +++ b/types/ion-rangeslider/v1/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for for Ion.RangeSlider 1.9.1 +// Type definitions for ion-rangeslider 1.9 // Project: https://github.com/IonDen/ion.rangeSlider/ // Definitions by: Douglas Eichelberger +// Karel van de Plassche // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/ion.rangeslider/v1/ion.rangeslider-tests.ts b/types/ion-rangeslider/v1/ion-rangeslider-tests.ts similarity index 100% rename from types/ion.rangeslider/v1/ion.rangeslider-tests.ts rename to types/ion-rangeslider/v1/ion-rangeslider-tests.ts diff --git a/types/ion.rangeslider/v1/tsconfig.json b/types/ion-rangeslider/v1/tsconfig.json similarity index 83% rename from types/ion.rangeslider/v1/tsconfig.json rename to types/ion-rangeslider/v1/tsconfig.json index c63da8c0e1..32d3577e6f 100644 --- a/types/ion.rangeslider/v1/tsconfig.json +++ b/types/ion-rangeslider/v1/tsconfig.json @@ -15,8 +15,8 @@ ], "types": [], "paths": { - "ion.rangeslider": [ - "ion.rangeslider/v1" + "ion-rangeslider": [ + "ion-rangeslider/v1" ] }, "noEmit": true, @@ -24,6 +24,6 @@ }, "files": [ "index.d.ts", - "ion.rangeslider-tests.ts" + "ion-rangeslider-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/ion.rangeslider/tslint.json b/types/ion-rangeslider/v1/tslint.json similarity index 100% rename from types/ion.rangeslider/tslint.json rename to types/ion-rangeslider/v1/tslint.json diff --git a/types/ion.rangeslider/index.d.ts b/types/ion.rangeslider/index.d.ts deleted file mode 100644 index 21d99c5c6d..0000000000 --- a/types/ion.rangeslider/index.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Type definitions for for Ion.RangeSlider 2.0.2 -// Project: https://github.com/IonDen/ion.rangeSlider/ -// Definitions by: Sixin Li -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html - -interface JQuery { - destroy(): void; - ionRangeSlider(): JQuery; - ionRangeSlider(options: IonRangeSliderOptions): JQuery; - reset(): void; - update(option: IonRangeSliderOptions): void; -} - -interface IonRangeSliderOptions { - decorate_both?: boolean; - disable?: boolean; - drag_interval?: boolean; - force_edges?: boolean; - from?: number; - from_fixed?: boolean; - from_max?: number; - from_min?: number; - from_shadow?: boolean; - grid?: boolean; - grid_margin?: boolean; - grid_num?: number; - grid_snap?: boolean; - hide_from_to?: boolean; - hide_min_max?: boolean; - keyboard?: boolean; - keyboard_step?: number; - max?: number; - max_interval?: number; - max_postfix?: string; - min?: number; - min_interval?: number; - onChange?: (obj: IonRangeSliderEvent) => void; - onFinish?: (obj: IonRangeSliderEvent) => void; - onStart?: (obj: IonRangeSliderEvent) => void; - onUpdate?: (obj: IonRangeSliderEvent) => void; - postfix?: string; - prefix?: string; - prettify?: (num: number) => string; - prettify_enabled?: boolean; - prettify_separator?: string; - step?: number; - to?: number; - to_fixed?: boolean; - to_max?: number; - to_min?: number; - to_shadowed?: boolean; - type?: string; - values?: any[]; - values_separator?: string; -} - -interface IonRangeSliderEvent { - from: number; - from_precent: number; - from_value: any; - input: JQuery; - max: number; - min: number; - slider: JQuery; - to: number; - to_precent: number; - to_value: any; -} diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 84ca51982a..3ad2f6aeb2 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -16,6 +16,7 @@ /// import Promise = require('bluebird'); +import tls = require('tls'); interface RedisStatic { new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; @@ -827,9 +828,7 @@ declare namespace IORedis { */ autoResendUnfulfilledCommands?: boolean; lazyConnect?: boolean; - tls?: { - ca: Buffer; - }; + tls?: tls.ConnectionOptions; sentinels?: Array<{ host: string; port: number; }>; name?: string; /** diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index e8e32062dc..7dd98879a5 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -29,7 +29,10 @@ new Redis({ password: 'auth', db: 0, retryStrategy() { return false; }, - showFriendlyErrorStack: true + showFriendlyErrorStack: true, + tls: { + servername: 'tlsservername' + } }); const pub = new Redis(); diff --git a/types/is-touch-device/index.d.ts b/types/is-touch-device/index.d.ts new file mode 100644 index 0000000000..7a17cbea63 --- /dev/null +++ b/types/is-touch-device/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for is-touch-device 1.0 +// Project: https://github.com/airbnb/is-touch-device +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function isTouchDevice(): boolean; diff --git a/types/is-touch-device/is-touch-device-tests.ts b/types/is-touch-device/is-touch-device-tests.ts new file mode 100644 index 0000000000..5ae2e1eff5 --- /dev/null +++ b/types/is-touch-device/is-touch-device-tests.ts @@ -0,0 +1,3 @@ +import isTouchDevice from 'is-touch-device'; + +if (isTouchDevice()) {} diff --git a/types/is-touch-device/tsconfig.json b/types/is-touch-device/tsconfig.json new file mode 100644 index 0000000000..4ab8fbd5cb --- /dev/null +++ b/types/is-touch-device/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-touch-device-tests.ts" + ] +} diff --git a/types/is-touch-device/tslint.json b/types/is-touch-device/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-touch-device/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/istanbul-lib-instrument/index.d.ts b/types/istanbul-lib-instrument/index.d.ts index e1d4e813f9..1b749a893c 100644 --- a/types/istanbul-lib-instrument/index.d.ts +++ b/types/istanbul-lib-instrument/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/istanbuljs/istanbuljs // Definitions by: Jason Cheatham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import { FileCoverage, FileCoverageData, Range } from 'istanbul-lib-coverage'; import { RawSourceMap } from 'source-map'; diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index af86996795..d11f79df64 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 23.0 +// Type definitions for Jest 23.1 // Project: http://facebook.github.io/jest/ // Definitions by: Asana // Ivo Stratev @@ -10,9 +10,11 @@ // Waseem Dahman // Jamie Mason // Douglas Duteil -// Ahn +// Ahn // Josh Goldberg -// Bradley Ayers +// Jeff Lau +// Andrew Makarov +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -207,6 +209,14 @@ declare namespace jest { readonly name: string; } + interface Each { + (cases: any[]): (name: string, fn: (...args: any[]) => any) => void; + (strings: TemplateStringsArray, ...placeholders: any[]): ( + name: string, + fn: (arg: any) => any + ) => void; + } + /** * Creates a test closure */ @@ -225,6 +235,7 @@ declare namespace jest { only: It; skip: It; concurrent: It; + each: Each; } interface Describe { @@ -232,6 +243,7 @@ declare namespace jest { (name: number | string | Function | FunctionLike, fn: EmptyFunction): void; only: Describe; skip: Describe; + each: Each; } interface MatcherUtils { @@ -357,10 +369,22 @@ declare namespace jest { } interface Matchers { + /** + * Ensures the last call to a mock function was provided specific args. + */ + lastCalledWith(...args: any[]): R; + /** + * Ensure that the last call to a mock function has returned a specified value. + */ + lastReturnedWith(value: any): R; /** * If you know how to test something, `.not` lets you test its opposite. */ not: Matchers; + /** + * Ensure that the nth call to a mock function has returned a specified value. + */ + nthReturnedWith(n: number, value: any): R; /** * Use resolves to unwrap the value of a fulfilled promise so any other * matcher can be chained. If the promise is rejected the assertion fails. @@ -371,7 +395,6 @@ declare namespace jest { * If the promise is fulfilled the assertion fails. */ rejects: Matchers>; - lastCalledWith(...args: any[]): R; /** * Checks that a value is what you expect. It uses `===` to check strict equality. * Don't use `toBe` with floating-point numbers. @@ -468,17 +491,46 @@ declare namespace jest { * Ensure that a mock function is called with specific arguments. */ toHaveBeenCalledWith(...params: any[]): R; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + */ + toHaveBeenNthCalledWith(nthCall: number, ...params: any[]): R; /** * If you have a mock function, you can use `.toHaveBeenLastCalledWith` * to test what arguments it was last called with. */ toHaveBeenLastCalledWith(...params: any[]): R; + /** + * Use to test the specific value that a mock function last returned. + * If the last call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + */ + toHaveLastReturnedWith(expected: any): R; /** * Used to check that an object has a `.length` property * and it is set to a certain numeric value. */ toHaveLength(expected: number): R; + /** + * Use to test the specific value that a mock function returned for the nth call. + * If the nth call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + */ + toHaveNthReturnedWith(nthCall: number, expected: any): R; toHaveProperty(propertyPath: string | any[], value?: any): R; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + */ + toHaveReturned(): R; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + */ + toHaveReturnedTimes(expected: number): R; + /** + * Use to ensure that a mock function returned a specific value. + */ + toHaveReturnedWith(expected: any): R; /** * Check that a string matches a regular expression. */ @@ -492,6 +544,22 @@ declare namespace jest { * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ toMatchSnapshot(snapshotName?: string): R; + /** + * Ensure that a mock function has returned (as opposed to thrown) at least once. + */ + toReturn(): R; + /** + * Ensure that a mock function has returned (as opposed to thrown) a specified number of times. + */ + toReturnTimes(count: number): R; + /** + * Ensure that a mock function has returned a specified value at least once. + */ + toReturnWith(value: any): R; + /** + * Use to test that objects have the same types as well as structure. + */ + toStrictEqual(expected: {}): R; /** * Used to test that a function throws when it is called. */ @@ -550,9 +618,29 @@ declare namespace jest { mockRejectedValueOnce(value: any): Mock; } + /** + * Represents the result of a single call to a mock function. + */ + interface MockResult { + /** + * True if the function threw. + * False if the function returned. + */ + isThrow: boolean; + /** + * The value that was either thrown or returned by the function. + */ + value: any; + } + interface MockContext { calls: any[][]; instances: T[]; + invocationCallOrder: number[]; + /** + * List of results of calls to the mock function. + */ + results: MockResult[]; } } @@ -795,6 +883,164 @@ declare namespace jest { type SnapshotUpdateState = 'all' | 'new' | 'none'; + interface DefaultOptions { + automock: boolean; + bail: boolean; + browser: boolean; + cache: boolean; + cacheDirectory: Path; + changedFilesWithAncestor: boolean; + clearMocks: boolean; + collectCoverage: boolean; + collectCoverageFrom: Maybe; + coverageDirectory: Maybe; + coveragePathIgnorePatterns: string[]; + coverageReporters: string[]; + coverageThreshold: Maybe<{global: {[key: string]: number}}>; + errorOnDeprecated: boolean; + expand: boolean; + filter: Maybe; + forceCoverageMatch: Glob[]; + globals: ConfigGlobals; + globalSetup: Maybe; + globalTeardown: Maybe; + haste: HasteConfig; + detectLeaks: boolean; + detectOpenHandles: boolean; + moduleDirectories: string[]; + moduleFileExtensions: string[]; + moduleNameMapper: {[key: string]: string}; + modulePathIgnorePatterns: string[]; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + preset: Maybe; + projects: Maybe>; + resetMocks: boolean; + resetModules: boolean; + resolver: Maybe; + restoreMocks: boolean; + rootDir: Maybe; + roots: Maybe; + runner: string; + runTestsByPath: boolean; + setupFiles: Path[]; + setupTestFrameworkScriptFile: Maybe; + skipFilter: boolean; + snapshotSerializers: Path[]; + testEnvironment: string; + testEnvironmentOptions: object; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string; + testResultsProcessor: Maybe; + testRunner: Maybe; + testURL: string; + timers: 'real' | 'fake'; + transform: Maybe<{[key: string]: string}>; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; + useStderr: boolean; + verbose: Maybe; + watch: boolean; + watchman: boolean; + } + + interface InitialOptions { + automock?: boolean; + bail?: boolean; + browser?: boolean; + cache?: boolean; + cacheDirectory?: Path; + clearMocks?: boolean; + changedFilesWithAncestor?: boolean; + changedSince?: string; + collectCoverage?: boolean; + collectCoverageFrom?: Glob[]; + collectCoverageOnlyFrom?: {[key: string]: boolean}; + coverageDirectory?: string; + coveragePathIgnorePatterns?: string[]; + coverageReporters?: string[]; + coverageThreshold?: {global: {[key: string]: number}}; + detectLeaks?: boolean; + detectOpenHandles?: boolean; + displayName?: string; + expand?: boolean; + filter?: Path; + findRelatedTests?: boolean; + forceCoverageMatch?: Glob[]; + forceExit?: boolean; + json?: boolean; + globals?: ConfigGlobals; + globalSetup?: Maybe; + globalTeardown?: Maybe; + haste?: HasteConfig; + reporters?: Array; + logHeapUsage?: boolean; + lastCommit?: boolean; + listTests?: boolean; + mapCoverage?: boolean; + moduleDirectories?: string[]; + moduleFileExtensions?: string[]; + moduleLoader?: Path; + moduleNameMapper?: {[key: string]: string}; + modulePathIgnorePatterns?: string[]; + modulePaths?: string[]; + name?: string; + noStackTrace?: boolean; + notify?: boolean; + notifyMode?: string; + onlyChanged?: boolean; + outputFile?: Path; + passWithNoTests?: boolean; + preprocessorIgnorePatterns?: Glob[]; + preset?: Maybe; + projects?: Glob[]; + replname?: Maybe; + resetMocks?: boolean; + resetModules?: boolean; + resolver?: Maybe; + restoreMocks?: boolean; + rootDir?: Path; + roots?: Path[]; + runner?: string; + runTestsByPath?: boolean; + scriptPreprocessor?: string; + setupFiles?: Path[]; + setupTestFrameworkScriptFile?: Path; + silent?: boolean; + skipFilter?: boolean; + skipNodeResolution?: boolean; + snapshotSerializers?: Path[]; + errorOnDeprecated?: boolean; + testEnvironment?: string; + testEnvironmentOptions?: object; + testFailureExitCode?: string | number; + testLocationInResults?: boolean; + testMatch?: Glob[]; + testNamePattern?: string; + testPathDirs?: Path[]; + testPathIgnorePatterns?: string[]; + testRegex?: string; + testResultsProcessor?: Maybe; + testRunner?: string; + testURL?: string; + timers?: 'real' | 'fake'; + transform?: {[key: string]: string}; + transformIgnorePatterns?: Glob[]; + watchPathIgnorePatterns?: string[]; + unmockedModulePathPatterns?: string[]; + updateSnapshot?: boolean; + useStderr?: boolean; + verbose?: Maybe; + watch?: boolean; + watchAll?: boolean; + watchman?: boolean; + watchPlugins?: string[]; + } + interface GlobalConfig { bail: boolean; collectCoverage: boolean; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index a90a7a9e5a..7d10075262 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -1,733 +1,1058 @@ -// TODO: Avoid requiring things that don't exist. -declare var require: { - (s: string): any; - requireActual(s: string): any; - requireMock(s: string): any; +/* Lifecycle events */ + +beforeAll(() => {}); +beforeAll((done: jest.DoneCallback) => {}); +beforeAll((done: jest.DoneCallback) => done.fail(), 9001); + +beforeEach(() => {}); +beforeEach((done: jest.DoneCallback) => {}); +beforeEach((done: jest.DoneCallback) => done.fail(), 9001); + +afterAll(() => {}); +afterAll((done: jest.DoneCallback) => {}); +afterAll((done: jest.DoneCallback) => done.fail(), 9001); + +afterEach(() => {}); +afterEach((done: jest.DoneCallback) => {}); +afterEach((done: jest.DoneCallback) => done.fail(), 9001); + +/* describe */ + +describe(0, () => {}); +describe("name", () => {}); +describe(() => {}, () => {}); +describe({ name: "name" }, () => {}); + +describe.only(0, () => {}); +describe.only("name", () => {}); +describe.only(() => {}, () => {}); +describe.only({ name: "name" }, () => {}); + +describe.skip(0, () => {}); +describe.skip("name", () => {}); +describe.skip(() => {}, () => {}); +describe.skip({ name: "name" }, () => {}); + +fdescribe(0, () => {}); +fdescribe("name", () => {}); +fdescribe(() => {}, () => {}); +fdescribe({ name: "name" }, () => {}); + +fdescribe.only(0, () => {}); +fdescribe.only("name", () => {}); +fdescribe.only(() => {}, () => {}); +fdescribe.only({ name: "name" }, () => {}); + +fdescribe.skip(0, () => {}); +fdescribe.skip("name", () => {}); +fdescribe.skip(() => {}, () => {}); +fdescribe.skip({ name: "name" }, () => {}); + +xdescribe(0, () => {}); +xdescribe("name", () => {}); +xdescribe(() => {}, () => {}); +xdescribe({ name: "name" }, () => {}); + +xdescribe.only(0, () => {}); +xdescribe.only("name", () => {}); +xdescribe.only(() => {}, () => {}); +xdescribe.only({ name: "name" }, () => {}); + +xdescribe.skip(0, () => {}); +xdescribe.skip("name", () => {}); +xdescribe.skip(() => {}, () => {}); +xdescribe.skip({ name: "name" }, () => {}); + +/* it */ + +it("name", () => {}); +it("name", async () => {}); +it("name", () => {}, 9001); +it("name", async () => {}, 9001); +it("name", (callback: jest.DoneCallback) => {}, 9001); + +it.only("name", () => {}); +it.only("name", async () => {}); +it.only("name", () => {}, 9001); +it.only("name", async () => {}, 9001); +it.only("name", (callback: jest.DoneCallback) => {}, 9001); + +it.skip("name", () => {}); +it.skip("name", async () => {}); +it.skip("name", () => {}, 9001); +it.skip("name", async () => {}, 9001); +it.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +it.concurrent("name", () => {}); +it.concurrent("name", async () => {}); +it.concurrent("name", () => {}, 9001); +it.concurrent("name", async () => {}, 9001); +it.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +fit("name", () => {}); +fit("name", async () => {}); +fit("name", () => {}, 9001); +fit("name", async () => {}, 9001); +fit("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.only("name", () => {}); +fit.only("name", async () => {}); +fit.only("name", () => {}, 9001); +fit.only("name", async () => {}, 9001); +fit.only("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.skip("name", () => {}); +fit.skip("name", async () => {}); +fit.skip("name", () => {}, 9001); +fit.skip("name", async () => {}, 9001); +fit.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.concurrent("name", () => {}); +fit.concurrent("name", async () => {}); +fit.concurrent("name", () => {}, 9001); +fit.concurrent("name", async () => {}, 9001); +fit.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +xit("name", () => {}); +xit("name", async () => {}); +xit("name", () => {}, 9001); +xit("name", async () => {}, 9001); +xit("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.only("name", () => {}); +xit.only("name", async () => {}); +xit.only("name", () => {}, 9001); +xit.only("name", async () => {}, 9001); +xit.only("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.skip("name", () => {}); +xit.skip("name", async () => {}); +xit.skip("name", () => {}, 9001); +xit.skip("name", async () => {}, 9001); +xit.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.concurrent("name", () => {}); +xit.concurrent("name", async () => {}); +xit.concurrent("name", () => {}, 9001); +xit.concurrent("name", async () => {}, 9001); +xit.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +test("name", () => {}); +test("name", async () => {}); +test("name", () => {}, 9001); +test("name", async () => {}, 9001); +test("name", (callback: jest.DoneCallback) => {}, 9001); + +test.only("name", () => {}); +test.only("name", async () => {}); +test.only("name", () => {}, 9001); +test.only("name", async () => {}, 9001); +test.only("name", (callback: jest.DoneCallback) => {}, 9001); + +test.skip("name", () => {}); +test.skip("name", async () => {}); +test.skip("name", () => {}, 9001); +test.skip("name", async () => {}, 9001); +test.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +test.concurrent("name", () => {}); +test.concurrent("name", async () => {}); +test.concurrent("name", () => {}, 9001); +test.concurrent("name", async () => {}, 9001); +test.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest("name", () => {}); +xtest("name", async () => {}); +xtest("name", () => {}, 9001); +xtest("name", async () => {}, 9001); +xtest("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.only("name", () => {}); +xtest.only("name", async () => {}); +xtest.only("name", () => {}, 9001); +xtest.only("name", async () => {}, 9001); +xtest.only("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.skip("name", () => {}); +xtest.skip("name", async () => {}); +xtest.skip("name", () => {}, 9001); +xtest.skip("name", async () => {}, 9001); +xtest.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.concurrent("name", () => {}); +xtest.concurrent("name", async () => {}); +xtest.concurrent("name", () => {}, 9001); +xtest.concurrent("name", async () => {}, 9001); +xtest.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +/* Done callbacks */ + +describe("", () => { + it("", (callback: jest.DoneCallback): void => { + callback(); + callback(""); + callback("", 3); + callback.fail(); + callback.fail("error"); + callback.fail({ message: "message" }); + }); +}); + +/* NodeRequire interface (require extensions) */ + +declare const nodeRequire: NodeRequire; + +// $ExpectType any +nodeRequire.requireActual("moduleName"); + +// $ExpectType any +nodeRequire.requireMock("moduleName"); + +/* Top-level jest namespace functions */ + +const customMatcherFactories: jasmine.CustomMatcherFactories = {}; + +jest + .addMatchers(customMatcherFactories) + .addMatchers({}) + .addMatchers(customMatcherFactories) + .autoMockOff() + .autoMockOn() + .clearAllMocks() + .clearAllTimers() + .resetAllMocks() + .restoreAllMocks() + .clearAllTimers() + .deepUnmock("moduleName") + .disableAutomock() + .doMock("moduleName") + .doMock("moduleName", jest.fn()) + .doMock("moduleName", jest.fn(), {}) + .doMock("moduleName", jest.fn(), { virtual: true }) + .dontMock("moduleName") + .enableAutomock() + .mock("moduleName") + .mock("moduleName", jest.fn()) + .mock("moduleName", jest.fn(), {}) + .mock("moduleName", jest.fn(), { virtual: true }) + .resetModuleRegistry() + .resetModules() + .runAllImmediates() + .runAllTicks() + .runAllTimers() + .runOnlyPendingTimers() + .runTimersToTime(9001) + .advanceTimersByTime(9001) + .setMock("moduleName", {}) + .setMock<{}>("moduleName", {}) + .setMock<{ a: "b" }>("moduleName", { a: "b" }) + .setTimeout(9001) + .unmock("moduleName") + .useFakeTimers() + .useRealTimers(); + +/* Mocks and spies */ + +const mock1: jest.Mock = jest.fn(); +const mock2: jest.Mock = jest.fn(() => undefined); +const mock3: jest.Mock = jest.fn(() => "abc"); +const mock4: jest.Mock<"abc"> = jest.fn((): "abc" => "abc"); +const mock5: jest.Mock = jest.fn((...args: string[]) => args.join("")); +const mock6: jest.Mock = jest.fn((arg: {}) => arg); + +const genMockModule1: {} = jest.genMockFromModule("moduleName"); +const genMockModule2: { a: "b" } = jest.genMockFromModule<{ a: "b" }>("moduleName"); + +const isStringMock: boolean = jest.isMockFunction("foo"); +const isMockMock: boolean = jest.isMockFunction(mock1); + +const maybeMock = () => {}; +if (jest.isMockFunction(maybeMock)) { + maybeMock.getMockName(); +} + +const mockName: string = jest.fn().getMockName(); +const mockContextVoid: jest.MockContext = jest.fn().mock; +const mockContextString: jest.MockContext = jest.fn(() => "").mock; + +jest.fn().mockClear(); + +jest.fn().mockReset(); + +const spiedTarget = { + returnsVoid(): void { }, + returnsString(): string { + return ""; + } }; -// TODO: use real jquery types? -declare const $: any; -// Tests based on the Jest website -jest.unmock('../sum'); +const spy1 = jest.spyOn(spiedTarget, "returnsVoid"); +const spy2 = jest.spyOn(spiedTarget, "returnsVoid", "get"); +const spy3 = jest.spyOn(spiedTarget, "returnsString", "set"); -class TestClass { } +const spy1Name: string = spy1.getMockName(); -describe(TestClass, () => { }); +const spy2Calls: any[][] = spy2.mock.calls; -describe('sum', () => { - it('adds 1 + 2 to equal 3', () => { - const sum: (a: number, b: number) => number = require('../sum'); - expect(sum(1, 2)).toBe(3); - }); +spy2.mockClear(); +spy2.mockReset(); + +const spy3Mock: jest.Mock<() => string> = spy3 + .mockImplementation(() => "") + .mockImplementation((arg: {}) => arg) + .mockImplementation((...args: string[]) => args.join("")) + .mockName("name") + .mockReturnThis() + .mockReturnValue("value") + .mockReturnValueOnce("value") + .mockResolvedValue("value") + .mockResolvedValueOnce("value") + .mockRejectedValue("value") + .mockRejectedValueOnce("value"); + +/* Snapshot serialization */ + +const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = { + print: () => "", + test: () => true, +}; + +expect.addSnapshotSerializer(snapshotSerializerPlugin); + +expect.addSnapshotSerializer({ + print: (value: {}) => "", + test: (value: {}) => value === value, }); -describe('restoreAllMocks', () => { - afterEach(() => { - jest.restoreAllMocks(); - }); +expect.addSnapshotSerializer({ + print: ( + value: {}, + serialize: ((val: {}) => string), + indent: ((str: string) => string), + opts: {}, + ) => "", + test: (value: {}) => value === value, }); -describe('fetchCurrentUser', () => { - it('calls the callback when $.ajax requests are finished', () => { - const fetchCurrentUser = require('../fetchCurrentUser'); +expect.addSnapshotSerializer({ + print(value, serialize, indent, opts, colors) { + let result = ""; - // Create a mock function for our callback - const callback = jest.fn(); - fetchCurrentUser(callback); + if (opts.callToJSON !== undefined && opts.callToJSON) { + result += " "; + } - // Now we emulate the process by which `$.ajax` would execute its own - // callback - $.ajax.mock.calls[0 /*first call*/][0 /*first argument*/].success({ - firstName: 'Bobby', - lastName: '");DROP TABLE Users;--' - }); + result += opts.edgeSpacing; + result += opts.spacing; - // And finally we assert that this emulated call by `$.ajax` incurred a - // call back into the mock function we provided as a callback - expect(callback.mock.calls[0/*first call*/][0/*first arg*/]).toEqual({ - loggedIn: true, - fullName: 'Bobby ");DROP TABLE Users;--' - }); - }); + if (opts.escapeRegex !== undefined && opts.escapeRegex) { + result += " "; + } + + if (opts.indent !== undefined) { + for (let i = 0; i < opts.indent; i += 1) { + result += "\t"; + } + } + + if (opts.maxDepth !== undefined) { + result = result.substring(0, opts.maxDepth); + } + + if (opts.min !== undefined && opts.min) { + result += " "; + } + + if (opts.plugins !== undefined) { + for (const plugin of opts.plugins) { + expect.addSnapshotSerializer(plugin); + } + } + + if (opts.printFunctionName !== undefined && opts.printFunctionName) { + result += " "; + } + + if (opts.theme) { + if (opts.theme.comment !== undefined) { + result += opts.theme.comment; + } + + if (opts.theme.content !== undefined) { + result += opts.theme.content; + } + + if (opts.theme.prop !== undefined) { + result += opts.theme.prop; + } + + if (opts.theme.tag !== undefined) { + result += opts.theme.tag; + } + + if (opts.theme.value !== undefined) { + result += opts.theme.value; + } + } + + for (const color of [ + colors.comment, + colors.content, + colors.prop, + colors.tag, + colors.value, + ]) { + result += color.open; + result += color.close; + } + + return result; + }, + test: (value: {}) => value === value, }); -// unmock is the recommended approach for unmocking... -jest.unmock('../displayUser.js'); +/* expect extensions */ -describe('displayUser', () => { - it('displays a user after a click', () => { - // Set up our document body - document.body.innerHTML = - '
' + - ' ' + - '
'; +const expectExtendMap: jest.ExpectExtendMap = {}; - const displayUser = require.requireActual('../displayUser'); - const $ = require('jquery'); - const fetchCurrentUser = require('../fetchCurrentUser'); - - // Tell the fetchCurrentUser mock function to automatically invoke - // its callback with some data - fetchCurrentUser.mockImplementation((cb: (...args: any[]) => any) => { - cb({ - loggedIn: true, - fullName: 'Johnny Cash' - }); - }); - - // Use jquery to emulate a click on our button - $('#button').click(); - - // Assert that the fetchCurrentUser function was called, and that the - // #username span's innter text was updated as we'd it expect. - expect(fetchCurrentUser).toBeCalled(); - expect($('#username').text()).toEqual('Johnny Cash - Logged In'); - }); -}); - -jest.unmock('../CheckboxWithLabel.js'); -describe('CheckboxWithLabel', () => { - it('changes the text after click', () => { - const React = require('react/addons'); - const CheckboxWithLabel = require('../CheckboxWithLabel.js'); - const TestUtils = React.addons.TestUtils; - - // Render a checkbox with label in the document - const checkbox = TestUtils.renderIntoDocument( - CheckboxWithLabel({ - labelOn: "On", - labelOff: "Off" - }) - ); - - // Verify that it's Off by default - const label = TestUtils.findRenderedDOMComponentWithTag( - checkbox, 'label'); - expect(label.getDOMNode().textContent).toEqual('Off'); - - // Simulate a click and verify that it is now On - const input = TestUtils.findRenderedDOMComponentWithTag( - checkbox, 'input'); - TestUtils.Simulate.change(input); - expect(label.getDOMNode().textContent).toEqual('On'); - }); -}); - -jest.runAllTicks(); -xdescribe('Hooks and Suits', () => { - let tested: boolean; - - beforeEach(() => { - tested = false; - }); - - afterEach(() => { - tested = true; - }); - - test('tested', () => { - expect(tested).toBeTruthy(); - expect(tested).not.toBeFalsy(); - }); - - fit('tested', () => { - expect(tested).toBeDefined(); - expect(tested).not.toBeUndefined(); - }); - - xit('expect null to be null', () => { - expect(null).toBeNull(); - }); - - xit('expect NaN to be NaN', () => { - expect(NaN).toBeNaN(); - }); -}); - -describe('compartion', () => { - const sum: (a: number, b: number) => number = require.requireMock('../sum'); - - it('compares is 7 + 2 greater than 3', () => { - expect(sum(7, 2)).toBeGreaterThan(3); - }); - - it('compares is 2 + 7 greater than or equal to 3', () => { - expect(sum(2, 7)).toBeGreaterThanOrEqual(3); - }); - - it('compares is 3 less than 3 + 4', () => { - expect(3).toBeLessThan(sum(3, 4)); - }); - - it('compares is 3 less than or equal to 4 + 3', () => { - expect(3).toBeLessThanOrEqual(sum(4, 3)); - }); - - it('works sanely with simple decimals', () => { - expect(0.2 + 0.1).toBeCloseTo(0.3, 5); - }); - - it('works sanely with simple decimals and the default delta', () => { - expect(0.2 + 0.1).toBeCloseTo(0.3); - }); -}); - -describe('toThrow API', () => { - function throwTypeError(): void { - throw new TypeError('toThrow Definition was out of date'); - } - - it('throws', () => { - expect(throwTypeError()).toThrow(); - expect(throwTypeError()).toThrowError(); - }); - - it('throws TypeError', () => { - expect(throwTypeError()).toThrow(TypeError); - expect(throwTypeError()).toThrowError(TypeError); - }); - - it('throws \'Definition was out of date\'', () => { - expect(throwTypeError()).toThrow(/Definition was out of date/); - expect(throwTypeError()).toThrowError(/Definition was out of date/); - }); - - it('throws \'toThorow Definition was out of date\'', () => { - expect(throwTypeError()).toThrow('toThrow Definition was out of date'); - expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); - }); -}); - -describe('Assymetric matchers', () => { - it('works', () => { - expect({ - timestamp: 1480807810388, - text: 'Some text content, but we care only about *this part*', - color: '#bada55', - greeting: 'hello, world!', - }).toEqual({ - timestamp: expect.any(Number), - text: expect.stringMatching('*this part*'), - color: expect.stringMatching(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i), - greeting: expect.stringContaining('hello'), - }); - - const callback = jest.fn(); - expect(callback).toEqual(expect.any(Function)); - callback(5, "test"); - expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)); - const obj = { - items: [1] +expect.extend(expectExtendMap); +expect.extend({}); +expect.extend({ + foo(this: jest.MatcherUtils, received: {}, ...actual: Array<{}>) { + return { + message: () => JSON.stringify(received), + pass: false, }; - expect(obj).toEqual(expect.objectContaining({ - items: expect.arrayContaining([ - expect.any(Number) - ]) + } +}); + +/* Basic matchers */ + +describe("", () => { + it("", () => { + expect(jest.fn()).lastCalledWith(); + expect(jest.fn()).lastCalledWith("jest"); + expect(jest.fn()).lastCalledWith({}, {}); + + expect(jest.fn()).lastReturnedWith("jest"); + expect(jest.fn()).lastReturnedWith({}); + + expect(jest.fn()).nthReturnedWith(0, "jest"); + expect(jest.fn()).nthReturnedWith(1, {}); + + expect({}).toBe({}); + expect([]).toBe([]); + expect(10).toBe(10); + + expect(jest.fn()).toBeCalled(); + + expect(jest.fn()).toBeCalledWith(); + expect(jest.fn()).toBeCalledWith("jest"); + expect(jest.fn()).toBeCalledWith({}, {}); + + expect(0).toBeCloseTo(1); + expect(0).toBeCloseTo(1, 2); + + expect(undefined).toBeDefined(); + expect({}).toBeDefined(); + + expect(true).toBeFalsy(); + expect(false).toBeFalsy(); + expect(0).toBeFalsy(); + + expect(0).toBeGreaterThan(1); + + expect(0).toBeGreaterThanOrEqual(1); + + expect(3).toBeInstanceOf(Number); + + expect(0).toBeLessThan(1); + + expect(0).toBeLessThanOrEqual(1); + + expect(null).toBeNull(); + expect(undefined).toBeNull(); + + expect(true).toBeTruthy(); + expect(false).toBeFalsy(); + expect(1).toBeTruthy(); + + expect(undefined).toBeUndefined(); + expect({}).toBeUndefined(); + + expect(NaN).toBeNaN(); + expect(Infinity).toBeNaN(); + + expect([]).toContain({}); + expect(["abc"]).toContain("abc"); + expect(["abc"]).toContain("def"); + + expect([]).toContainEqual({}); + expect(["abc"]).toContainEqual("def"); + + expect([]).toEqual([]); + expect({}).toEqual({}); + + expect(jest.fn()).toHaveBeenCalled(); + + expect(jest.fn()).toHaveBeenCalledTimes(0); + expect(jest.fn()).toHaveBeenCalledTimes(1); + + expect(jest.fn()).toHaveBeenCalledWith(); + expect(jest.fn()).toHaveBeenCalledWith("jest"); + expect(jest.fn()).toHaveBeenCalledWith({}, {}); + + expect(jest.fn()).toHaveBeenCalledWith(0); + expect(jest.fn()).toHaveBeenCalledWith(1, "jest"); + expect(jest.fn()).toHaveBeenCalledWith(2, {}, {}); + + expect(jest.fn()).toHaveBeenLastCalledWith(); + expect(jest.fn()).toHaveBeenLastCalledWith("jest"); + expect(jest.fn()).toHaveBeenLastCalledWith({}, {}); + + expect(jest.fn()).toHaveLastReturnedWith("jest"); + expect(jest.fn()).toHaveLastReturnedWith({}); + + expect([]).toHaveLength(0); + expect("").toHaveLength(1); + + expect(jest.fn()).toHaveNthReturnedWith(0, "jest"); + expect(jest.fn()).toHaveNthReturnedWith(1, {}); + + expect({}).toHaveProperty("property"); + expect({}).toHaveProperty("property", {}); + expect({}).toHaveProperty(["property"]); + expect({}).toHaveProperty(["property"], {}); + expect({}).toHaveProperty(["property", "deep"]); + expect({}).toHaveProperty(["property", "deep"], {}); + + expect(jest.fn()).toHaveReturned(); + + expect(jest.fn()).toHaveReturnedTimes(0); + expect(jest.fn()).toHaveReturnedTimes(1); + + expect(jest.fn()).toHaveReturnedWith("jest"); + expect(jest.fn()).toHaveReturnedWith({}); + + expect("").toMatch(""); + expect("").toMatch(/foo/); + + expect({}).toMatchObject({}); + expect({ abc: "def" }).toMatchObject({ abc: "def" }); + expect({}).toMatchObject([{}, {}]); + expect({ abc: "def" }).toMatchObject([{ abc: "def" }, { invalid: "property" }]); + + expect({}).toMatchSnapshot(); + expect({}).toMatchSnapshot("snapshotName"); + + expect(jest.fn()).toReturn(); + + expect(jest.fn()).toReturnTimes(0); + expect(jest.fn()).toReturnTimes(1); + + expect(jest.fn()).toReturnWith("jest"); + expect(jest.fn()).toReturnWith({}); + + expect(true).toStrictEqual(false); + expect({}).toStrictEqual({}); + + expect(() => {}).toThrow(); + expect(() => { throw new Error(); }).toThrow(""); + expect(jest.fn()).toThrow(Error); + expect(jest.fn(() => { throw new Error(); })).toThrow(/foo/); + + expect(() => {}).toThrowErrorMatchingSnapshot(); + expect(() => { throw new Error(); }).toThrowErrorMatchingSnapshot(); + expect(jest.fn()).toThrowErrorMatchingSnapshot(); + expect(jest.fn(() => { throw new Error(); })).toThrowErrorMatchingSnapshot(); + + /* not */ + + expect({}).not.toEqual({}); + expect([]).not.toStrictEqual([]); + + /* Promise matchers */ + + expect(Promise.reject("jest")).rejects.toEqual("jest"); + expect(Promise.reject({})).rejects.toEqual({}); + expect(Promise.resolve("jest")).rejects.toEqual("jest"); + expect(Promise.resolve({})).rejects.toEqual({}); + + expect(Promise.reject("jest")).resolves.toEqual("jest"); + expect(Promise.reject({})).resolves.toEqual({}); + expect(Promise.resolve("jest")).resolves.toEqual("jest"); + expect(Promise.resolve({})).resolves.toEqual({}); + + /* type matchers */ + + expect({}).toBe(expect.anything()); + + expect({}).toBe(expect.any(class Foo { })); + expect(new Error()).toBe(expect.any(Error)); + expect(7).toBe(expect.any(Number)); + + expect({}).toBe(expect.arrayContaining(["a", "b"])); + expect(["abc"]).toBe(expect.arrayContaining(["a", "b"])); + + expect.objectContaining({}); + expect.stringMatching("foo"); + expect.stringMatching(/foo/); + expect.stringContaining("foo"); + + expect({ abc: "def" }).toBe(expect.objectContaining({ + abc: expect.arrayContaining([expect.any(Date), {}]), + def: expect.objectContaining({ + foo: "bar", + }), + ghi: expect.stringMatching("foo"), })); - expect.assertions(4); + /* Miscellaneous */ - interface Test { - a: number; - b: string; + expect.hasAssertions(); + expect.assertions(0); + expect.assertions(9001); + }); +}); + +/* Test framework and config */ + +const globalConfig: jest.GlobalConfig = { + bail: true, + collectCoverage: false, + collectCoverageFrom: ["glob"], + collectCoverageOnlyFrom: { + abc: true, + def: false, + }, + coverageDirectory: "", + coverageReporters: [""], + coverageThreshold: { + global: { + abc: 90, + def: 100, + }, + }, + expand: true, + forceExit: false, + logHeapUsage: true, + mapCoverage: false, + noStackTrace: true, + notify: false, + projects: ["projects"], + replname: "", + reporters: [ + ["abc", {}], + ["def", {}], + ], + rootDir: "path", + silent: true, + testNamePattern: "", + testPathPattern: "", + testResultsProcessor: "", + updateSnapshot: "all" as "all" | "new" | "none", + useStderr: true, + verbose: false, + watch: true, + watchman: false, +}; + +const projectConfig: jest.ProjectConfig = { + automock: true, + browser: false, + cache: true, + cacheDirectory: "", + clearMocks: true, + coveragePathIgnorePatterns: [""], + cwd: "", + detectLeaks: true, + displayName: "", + forceCoverageMatch: ["abc", "def"], + globals: { + "ts-jest": {}, + }, + haste: { + defaultPlatform: "", + hasteImplModulePath: "", + platforms: ["win95", "win2000", "clippy"], + providesModuleNodeModules: ["abc", "def"], + }, + moduleDirectories: ["", ""], + moduleFileExtensions: [".ts", ".json"], + moduleLoader: "laoder", + moduleNameMapper: [ + ["abc", "def"], + ["ghi", "jkl"], + ], + modulePathIgnorePatterns: ["abc", "def"], + modulePaths: ["abc", "def"], + name: "", + resetMocks: true, + resetModules: false, + resolver: "", + rootDir: "", + roots: ["", ""], + runner: "", + setupFiles: ["abc", "def"], + setupTestFrameworkScriptFile: "", + skipNodeResolution: true, + snapshotSerializers: ["abc", "def"], + testEnvironment: "", + testEnvironmentOptions: {}, + testLocationInResults: true, + testMatch: [".test.ts"], + testPathIgnorePatterns: ["*.spec.*"], + testRegex: "abc", + testRunner: "m", + testURL: "localhost:3000", + timers: "real", + transform: [ + ["abc", "def"], + ], + transformIgnorePatterns: ["", ""], + unmockedModulePathPatterns: ["abc"], + watchPathIgnorePatterns: ["def"], +}; + +const environment = { + global: {}, + fakeTimers: { + clearAllTimers() { }, + runAllImmediates() { }, + runAllTicks() { }, + runAllTimers() { }, + runTimersToTime(time: number) { }, + advanceTimersByTime(time: number) { }, + runOnlyPendingTimers() { }, + runWithRealTimers(callback: () => void) { + callback(); + }, + useFakeTimers() { }, + useRealTimers() { }, + }, + testFilePath: "", + moduleMocker: {}, + dispose() {}, + runScript(script: "") { + return {}; + }, +}; + +const workTestFramework = async (testFramework: jest.TestFramework): Promise => { + return testFramework( + globalConfig, + projectConfig, + environment, + {}, + "testPath" + ); +}; + +/* Jasmine status changers */ + +describe("", () => { + it("", () => { + pending(); + pending("reason"); + + fail(); + fail("error"); + fail(new Error("reason")); + fail({}); + }); +}); + +/* Jasmine clocks and timing */ + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 9001; + +const clock = jasmine.clock(); + +clock.install(); + +clock.mockDate(); +clock.mockDate(undefined); +clock.mockDate(new Date()); + +clock.tick(0); +clock.tick(9001); + +/* Jasmine matchers */ + +expect({}).toBe(jasmine.anything()); + +expect({}).toBe(jasmine.any(class Foo { })); +expect(new Error()).toBe(jasmine.any(Error)); +expect(7).toBe(jasmine.any(Number)); + +expect({}).toBe(jasmine.arrayContaining(["a", "b"])); +expect(["abc"]).toBe(jasmine.arrayContaining(["a", "b"])); + +jasmine.arrayContaining([]); +new (jasmine.arrayContaining([]))([]); +const arrayContained: boolean = jasmine + .arrayContaining([]) + .asymmetricMatch([]); +const arrayContainedName: string = jasmine + .arrayContaining([]) + .jasmineToString(); + +jasmine.objectContaining({}); +new (jasmine.objectContaining({}))({}); +const objectContained: boolean = jasmine + .objectContaining({}) + .jasmineMatches({}, ["abc"], ["def"]); +const objectContainedName: string = jasmine + .objectContaining({}) + .jasmineToString(); + +jasmine.stringMatching("foo"); +jasmine.stringMatching(/foo/); +new (jasmine.stringMatching("foo"))({}); +const stringContained: boolean = jasmine + .stringMatching(/foo/) + .jasmineMatches({}); +const stringContainedName: string = jasmine + .stringMatching("foo") + .jasmineToString(); + +expect({ abc: "def" }).toBe(jasmine.objectContaining({ + abc: jasmine.arrayContaining([jasmine.any(Date), {}]), + def: jasmine.objectContaining({ + foo: "bar", + }), + ghi: jasmine.stringMatching("foo"), +})); + +/* Jasmine spies */ + +describe("", () => { + it("", () => { + let spy = jasmine.createSpy(); + jasmine.createSpy("name"); + jasmine.createSpy("name", () => {}); + jasmine.createSpy("name", (arg: {}) => arg); + jasmine.createSpy("name", (...args: string[]) => args.join("")); + + spy = jasmine.createSpy() + .and.callFake(() => {}) + .and.callFake((arg: {}) => arg) + .and.callFake((...args: string[]) => args.join("")) + .and.callThrough() + .and.returnValue("jasmine") + .and.returnValue({}) + .and.returnValues() + .and.returnValues("jasmine") + .and.returnValues({}, {}) + .and.stub() + .and.throwError("message"); + + const identity: string = spy.identity; + + let args: any[]; + args = spy.mostRecentCall.args; + args = spy.argsForCall[0]; + args = spy.calls.allArgs(); + args = spy.calls.argsFor(0); + + const spyCalled: boolean = spy.calls.any(); + + const wasCalled: boolean = spy.wasCalled; + + for (const call of [ + ...spy.calls.all(), + spy.calls.first(), + spy.calls.mostRecent(), + ]) { + const callType: jasmine.CallInfo = call; + const callArgs: any[] = call.args; + const { object, returnValue } = call; } - // It's useful to create expected objects before the test call for refactoring purposes - // Assymetric matchers must return any in this case to constrain the required type - const test: Test = { - a: expect.any(Number), - b: expect.anything() + spy.calls.reset(); + + const spyReturn = spy(); + + /* Jasmine spy objects */ + + let spyObject = { + abc() { + return ""; + }, + def: 7, }; - expect(callback).toHaveBeenCalledWith(test); + + spyObject = jasmine.createSpyObj("baseName", ["abc"]); + spyObject = jasmine.createSpyObj("baseName", ["abc"]); + + const newSpyObject: typeof spyObject = jasmine.createSpyObj("baseName", ["abc"]); }); }); -describe('setTimeout', () => { - it('works as expected', done => { - jest.setTimeout(1000); +/* Jasmine pp */ - setTimeout(() => { - expect(true).toBeTruthy(); - done(); - }, 900); - }); -}); +const pp: string = jasmine.pp({}); -describe('Extending extend', () => { - it('works', () => { - expect.extend({ - toBeNumber(received: any, actual: any) { - const pass = received === actual; - const message = - () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; - return { message, pass }; - }, - toBeVariadicMatcher(received: any, floor: number, ceiling: number) { - const pass = received >= floor && received <= ceiling; - const message = - () => `expected ${received} ${pass ? 'not ' : ''} to be within range ${floor}-${ceiling}`; - return { message, pass }; - }, - toBeTest(received: any, actual: any) { - this.utils.ensureNoExpected(received); - this.utils.ensureActualIsNumber(received); - this.utils.ensureExpectedIsNumber(actual); - this.utils.ensureNumbers(received, actual); +/* Jasmine equality testers */ - return { - message: () => ` - ${this.utils.getType(received).toLowerCase()} \n\n - ${this.utils.matcherHint(".not.toBe")} ${this.utils.printExpected(actual)} ${this.utils.printReceived(received)}\n\n - `, - pass: true - }; - } - }); - }); -}); +const equalityTesterObject = (first: {}, second: {}) => false; +const equalityTesterString: jasmine.CustomEqualityTester = (first: string, second: string) => first === second; -describe('missing tests', () => { - it('creates closures', () => { - class Closure { - private arg: T; +jasmine.addCustomEqualityTester(equalityTesterObject); +jasmine.addCustomEqualityTester(equalityTesterObject); - constructor(private readonly fn: (arg: T) => void) { - this.fn = fn; - } - - bind(arg: T): void { - this.arg = arg; - } - - call(): void { - this.fn(this.arg); - } - } - - type StringClosure = (arg: string) => void; - const spy: jest.Mock = jest.fn(); - const closure: Closure = new Closure(spy); - closure.bind('jest'); - closure.call(); - expect(spy).lastCalledWith('jest'); - expect(spy).toBeCalledWith('jest'); - expect(jest.isMockFunction(spy)).toBeTruthy(); - }); - - it('tests all missing Mocks functionality', () => { - type FruitsGetter = () => string[]; - const mock: jest.Mock = jest.fn(); - mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']); - jest.setMock('./../tesks/getFruits', mock); - const getFruits: FruitsGetter = require('./../tesks/getFruits'); - expect(getFruits()).toContain('Orange'); - mock.mockReturnValueOnce(['Apple', 'Plum']); - expect(mock()).not.toContain('Orange'); - const myBeverage: any = {delicious: true, sour: false}; - expect(myBeverage).toContainEqual({delicious: true, sour: false}); - mock.mockReturnValue([]); // Deprecated: Use jest.fn(() => value) instead. - mock.mockClear(); - const thisMock: jest.Mock = jest.fn().mockReturnThis(); - expect(thisMock()).toBe(this); - }); - - it('async test with mockResolvedValue and mockResolvedValueOnce', async () => { - const asyncMock = jest - .fn() - .mockResolvedValue('default') - .mockResolvedValueOnce('first call') - .mockResolvedValueOnce('second call'); - - await asyncMock(); // first call - await asyncMock(); // second call - await asyncMock(); // default - await asyncMock(); // default - }); - - it('async test with mockRejectedValue', async () => { - const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); - - await asyncMock(); // throws "Async error" - }); - - it('async test with mockResolvedValueOnce and mockRejectedValueOnce', async () => { - const asyncMock = jest - .fn() - .mockResolvedValueOnce('first call') - .mockRejectedValueOnce(new Error('Async error')); - - await asyncMock(); // first call - await asyncMock(); // throws "Async error" - }); - - it('tests mock name functionality', () => { - const mock: jest.Mock = jest.fn(); - mock.mockName('Carrot'); - expect(mock.getMockName()).toBe('Carrot'); - }); - - it('tests mock name functionality', () => { - const mock = spyOn(console, 'warn'); - expect(mock).toHaveBeenCalled(); - }); - - it('creates snapshoter', () => { - jest.disableAutomock().mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); - const render: () => string = require('./render'); - expect(render()).toMatch(/Link/); - jest.enableAutomock(); - }); - - it('runs only pending timers', () => { - jest.useRealTimers(); - setTimeout(() => expect(1).not.toEqual(0), 3000); - jest.runOnlyPendingTimers().runTimersToTime(300); - }); - - it('runs all timers', () => { - jest.clearAllTimers(); - jest.useFakeTimers(); - setTimeout(() => expect(0).not.toEqual(1), 3000); - jest.runAllTimers(); - }); - - it('cleares cache', () => { - const sum1 = require('../sum'); - jest.resetModules(); - const sum2 = require('../sum'); - expect(sum1).not.toBe(sum2); - }); -}); - -describe('toMatchSnapshot', () => { - it('compares snapshots', () => { - expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); - }); - - it('can give name to snapshot', () => { - expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot('given name'); - }); -}); - -describe('toThrowErrorMatchingSnapshot', () => { - it('compares snapshots', () => { - expect(() => { throw new Error('descriptiton'); }).toThrowErrorMatchingSnapshot(); - }); -}); - -const testSerializerPluginString = "set by testSerializerPlugin"; -let testSerializerPluginCallCount = 0; -expect.addSnapshotSerializer({ - print(val, serialize, indent, opts, colors) { - val.willOverwrite = testSerializerPluginString; - testSerializerPluginCallCount += 1; - return 'plugin called: ' + serialize(val.willOverwrite); - }, - test(val) { - return val && val.willOverwrite && val.willOverwrite !== testSerializerPluginString; - }, -}); -describe('addSnapshotSerializer', () => { - it('the plugin does its work', () => { - testSerializerPluginCallCount = 0; - expect({ willOverwrite: { x: 1, y: 2, } }).toMatchSnapshot(); - expect({ willOverwrite: "this will get overwritten by testSerializerPlugin" }).toMatchSnapshot(); - expect({ willOverwrite: "so will this" }).toMatchSnapshot(); - expect({ foo: "this will not" }).toMatchSnapshot(); - expect(testSerializerPluginCallCount).toBe(3); - }); -}); - -function testInstances() { - const mockFn = jest.fn<(...args: any[]) => any>(); - const a = new mockFn(); - const b = new mockFn(); - - mockFn.mock.instances[0] === a; // true - mockFn.mock.instances[1] === b; // true -} - -function testMockImplementation() { - const mockFn = jest.fn<(...args: any[]) => any>().mockImplementation((scalar: number): number => { - return 42 + scalar; - }); - - const a = mockFn(0); - const b = mockFn(1); - - a === 42; // true - b === 43; // true - - mockFn.mock.calls[0][0] === 0; // true - mockFn.mock.calls[1][0] === 1; // true -} - -// Test from jest Docs: -describe('genMockFromModule', () => { - // Interfaces: - interface MockFiles { - [index: string]: string; - } - - interface MockedFS { - readdirSync(dir: string): string[]; - __setMockFiles(newMockFiles: MockFiles): void ; - } - - // ------------------------------------------------------------------------------------ - // FileSummarizer.ts - - const fs = require('fs'); - - function summarizeFilesInDirectorySync(directory: string): string[] { - return fs.readdirSync(directory).map((fileName: string) => ({ - fileName, - directory, - })); - } - - // export default summarizeFilesInDirectorySync; // For sake of compilation - - // ------------------------------------------------------------------------------------ - // __mocks__/fs.js - - const path = require('path'); - - const mockedFS: MockedFS = jest.genMockFromModule('fs'); - - let mockFiles: any = Object.create(null); - function __setMockFiles(newMockFiles: MockFiles): void { - mockFiles = Object.create(null); - for (const file in newMockFiles) { - const dir: string = path.dirname(file); - - if (!mockFiles[dir]) { - mockFiles[dir] = []; - } - mockFiles[dir].push(path.basename(file)); - } - } - - function readdirSync(directoryPath: string): string[] { - return mockFiles[directoryPath] || []; - } - - mockedFS.readdirSync = readdirSync; - mockedFS.__setMockFiles = __setMockFiles; - - // export = mockedFS; // For sake of compilation - // ------------------------------------------------------------------------------------ - // __tests__/FileSummarizer-test.js - - jest.mock('fs'); - - describe('listFilesInDirectorySync', () => { - const MOCK_FILE_INFO: MockFiles = { - '/path/to/file1.js': 'console.log("file1 contents");', - '/path/to/file2.txt': 'file2 contents', - }; - - beforeEach(() => { - // Set up some mocked out file info before each test - (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); - }); - - it('includes all files in the directory in the summary', () => { - const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); - const fileSummary = FileSummarizer('/path/to'); - - expect(fileSummary.length).toBe(2); - }); - }); -}); - -/** - * Pass strictNullChecks - */ -describe('strictNullChecks', () => { - it('does not complain when using done callback', (done) => { - done(); - }); -}); - -describe('beforeEach with timeout', () => { - beforeEach(() => { - // this shouldn't take more than a second - }, 1000); -}); - -class TestApi { - constructor() { } - testProp: boolean; - private readonly anotherProp: string; - testMethod(a: number): string { return ""; } -} - -declare function mockedFunc(a: number): string; - -declare function mockedFuncWithApi(api: TestApi): void; - -describe('Mocked type', () => { - it('Works', () => { - const mock: jest.Mocked = new TestApi() as any; - mock.testProp; - mock.testMethod.mockImplementation(() => 'test'); - mock.testMethod(5).toUpperCase(); - - mockedFuncWithApi(mock); - }); -}); - -describe('Mocks', () => { - it('jest.fn() without args is a function type', () => { - const test = jest.fn(); - test(); - new test(); - test.mock.instances[0]; - test.mockImplementation(() => { }); - }); - - it('jest.fn() with returned object infers type', () => { - const testMock = jest.fn(() => ({ a: 5, test: jest.fn() })); - - testMock(5, 5, 'a'); - testMock.mockImplementation(() => { }); - testMock.caller; - - const ins = new testMock(); - ins.a; - ins.test(); - ins.test.mockImplementation(() => 5); - ins.test.mock.calls; - - const anotherMock = jest.fn(() => { - const api: Partial = { - testMethod: jest.fn() - }; - return api; - }); - const anotherIns: jest.Mocked = new anotherMock() as any; - anotherIns.testMethod.mockImplementation(() => 1); - }); - - it('jest.fn() accepts constructor arguments', () => { - interface TestLog { - log(...msg: any[]): void; - } - - class LogMock extends jest.fn((verbose?: boolean) => { - const mockLog = () => { - if (verbose) { - return jest.fn((...args) => { - const subj = args.shift() || ""; - console.log(subj, ...args); - }); - } - return jest.fn(); - }; +/* Jasmine matchers */ +const customMatcherFactoriesNone = {}; +const customMatcherFactoriesIndex: { [i: string]: jasmine.CustomMatcherFactory } = {}; +const customMatcherFactoriesManual = { + abc: () => ({ + compare: (actual: "", expected: "", ...args: Array<{}>) => ({ + pass: true, + message: "", + }), + }), + def: (util: jasmine.MatchersUtil, customEqualityTestesr: jasmine.CustomEqualityTester): jasmine.CustomMatcher => ({ + compare(actual: T, expected: T): jasmine.CustomMatcherResult { return { - log: mockLog() + pass: actual === expected, + message: () => "foo", }; - }) { - } + }, + }), +}; - const nonVerboseLog = new LogMock(); - nonVerboseLog.log("this is completely catched by jest"); - expect(nonVerboseLog.log).toBeCalledWith("this is completely catched by jest"); - const verboseLog = new LogMock(true); - verboseLog.log("this should also be printed to the console"); - expect(verboseLog.log).toBeCalledWith("this should also be printed to the console"); - }); -}); +const matchersUtil1 = { + buildFailureMessage: () => "", + contains: (haystack: string, needle: string) => haystack.indexOf(needle) !== -1, + equals: (a: {}, b: {}) => false, +}; -// https://facebook.github.io/jest/docs/en/expect.html#resolves -describe('resolves', () => { - it('unwraps the expected Promise', () => { - const expectation = expect(Promise.resolve('test')).resolves.toEqual('test'); - expect(expectation instanceof Promise).toBeTruthy(); - return expectation; - }); +let matchersUtil2: jasmine.MatchersUtil = { + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string { + return `${matcherName}${isNot ? "1" : "0"}${actual}${expected.join("")}`; + }, + contains(haystack: T[], needle: T, customTesters?: jasmine.CustomEqualityTester[]) { + return true; + }, + equals: (a: {}, b: {}, customTesters?: jasmine.CustomEqualityTester[]) => false, +}; - it('unwraps a .toHaveBeenCalledX', done => { - expect.assertions(2); +// Jest config - const fn = jest.fn(); - return expect(Promise.resolve(fn)).resolves.toHaveBeenCalledTimes(0).then(val => { - expect(val).toEqual(true); - done(); +const testJestConfig = (defaults: jest.DefaultOptions) => { + const config: jest.InitialOptions = { + transform: { + '^.+\\.(ts|tsx)$': 'ts-jest' + }, + testMatch: [ + ...defaults.testMatch, + '**/__tests__/**/*.ts?(x)', + '**/?(*.)+(spec|test).ts?(x)' + ], + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + globals: { + 'ts-jest': {} + } + }; +}; + +// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/26368 + +describe.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a: number, b: number, expected: number) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); }); - }); - - it('unwraps a not.toHaveBeenCalledX', done => { - expect.assertions(2); - - const fn = jest.fn(); - return expect(Promise.resolve(fn)).resolves.not.toHaveBeenCalledTimes(1).then(val => { - expect(val).toEqual(true); - done(); - }); - }); -}); - -// https://facebook.github.io/jest/docs/en/expect.html#rejects -describe('rejects', () => { - it('unwraps the expected Promise', () => { - const expectation = expect(Promise.reject(new Error('error'))).rejects.toMatch('error'); - expect(expectation instanceof Promise).toBeTruthy(); - return expectation; - }); -}); - -// https://facebook.github.io/jest/docs/en/expect.html#tohavepropertykeypath-value -describe('toHaveProperty', () => { - it('it accepts a keyPath as string', () => { - expect({ a: { b: {}}}).toHaveProperty('a'); - }); - it('it accepts a keyPath as string with dot notation', () => { - expect({ a: { b: {}}}).toHaveProperty('a.b'); - }); - it('it accepts a keyPath as an array', () => { - expect({ a: { b: {}}}).toHaveProperty(['a', 'b']); - }); - it('it accepts a keyPath as an array containing non-string values', () => { - expect({ a: ['b']}).toHaveProperty(['a', 0]); - }); -}); - -class MyTransformer implements jest.Transformer { - process(text: string, path: string) { - return ` - // some comments - ${text} - `; } +); + +interface Case { + a: number; + b: number; + expected: number; } -class MyReporter implements jest.Reporter { - onRunStart() { - console.log('hello world'); +describe.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("$a + $b", ({ a, b, expected }: Case) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); + +describe.only.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); } -} +); -declare const testResult: jest.TestResult; -const myTestRunner: jest.TestFramework = () => Promise.resolve(testResult); - -const testResultsProcessor: jest.TestResultsProcessor = result => ({...result, numFailedTests: 1}); - -// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18826 -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 1); +describe.only.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("$a + $b", ({ a, b, expected }: Case) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(1); }); -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 2); + +describe.skip.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + } +); + +describe.skip.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("$a + $b", ({ a, b, expected }: Case) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(2); +}); + +test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + expect(a + b).toBe(expected); + } +); + +test.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("returns $expected when $a is added $b", ({ a, b, expected }: Case) => { + expect(a + b).toBe(expected); +}); + +test.only.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + expect(a + b).toBe(expected); + } +); + +test.only.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("returns $expected when $a is added $b", ({ a, b, expected }: Case) => { + expect(a + b).toBe(expected); }); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 48e2a0327c..dbf60400b9 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for joi v13.0.1 +// Type definitions for joi v13.3.0 // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor // Laurence Dougal Myers @@ -12,6 +12,7 @@ // Anjun Wang // Rafael Kallis // Conan Lai +// Peter Thorson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -106,6 +107,13 @@ export interface EmailOptions { minDomainAtoms?: number; } +export interface HexOptions { + /** + * hex decoded representation must be byte aligned + */ + byteAligned: boolean; +} + export interface IpOptions { /** * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture @@ -512,6 +520,11 @@ export interface NumberSchema extends AnySchema { * Requires the number to be negative. */ negative(): this; + + /** + * Requires the number to be a TCP port, so between 0 and 65535. + */ + port(): this; } export interface StringSchema extends AnySchema { @@ -624,7 +637,7 @@ export interface StringSchema extends AnySchema { /** * Requires the string value to be a valid hexadecimal string. */ - hex(): this; + hex(options?: HexOptions): this; /** * Requires the string value to be a valid hostname as per RFC1123. @@ -714,10 +727,15 @@ export interface ArraySchema extends AnySchema { export interface ObjectSchema extends AnySchema { /** - * Sets the allowed object keys. + * Sets or extends the allowed object keys. */ keys(schema?: SchemaMap): this; + /** + * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied. + */ + append(schema?: SchemaMap): this; + /** * Specifies the minimum number of keys in the object. */ @@ -966,7 +984,7 @@ export interface Rules

{ name: string; params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; setup?(this: ExtensionBoundSchema, params: P): Schema | void; - validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; + validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): any; description?: string | ((params: P) => string); } @@ -974,8 +992,8 @@ export interface Extension { name: string; base?: Schema; language?: LanguageOptions; - coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; - pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; + pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; describe?(this: Schema, description: Description): Description; rules?: Rules[]; } @@ -1101,10 +1119,13 @@ export function ref(key: string, options?: ReferenceOptions): Reference; export function isRef(ref: any): ref is Reference; /** - * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array + * of strings For string values path separator is a dot (`.`) */ export function reach(schema: ObjectSchema, path: string): Schema; export function reach(schema: ObjectSchema, path: string): T; +export function reach(schema: ObjectSchema, path: string[]): Schema; +export function reach(schema: ObjectSchema, path: string[]): T; /** * Creates a new Joi instance customized with the extension(s) you provide included. diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 5ea9088a74..def9eaafd4 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -96,6 +96,12 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +let hexOpts: Joi.HexOptions = null; + +hexOpts = { byteAligned: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; @@ -602,6 +608,7 @@ numSchema = numSchema.precision(num); numSchema = numSchema.multiple(num); numSchema = numSchema.positive(); numSchema = numSchema.negative(); +numSchema = numSchema.port(); namespace common { numSchema = numSchema.allow(x); @@ -659,6 +666,9 @@ objSchema = Joi.object(schemaMap); objSchema = objSchema.keys(); objSchema = objSchema.keys(schemaMap); +objSchema = objSchema.append(); +objSchema = objSchema.append(schemaMap); + objSchema = objSchema.min(num); objSchema = objSchema.max(num); objSchema = objSchema.length(num); @@ -801,6 +811,7 @@ strSchema = strSchema.guid(); strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); +strSchema = strSchema.hex(hexOpts); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); @@ -969,6 +980,7 @@ description = Joi.describe(schema); description = schema.describe(); schema = Joi.reach(objSchema, ''); +schema = Joi.reach(objSchema, []); const Joi2 = Joi.extend({ name: '', base: schema }); @@ -988,13 +1000,13 @@ const Joi3 = Joi.extend({ { name: 'asd', params: { - allowF: Joi.boolean().default(false), + allowFalse: Joi.boolean().default(false), }, setup(params) { - const fIsAllowed = params.allowF; + const fIsAllowed = params.allowFalse; }, - validate(params, value, state, options) { - if (value === 'asd' || params.allowF && value === 'asdf') { + validate(params, value: boolean, state, options) { + if (value || params.allowFalse && !value) { return value; } return this.createError('asd', { v: value }, state, options); diff --git a/types/jquery-animate-scroll/index.d.ts b/types/jquery-animate-scroll/index.d.ts new file mode 100644 index 0000000000..a21b179738 --- /dev/null +++ b/types/jquery-animate-scroll/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for JQuery Animate Scroll 1.0 +// Project: https://github.com/risan/jquery-animate-scroll +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export type Options = Partial<{ + $container: JQuery; + speed: number; + offset: number; +}>; + +declare global { + interface JQuery { + animateScroll(options?: Options): JQuery; + scrollHere(options?: Options): JQuery; + } + + interface JQueryStatic { + scrollTo(element: JQuery, options?: Options): void; + } +} diff --git a/types/jquery-animate-scroll/jquery-animate-scroll-tests.ts b/types/jquery-animate-scroll/jquery-animate-scroll-tests.ts new file mode 100644 index 0000000000..65bdb07aef --- /dev/null +++ b/types/jquery-animate-scroll/jquery-animate-scroll-tests.ts @@ -0,0 +1,21 @@ +import { Options } from "jquery-animate-scroll"; + +// basic usage +$('a').animateScroll(); + +$('#article-1').scrollHere(); + +$.scrollTo($('#article-1')); + +// with options +const options: Options = { + $container: $('body'), + speed: 1000, + offset: -100 +}; + +$('a').animateScroll(options); + +$('#article-1').scrollHere(options); + +$.scrollTo($('#article-1'), options); diff --git a/types/jquery-animate-scroll/tsconfig.json b/types/jquery-animate-scroll/tsconfig.json new file mode 100644 index 0000000000..94883a5e7b --- /dev/null +++ b/types/jquery-animate-scroll/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "jquery-animate-scroll-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-animate-scroll/tslint.json b/types/jquery-animate-scroll/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-animate-scroll/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/jquery-mockjax/index.d.ts b/types/jquery-mockjax/index.d.ts index 54cc036416..f1333b1028 100644 --- a/types/jquery-mockjax/index.d.ts +++ b/types/jquery-mockjax/index.d.ts @@ -1,11 +1,28 @@ -// Type definitions for jQuery Mockjax 2.0.1 +// Type definitions for jQuery Mockjax 2.3.0 // Project: https://github.com/jakerella/jquery-mockjax -// Definitions by: Laszlo Jakab , Vladimir Đokić +// Definitions by: +// Laszlo Jakab , +// Vladimir Đokić , +// James Johnson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +type MockJaxLoggingFunction = (message?: any, ...additionalParameters: any[]) => void; + +interface MockJaxStandardLogger { + error?: MockJaxLoggingFunction; + warn?: MockJaxLoggingFunction; + info?: MockJaxLoggingFunction; + log?: MockJaxLoggingFunction; + debug?: MockJaxLoggingFunction; +} + +interface MockJaxCustomLogger { + [key: string]: MockJaxLoggingFunction; +} + interface MockJaxSettingsHeaders { [key: string]: string; } @@ -33,15 +50,22 @@ interface MockJaxSettings { onAfterSuccess?: Function; onAfterError?: Function; onAfterComplete?: Function; + logger?: MockJaxStandardLogger | MockJaxCustomLogger; + logLevelMethods?: string[]; + namespace?: string; + throwUnmocked?: boolean; + retainAjaxCalls?: boolean; } interface MockJaxStatic { (options: MockJaxSettings): number; + (options: MockJaxSettings[]): number[]; handler(id?: number): any; clear(id?: number): void; mockedAjaxCalls(): any[]; unfiredHandlers(): any[]; unmockedAjaxCalls(): any[]; + clearRetainedAjaxCalls(): void; } interface JQueryStatic { diff --git a/types/jquery-mockjax/jquery-mockjax-tests.ts b/types/jquery-mockjax/jquery-mockjax-tests.ts index 3090a1c3cc..31babd9cd8 100644 --- a/types/jquery-mockjax/jquery-mockjax-tests.ts +++ b/types/jquery-mockjax/jquery-mockjax-tests.ts @@ -192,6 +192,81 @@ class Tests { } }); }); + + t('Standard logger type gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + error: logFunction, + warn: logFunction, + info: logFunction, + log: logFunction, + debug: logFunction + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Standard logger was called'); + done(); + } + }); + }); + + t('Custom logger object gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + customName: logFunction + }, + logLevelMethods: ['customName', 'customName', 'customName', 'customName', 'customName'] + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Custom logger was called'); + done(); + } + }); + }); + + t('Throws when ajax call is not mocked', (assert) => { + let done = assert.async(); + + $.mockjaxSettings.throwUnmocked = true; + + $.ajax({ + url: '/unmocked-ajax-call', + error: (error) => { + assert.ok(error, 'Expected the call to fail because it was not mocked'); + done(); + }, + complete: (xhr) => { + assert.ok(false, 'Expected a failure'); + done(); + } + }); + }); } } diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index b0838f9a8d..4b0ebd1614 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -37,13 +37,12 @@ declare const $: JQueryStatic; // Used by JQuery.Event type _Event = Event; -// Used by JQuery.Promise3 and JQuery.Promise -type _Promise = Promise; -interface JQueryStatic { +interface JQueryStatic { /** - * @see {@link http://api.jquery.com/jquery.ajax/#jQuery-ajax1} - * @deprecated Use jQuery.ajaxSetup(options) + * @see \`{@link http://api.jquery.com/jquery.ajax/#jQuery-ajax1 }\` + * + * @deprecated Use \`{@link JQueryStatic.ajaxSetup }\`. */ ajaxSettings: JQuery.AjaxSettings; /** @@ -52,41 +51,44 @@ interface JQueryStatic { * any synchronous or asynchronous function. * * @param beforeStart A function that is called just before the constructor returns. - * @see {@link https://api.jquery.com/jQuery.Deferred/} + * @see \`{@link https://api.jquery.com/jQuery.Deferred/ }\` * @since 1.5 */ Deferred: JQuery.DeferredStatic; - Event: JQuery.EventStatic; + Event: JQuery.EventStatic; /** * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize * CSS property naming, or create custom properties. * - * @see {@link https://api.jquery.com/jQuery.cssHooks/} + * @see \`{@link https://api.jquery.com/jQuery.cssHooks/ }\` * @since 1.4.3 */ - cssHooks: JQuery.PlainObject>; + // Set to HTMLElement to minimize breaks but should probably be Element. + cssHooks: JQuery.PlainObject>; /** * An object containing all CSS properties that may be used without a unit. The .css() method uses this * object to see if it may append px to unitless values. * - * @see {@link https://api.jquery.com/jQuery.cssNumber/} + * @see \`{@link https://api.jquery.com/jQuery.cssNumber/ }\` * @since 1.4.3 */ cssNumber: JQuery.PlainObject; - readonly fn: JQuery; + // Set to HTMLElement to minimize breaks but should probably be Element. + readonly fn: JQuery; fx: { /** * The rate (in milliseconds) at which animations fire. * - * @see {@link https://api.jquery.com/jQuery.fx.interval/} + * @see \`{@link https://api.jquery.com/jQuery.fx.interval/ }\` * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. See \`{@link https://api.jquery.com/jQuery.fx.interval/ }\`. */ interval: number; /** * Globally disable all animations. * - * @see {@link https://api.jquery.com/jQuery.fx.off/} + * @see \`{@link https://api.jquery.com/jQuery.fx.off/ }\` * @since 1.3 */ off: boolean; @@ -95,10 +97,10 @@ interface JQueryStatic { /** * A Promise-like object (or "thenable") that resolves when the document is ready. * - * @see {@link https://api.jquery.com/jQuery.ready/} + * @see \`{@link https://api.jquery.com/jQuery.ready/ }\` * @since 1.8 */ - ready: JQuery.Thenable>; + ready: JQuery.Thenable; /** * A collection of properties that represent the presence of different browser features or bugs. * Intended for jQuery's internal use; specific properties may be removed when they are no longer @@ -106,12 +108,17 @@ interface JQueryStatic { * needs, we strongly recommend the use of an external library such as Modernizr instead of dependency * on properties in jQuery.support. * - * @see {@link https://api.jquery.com/jQuery.support/} + * @see \`{@link https://api.jquery.com/jQuery.support/ }\` * @since 1.3 - * @deprecated 1.9 + * + * @deprecated Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. */ support: JQuery.PlainObject; - valHooks: JQuery.PlainObject>; + // Set to HTMLElement to minimize breaks but should probably be Element. + valHooks: JQuery.PlainObject>; + // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. + // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. + (window: Window, discriminator: boolean): JQueryStatic; /** * Creates DOM elements on the fly from the provided string of raw HTML. * @@ -119,48 +126,74 @@ interface JQueryStatic { * A string defining a single, standalone, HTML element (e.g.

or
). * @param ownerDocument_attributes A document in which the new elements will be created. * An object of attributes, events, and methods to call on the newly-created element. - * @see {@link https://api.jquery.com/jQuery/} + * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 * @since 1.4 */ - (html: JQuery.htmlString, ownerDocument_attributes: Document | JQuery.PlainObject): JQuery; + // tslint:disable-next-line:no-unnecessary-generics + (html: JQuery.htmlString, ownerDocument_attributes?: Document | JQuery.PlainObject): JQuery; /** * Accepts a string containing a CSS selector which is then used to match a set of elements. * * @param selector A string containing a selector expression * @param context A DOM Element, Document, or jQuery to use as context - * @see {@link https://api.jquery.com/jQuery/} + * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 */ - (selector: JQuery.Selector, context: Element | Document | JQuery | undefined): JQuery; - // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. - // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. - (window: Window, discriminator: boolean): JQueryStatic; + // tslint:disable-next-line:no-unnecessary-generics + (selector: JQuery.Selector, context?: Element | Document | JQuery): JQuery; /** - * Creates DOM elements on the fly from the provided string of raw HTML. + * Return a collection of matched elements either found in the DOM based on passed argument(s) or created + * by passing an HTML string. * + * @param element_elementArray A DOM element to wrap in a jQuery object. + * An array containing a set of DOM elements to wrap in a jQuery object. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + */ + (element_elementArray: T | ArrayLike): JQuery; + /** + * Return a collection of matched elements either found in the DOM based on passed argument(s) or created + * by passing an HTML string. + * + * @param selection An existing jQuery object to clone. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + */ + (selection: JQuery): JQuery; + /** * Binds a function to be executed when the DOM has finished loading. * - * @param selector_object_callback A string containing a selector expression - * A DOM element to wrap in a jQuery object. - * An array containing a set of DOM elements to wrap in a jQuery object. - * A plain object to wrap in a jQuery object. - * An existing jQuery object to clone. - * The function to execute when the DOM is ready. - * @see {@link https://api.jquery.com/jQuery/} + * @param callback The function to execute when the DOM is ready. + * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 + */ + // tslint:disable-next-line:no-unnecessary-generics unified-signatures + (callback: ((this: Document, $: JQueryStatic) => void)): JQuery; + /** + * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. + * + * @param object A plain object to wrap in a jQuery object. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + */ + (object: T): JQuery; + /** + * Returns an empty jQuery set. + * + * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.4 */ - (selector_object_callback?: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery | - JQuery.PlainObject | Window | - ((this: Document, $: JQueryStatic) => void)): JQuery; + // tslint:disable-next-line:no-unnecessary-generics + (): JQuery; /** * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. * * @param flags An optional list of space-separated flags that change how the callback list behaves. - * @see {@link https://api.jquery.com/jQuery.Callbacks/} + * @see \`{@link https://api.jquery.com/jQuery.Callbacks/ }\` * @since 1.7 */ + // tslint:disable-next-line:ban-types no-unnecessary-generics Callbacks(flags?: string): JQuery.Callbacks; /** * Perform an asynchronous HTTP (Ajax) request. @@ -168,7 +201,7 @@ interface JQueryStatic { * @param url A string containing the URL to which the request is sent. * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can * be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. - * @see {@link https://api.jquery.com/jQuery.ajax/} + * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` * @since 1.5 */ ajax(url: string, settings?: JQuery.AjaxSettings): JQuery.jqXHR; @@ -177,7 +210,7 @@ interface JQueryStatic { * * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can * be set for any option with $.ajaxSetup(). - * @see {@link https://api.jquery.com/jQuery.ajax/} + * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` * @since 1.0 */ ajax(settings?: JQuery.AjaxSettings): JQuery.jqXHR; @@ -187,7 +220,7 @@ interface JQueryStatic { * * @param dataTypes An optional string containing one or more space-separated dataTypes * @param handler A handler to set default values for future Ajax requests. - * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} + * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` * @since 1.5 */ ajaxPrefilter(dataTypes: string, @@ -197,7 +230,7 @@ interface JQueryStatic { * are processed by $.ajax(). * * @param handler A handler to set default values for future Ajax requests. - * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} + * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` * @since 1.5 */ ajaxPrefilter(handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; @@ -205,7 +238,7 @@ interface JQueryStatic { * Set default values for future Ajax requests. Its use is not recommended. * * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - * @see {@link https://api.jquery.com/jQuery.ajaxSetup/} + * @see \`{@link https://api.jquery.com/jQuery.ajaxSetup/ }\` * @since 1.1 */ ajaxSetup(options: JQuery.AjaxSettings): JQuery.AjaxSettings; @@ -214,13 +247,13 @@ interface JQueryStatic { * * @param dataType A string identifying the data type to use * @param handler A handler to return the new transport object to use with the data type provided in the first argument. - * @see {@link https://api.jquery.com/jQuery.ajaxTransport/} + * @see \`{@link https://api.jquery.com/jQuery.ajaxTransport/ }\` * @since 1.5 */ ajaxTransport(dataType: string, handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => JQuery.Transport | void): void; /** - * @deprecated 3.3 + * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3384 }\`. */ camelCase(value: string): string; /** @@ -228,7 +261,7 @@ interface JQueryStatic { * * @param container The DOM element that may contain the other element. * @param contained The DOM element that may be contained by (a descendant of) the other element. - * @see {@link https://api.jquery.com/jQuery.contains/} + * @see \`{@link https://api.jquery.com/jQuery.contains/ }\` * @since 1.4 */ contains(container: Element, contained: Element): boolean; @@ -239,7 +272,7 @@ interface JQueryStatic { * * @param element The DOM element to query for the data. * @param key Name of the data stored. - * @see {@link https://api.jquery.com/jQuery.data/} + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` * @since 1.2.3 */ data(element: Element, key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures @@ -249,7 +282,7 @@ interface JQueryStatic { * @param element The DOM element to associate with the data. * @param key A string naming the piece of data to set. * @param value The new data value; this can be any Javascript type except undefined. - * @see {@link https://api.jquery.com/jQuery.data/} + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` * @since 1.2.3 */ data(element: Element, key: string, value: T): T; @@ -259,7 +292,7 @@ interface JQueryStatic { * * @param element The DOM element to query for the data. * @param key Name of the data stored. - * @see {@link https://api.jquery.com/jQuery.data/} + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` * @since 1.2.3 * @since 1.4 */ @@ -269,7 +302,7 @@ interface JQueryStatic { * * @param element A DOM element from which to remove and execute a queued function. * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/jQuery.dequeue/} + * @see \`{@link https://api.jquery.com/jQuery.dequeue/ }\` * @since 1.3 */ dequeue(element: Element, queueName?: string): void; @@ -280,7 +313,7 @@ interface JQueryStatic { * * @param array The array to iterate over. * @param callback The function that will be executed on every object. - * @see {@link https://api.jquery.com/jQuery.each/} + * @see \`{@link https://api.jquery.com/jQuery.each/ }\` * @since 1.0 */ each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => false | any): ArrayLike; @@ -291,7 +324,7 @@ interface JQueryStatic { * * @param obj The object to iterate over. * @param callback The function that will be executed on every object. - * @see {@link https://api.jquery.com/jQuery.each/} + * @see \`{@link https://api.jquery.com/jQuery.each/ }\` * @since 1.0 */ each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => false | any): T; @@ -299,7 +332,7 @@ interface JQueryStatic { * Takes a string and throws an exception containing it. * * @param message The message to send out. - * @see {@link https://api.jquery.com/jQuery.error/} + * @see \`{@link https://api.jquery.com/jQuery.error/ }\` * @since 1.4.1 */ error(message: string): any; @@ -307,7 +340,7 @@ interface JQueryStatic { * Escapes any character that has a special meaning in a CSS selector. * * @param selector A string containing a selector expression to escape. - * @see {@link https://api.jquery.com/jQuery.escapeSelector/} + * @see \`{@link https://api.jquery.com/jQuery.escapeSelector/ }\` * @since 3.0 */ escapeSelector(selector: JQuery.Selector): JQuery.Selector; @@ -316,7 +349,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; @@ -325,7 +358,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; @@ -334,7 +367,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; @@ -343,7 +376,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U, object2: V, object3: W): T & U & V & W; @@ -352,7 +385,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U, object2: V): T & U & V; @@ -361,7 +394,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: T, object1: U): T & U; @@ -370,7 +403,7 @@ interface JQueryStatic { * * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.1.4 */ extend(deep: true, target: any, object1: any, ...objects: any[]): any; @@ -379,7 +412,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; @@ -388,7 +421,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; @@ -397,7 +430,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; @@ -406,7 +439,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U, object2: V, object3: W): T & U & V & W; @@ -415,7 +448,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U, object2: V): T & U & V; @@ -424,7 +457,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: T, object1: U): T & U; @@ -433,7 +466,7 @@ interface JQueryStatic { * * @param target An object that will receive the new properties if additional objects are passed in or that will * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` * @since 1.0 */ extend(target: any, object1: any, ...objects: any[]): any; @@ -445,7 +478,7 @@ interface JQueryStatic { * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but * you can use null or jQuery.noop as a placeholder. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.get/} + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 */ get(url: string, @@ -459,7 +492,7 @@ interface JQueryStatic { * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but * you can use null or jQuery.noop as a placeholder. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.get/} + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 */ get(url: string, @@ -472,7 +505,7 @@ interface JQueryStatic { * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but * you can use null or jQuery.noop as a placeholder. * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.get/} + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 */ get(url: string, @@ -484,7 +517,7 @@ interface JQueryStatic { * A set of key/value pairs that configure the Ajax request. All properties except for url are * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a * complete list of all settings. The type option will automatically be set to GET. - * @see {@link https://api.jquery.com/jQuery.get/} + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 * @since 1.12 * @since 2.2 @@ -496,7 +529,7 @@ interface JQueryStatic { * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. - * @see {@link https://api.jquery.com/jQuery.getJSON/} + * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` * @since 1.0 */ getJSON(url: string, @@ -508,7 +541,7 @@ interface JQueryStatic { * @param url A string containing the URL to which the request is sent. * @param success_data A callback function that is executed if the request succeeds. * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.getJSON/} + * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` * @since 1.0 */ getJSON(url: string, @@ -518,7 +551,7 @@ interface JQueryStatic { * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. - * @see {@link https://api.jquery.com/jQuery.getScript/} + * @see \`{@link https://api.jquery.com/jQuery.getScript/ }\` * @since 1.0 */ getScript(url: string, @@ -527,7 +560,7 @@ interface JQueryStatic { * Execute some JavaScript code globally. * * @param code The JavaScript code to execute. - * @see {@link https://api.jquery.com/jQuery.globalEval/} + * @see \`{@link https://api.jquery.com/jQuery.globalEval/ }\` * @since 1.0.4 */ globalEval(code: string): void; @@ -540,7 +573,7 @@ interface JQueryStatic { * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements * for which "callback" returns true. If "invert" is true, then the function returns an array * consisting of all elements for which "callback" returns false. - * @see {@link https://api.jquery.com/jQuery.grep/} + * @see \`{@link https://api.jquery.com/jQuery.grep/ }\` * @since 1.0 */ grep(array: ArrayLike, @@ -550,7 +583,7 @@ interface JQueryStatic { * Determine whether an element has any jQuery data associated with it. * * @param element A DOM element to be checked for data. - * @see {@link https://api.jquery.com/jQuery.hasData/} + * @see \`{@link https://api.jquery.com/jQuery.hasData/ }\` * @since 1.5 */ hasData(element: Element): boolean; @@ -558,16 +591,17 @@ interface JQueryStatic { * Holds or releases the execution of jQuery's ready event. * * @param hold Indicates whether the ready hold is being requested or released - * @see {@link https://api.jquery.com/jQuery.holdReady/} + * @see \`{@link https://api.jquery.com/jQuery.holdReady/ }\` * @since 1.6 - * @deprecated 3.2 + * + * @deprecated Deprecated since 3.2. See \`{@link https://github.com/jquery/jquery/issues/3288 }\`. */ holdReady(hold: boolean): void; /** * Modify and filter HTML strings passed through jQuery manipulation methods. * * @param html The HTML string on which to operate. - * @see {@link https://api.jquery.com/jQuery.htmlPrefilter/} + * @see \`{@link https://api.jquery.com/jQuery.htmlPrefilter/ }\` * @since 1.12/2.2 */ htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; @@ -577,7 +611,7 @@ interface JQueryStatic { * @param value The value to search for. * @param array An array through which to search. * @param fromIndex The index of the array at which to begin the search. The default is 0, which will search the whole array. - * @see {@link https://api.jquery.com/jQuery.inArray/} + * @see \`{@link https://api.jquery.com/jQuery.inArray/ }\` * @since 1.2 */ inArray(value: T, array: T[], fromIndex?: number): number; @@ -585,16 +619,17 @@ interface JQueryStatic { * Determine whether the argument is an array. * * @param obj Object to test whether or not it is an array. - * @see {@link https://api.jquery.com/jQuery.isArray/} + * @see \`{@link https://api.jquery.com/jQuery.isArray/ }\` * @since 1.3 - * @deprecated 3.2 + * + * @deprecated Deprecated since 3.2. Use \`{@link Array.isArray }\`. */ isArray(obj: any): obj is any[]; /** * Check to see if an object is empty (contains no enumerable properties). * * @param obj The object that will be checked to see if it's empty. - * @see {@link https://api.jquery.com/jQuery.isEmptyObject/} + * @see \`{@link https://api.jquery.com/jQuery.isEmptyObject/ }\` * @since 1.4 */ isEmptyObject(obj: any): boolean; @@ -602,25 +637,28 @@ interface JQueryStatic { * Determine if the argument passed is a JavaScript function object. * * @param obj Object to test whether or not it is a function. - * @see {@link https://api.jquery.com/jQuery.isFunction/} + * @see \`{@link https://api.jquery.com/jQuery.isFunction/ }\` * @since 1.2 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use `typeof x === "function"`. */ + // tslint:disable-next-line:ban-types isFunction(obj: any): obj is Function; /** * Determines whether its argument represents a JavaScript number. * * @param value The value to be tested. - * @see {@link https://api.jquery.com/jQuery.isNumeric/} + * @see \`{@link https://api.jquery.com/jQuery.isNumeric/ }\` * @since 1.7 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/2960 }\`. */ isNumeric(value: any): value is number; /** * Check to see if an object is a plain object (created using "{}" or "new Object"). * * @param obj The object that will be checked to see if it's a plain object. - * @see {@link https://api.jquery.com/jQuery.isPlainObject/} + * @see \`{@link https://api.jquery.com/jQuery.isPlainObject/ }\` * @since 1.4 */ isPlainObject(obj: any): obj is JQuery.PlainObject; @@ -628,16 +666,17 @@ interface JQueryStatic { * Determine whether the argument is a window. * * @param obj Object to test whether or not it is a window. - * @see {@link https://api.jquery.com/jQuery.isWindow/} + * @see \`{@link https://api.jquery.com/jQuery.isWindow/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3629 }\`. */ isWindow(obj: any): obj is Window; /** * Check to see if a DOM node is within an XML document (or is an XML document). * * @param node The DOM node that will be checked to see if it's in an XML document. - * @see {@link https://api.jquery.com/jQuery.isXMLDoc/} + * @see \`{@link https://api.jquery.com/jQuery.isXMLDoc/ }\` * @since 1.1.4 */ isXMLDoc(node: Node): boolean; @@ -645,7 +684,7 @@ interface JQueryStatic { * Convert an array-like object into a true JavaScript array. * * @param obj Any object to turn into a native Array. - * @see {@link https://api.jquery.com/jQuery.makeArray/} + * @see \`{@link https://api.jquery.com/jQuery.makeArray/ }\` * @since 1.2 */ makeArray(obj: ArrayLike): T[]; @@ -656,10 +695,10 @@ interface JQueryStatic { * @param callback The function to process each item against. The first argument to the function is the array item, the * second argument is the index in array The function can return any value. A returned array will be * flattened into the resulting array. Within the function, this refers to the global (window) object. - * @see {@link https://api.jquery.com/jQuery.map/} + * @see \`{@link https://api.jquery.com/jQuery.map/ }\` * @since 1.0 */ - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => R): R[]; + map(array: T[], callback: (this: Window, elementOfArray: T, indexInArray: number) => JQuery.TypeOrArray | null | undefined): TReturn[]; /** * Translate all items in an array or object to new array of items. * @@ -668,16 +707,16 @@ interface JQueryStatic { * second argument is the key of the object property. The function can return any value to add to the * array. A returned array will be flattened into the resulting array. Within the function, this refers * to the global (window) object. - * @see {@link https://api.jquery.com/jQuery.map/} + * @see \`{@link https://api.jquery.com/jQuery.map/ }\` * @since 1.6 */ - map(obj: T, callback: (propertyOfObject: T[K], key: K) => R): R[]; + map(obj: T, callback: (this: Window, propertyOfObject: T[K], key: K) => JQuery.TypeOrArray | null | undefined): TReturn[]; /** * Merge the contents of two arrays together into the first array. * * @param first The first array-like object to merge, the elements of second added. * @param second The second array-like object to merge into the first, unaltered. - * @see {@link https://api.jquery.com/jQuery.merge/} + * @see \`{@link https://api.jquery.com/jQuery.merge/ }\` * @since 1.0 */ merge(first: ArrayLike, second: ArrayLike): Array; @@ -685,23 +724,24 @@ interface JQueryStatic { * Relinquish jQuery's control of the $ variable. * * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - * @see {@link https://api.jquery.com/jQuery.noConflict/} + * @see \`{@link https://api.jquery.com/jQuery.noConflict/ }\` * @since 1.0 */ noConflict(removeAll?: boolean): this; /** * An empty function. * - * @see {@link https://api.jquery.com/jQuery.noop/} + * @see \`{@link https://api.jquery.com/jQuery.noop/ }\` * @since 1.4 */ noop(): undefined; /** * Return a number representing the current time. * - * @see {@link https://api.jquery.com/jQuery.now/} + * @see \`{@link https://api.jquery.com/jQuery.now/ }\` * @since 1.4.3 - * @deprecated 3.3 Use Date.now(). + * + * @deprecated Deprecated since 3.3. Use \`{@link Date.now }\`. */ now(): number; /** @@ -711,7 +751,7 @@ interface JQueryStatic { * * @param obj An array, a plain object, or a jQuery object to serialize. * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - * @see {@link https://api.jquery.com/jQuery.param/} + * @see \`{@link https://api.jquery.com/jQuery.param/ }\` * @since 1.2 * @since 1.4 */ @@ -722,7 +762,7 @@ interface JQueryStatic { * @param data HTML string to be parsed * @param context Document element to serve as the context in which the HTML fragment will be created * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - * @see {@link https://api.jquery.com/jQuery.parseHTML/} + * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` * @since 1.8 */ parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; @@ -732,7 +772,7 @@ interface JQueryStatic { * @param data HTML string to be parsed * @param context_keepScripts Document element to serve as the context in which the HTML fragment will be created * A Boolean indicating whether to include scripts passed in the HTML string - * @see {@link https://api.jquery.com/jQuery.parseHTML/} + * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` * @since 1.8 */ parseHTML(data: string, context_keepScripts?: Document | null | boolean): JQuery.Node[]; @@ -740,16 +780,17 @@ interface JQueryStatic { * Takes a well-formed JSON string and returns the resulting JavaScript value. * * @param json The JSON string to parse. - * @see {@link https://api.jquery.com/jQuery.parseJSON/} + * @see \`{@link https://api.jquery.com/jQuery.parseJSON/ }\` * @since 1.4.1 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JSON.parse }\`. */ parseJSON(json: string): any; /** * Parses a string into an XML document. * * @param data a well-formed XML string to be parsed - * @see {@link https://api.jquery.com/jQuery.parseXML/} + * @see \`{@link https://api.jquery.com/jQuery.parseXML/ }\` * @since 1.5 */ parseXML(data: string): XMLDocument; @@ -761,7 +802,7 @@ interface JQueryStatic { * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but * can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.post/} + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 */ post(url: string, @@ -775,7 +816,7 @@ interface JQueryStatic { * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but * can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.post/} + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 */ post(url: string, @@ -788,7 +829,7 @@ interface JQueryStatic { * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but * can be null in that case. * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.post/} + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 */ post(url: string, @@ -800,7 +841,7 @@ interface JQueryStatic { * A set of key/value pairs that configure the Ajax request. All properties except for url are * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a * complete list of all settings. Type will automatically be set to POST. - * @see {@link https://api.jquery.com/jQuery.post/} + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 * @since 1.12 * @since 2.2 @@ -820,9 +861,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, @@ -833,9 +875,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, @@ -846,9 +889,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B, c: C, d: D, e: E) => TReturn, @@ -859,9 +903,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B, c: C, d: D) => TReturn, @@ -872,9 +917,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B, c: C) => TReturn, @@ -885,9 +931,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A, b: B) => TReturn, @@ -898,10 +945,11 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4` * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (a: A) => TReturn, @@ -912,9 +960,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: () => TReturn, context: null | undefined): () => TReturn; @@ -928,9 +977,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T) => TReturn, @@ -1050,9 +1107,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U) => TReturn, @@ -1172,9 +1237,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U, v: V) => TReturn, @@ -1294,9 +1367,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U, v: V, w: W) => TReturn, @@ -1416,9 +1497,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U, v: V, w: W, x: X) => TReturn, @@ -1538,9 +1627,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, @@ -1660,9 +1757,10 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, @@ -1785,9 +1890,10 @@ interface JQueryStatic { * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.9 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (...args: any[]) => TReturn, context: null | undefined, @@ -1808,10 +1914,11 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4` * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: () => TReturn, @@ -1931,10 +2045,11 @@ interface JQueryStatic { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy { * @param fn The function whose context will be changed. * @param context The object to which the context (this) of the function should be set. * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(fn: (...args: any[]) => TReturn, @@ -2922,10 +3093,11 @@ interface JQueryStatic { * @param context The object to which the context of the function should be set. * @param name The name of the function whose context will be changed (should be a property of the context object). * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - * @see {@link https://api.jquery.com/jQuery.proxy/} + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` * @since 1.4 * @since 1.6 - * @deprecated 3.3 Use Function#bind. + * + * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. */ proxy(context: TContext, name: keyof TContext, @@ -2942,7 +3114,7 @@ interface JQueryStatic { * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param newQueue The new function to add to the queue. * An array of functions to replace the current queue contents. - * @see {@link https://api.jquery.com/jQuery.queue/} + * @see \`{@link https://api.jquery.com/jQuery.queue/ }\` * @since 1.3 */ queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; @@ -2950,7 +3122,7 @@ interface JQueryStatic { * Handles errors thrown synchronously in functions wrapped in jQuery(). * * @param error An error thrown in the function wrapped in jQuery(). - * @see {@link https://api.jquery.com/jQuery.readyException/} + * @see \`{@link https://api.jquery.com/jQuery.readyException/ }\` * @since 3.1 */ readyException(error: Error): any; @@ -2959,7 +3131,7 @@ interface JQueryStatic { * * @param element A DOM element from which to remove data. * @param name A string naming the piece of data to remove. - * @see {@link https://api.jquery.com/jQuery.removeData/} + * @see \`{@link https://api.jquery.com/jQuery.removeData/ }\` * @since 1.2.3 */ removeData(element: Element, name?: string): void; @@ -2969,37 +3141,37 @@ interface JQueryStatic { * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` * @since 1.1 */ - speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; + speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * * @param duration A string or number determining how long the animation will run. * @param easing_complete A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` * @since 1.0 * @since 1.1 */ - speed(duration: JQuery.Duration, - easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; + speed(duration: JQuery.Duration, + easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * * @param duration_complete_settings A string or number determining how long the animation will run. * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` * @since 1.0 * @since 1.1 */ - speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; + speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; /** * Remove the whitespace from the beginning and end of a string. * * @param str The string to trim. - * @see {@link https://api.jquery.com/jQuery.trim/} + * @see \`{@link https://api.jquery.com/jQuery.trim/ }\` * @since 1.0 */ trim(str: string): string; @@ -3007,19 +3179,21 @@ interface JQueryStatic { * Determine the internal JavaScript [[Class]] of an object. * * @param obj Object to get the internal JavaScript [[Class]] of. - * @see {@link https://api.jquery.com/jQuery.type/} + * @see \`{@link https://api.jquery.com/jQuery.type/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/jquery/issues/3605 }`. */ type(obj: any): 'array' | 'boolean' | 'date' | 'error' | 'function' | 'null' | 'number' | 'object' | 'regexp' | 'string' | 'symbol' | 'undefined'; /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on + * @description Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on * arrays of DOM elements, not strings or numbers. * * @param array The Array of DOM elements. - * @see {@link https://api.jquery.com/jQuery.unique/} + * @see \`{@link https://api.jquery.com/jQuery.unique/ }\` * @since 1.1.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQueryStatic.uniqueSort }`. */ unique(array: T[]): T[]; /** @@ -3027,7 +3201,7 @@ interface JQueryStatic { * arrays of DOM elements, not strings or numbers. * * @param array The Array of DOM elements. - * @see {@link https://api.jquery.com/jQuery.uniqueSort/} + * @see \`{@link https://api.jquery.com/jQuery.uniqueSort/ }\` * @since 1.12 * @since 2.2 */ @@ -3036,80 +3210,80 @@ interface JQueryStatic { * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ when - (deferredT: JQuery.Promise | JQuery.Thenable | TR1, - deferredU: JQuery.Promise | JQuery.Thenable | UR1, - deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3( + deferredT: JQuery.Promise | JQuery.Thenable | TR1, // tslint:disable-line:use-default-type-parameter + deferredU: JQuery.Promise | JQuery.Thenable | UR1, // tslint:disable-line:use-default-type-parameter + deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3; /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ when - (deferredT: JQuery.Promise | JQuery.Thenable | TR1, - deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2( + deferredT: JQuery.Promise | JQuery.Thenable | TR1, // tslint:disable-line:use-default-type-parameter + deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2; /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ when - (deferredT: JQuery.Promise3 | - JQuery.Promise2): JQuery.Promise3; + TR3 = never, TJ3 = never>( + deferredT: JQuery.Promise3 | + JQuery.Promise2): JQuery.Promise3; /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ - when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; + when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; // tslint:disable-line:use-default-type-parameter /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * * @param deferreds Zero or more Thenable objects. - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ - when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; + when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; // tslint:disable-line:use-default-type-parameter /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. * * @param deferreds Zero or more Thenable objects. - * @see {@link https://api.jquery.com/jQuery.when/} + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` * @since 1.5 */ when(...deferreds: any[]): JQuery.Promise; } -interface JQuery extends Iterable { +interface JQuery extends Iterable { /** * A string containing the jQuery version number. * - * @see {@link https://api.jquery.com/jquery/} + * @see \`{@link https://api.jquery.com/jquery/ }\` * @since 1.0 */ jquery: string; /** * The number of elements in the jQuery object. * - * @see {@link https://api.jquery.com/length/} + * @see \`{@link https://api.jquery.com/length/ }\` * @since 1.0 */ length: number; @@ -3119,7 +3293,7 @@ interface JQuery extends Iterable * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. * @param context The point in the document at which the selector should begin matching; similar to the context * argument of the $(selector, context) method. - * @see {@link https://api.jquery.com/add/} + * @see \`{@link https://api.jquery.com/add/ }\` * @since 1.4 */ add(selector: JQuery.Selector, context: Element): this; @@ -3130,7 +3304,7 @@ interface JQuery extends Iterable * One or more elements to add to the set of matched elements. * An HTML fragment to add to the set of matched elements. * An existing jQuery object to add to the set of matched elements. - * @see {@link https://api.jquery.com/add/} + * @see \`{@link https://api.jquery.com/add/ }\` * @since 1.0 * @since 1.3.2 */ @@ -3139,7 +3313,7 @@ interface JQuery extends Iterable * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. * * @param selector A string containing a selector expression to match the current set of elements against. - * @see {@link https://api.jquery.com/addBack/} + * @see \`{@link https://api.jquery.com/addBack/ }\` * @since 1.8 */ addBack(selector?: JQuery.Selector): this; @@ -3151,7 +3325,7 @@ interface JQuery extends Iterable * A function returning one or more space-separated class names to be added to the existing class * name(s). Receives the index position of the element in the set and the existing class name(s) as * arguments. Within the function, this refers to the current element in the set. - * @see {@link https://api.jquery.com/addClass/} + * @see \`{@link https://api.jquery.com/addClass/ }\` * @since 1.0 * @since 1.4 * @since 3.3 @@ -3162,7 +3336,7 @@ interface JQuery extends Iterable * * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or * jQuery objects to insert after each element in the set of matched elements. - * @see {@link https://api.jquery.com/after/} + * @see \`{@link https://api.jquery.com/after/ }\` * @since 1.0 */ after(...contents: Array>>): this; @@ -3173,7 +3347,7 @@ interface JQuery extends Iterable * after each element in the set of matched elements. Receives the index position of the element in the * set and the old HTML value of the element as arguments. Within the function, this refers to the * current element in the set. - * @see {@link https://api.jquery.com/after/} + * @see \`{@link https://api.jquery.com/after/ }\` * @since 1.4 * @since 1.10 */ @@ -3182,7 +3356,7 @@ interface JQuery extends Iterable * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxComplete/} + * @see \`{@link https://api.jquery.com/ajaxComplete/ }\` * @since 1.0 */ ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; @@ -3190,7 +3364,7 @@ interface JQuery extends Iterable * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxError/} + * @see \`{@link https://api.jquery.com/ajaxError/ }\` * @since 1.0 */ ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; @@ -3198,7 +3372,7 @@ interface JQuery extends Iterable * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxSend/} + * @see \`{@link https://api.jquery.com/ajaxSend/ }\` * @since 1.0 */ ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; @@ -3206,7 +3380,7 @@ interface JQuery extends Iterable * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxStart/} + * @see \`{@link https://api.jquery.com/ajaxStart/ }\` * @since 1.0 */ ajaxStart(handler: (this: Document) => void | false): this; @@ -3214,7 +3388,7 @@ interface JQuery extends Iterable * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxStop/} + * @see \`{@link https://api.jquery.com/ajaxStop/ }\` * @since 1.0 */ ajaxStop(handler: (this: Document) => void | false): this; @@ -3222,7 +3396,7 @@ interface JQuery extends Iterable * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. * * @param handler The function to be invoked. - * @see {@link https://api.jquery.com/ajaxSuccess/} + * @see \`{@link https://api.jquery.com/ajaxSuccess/ }\` * @since 1.0 */ ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; @@ -3233,7 +3407,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/animate/} + * @see \`{@link https://api.jquery.com/animate/ }\` * @since 1.0 */ animate(properties: JQuery.PlainObject, @@ -3247,7 +3421,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/animate/} + * @see \`{@link https://api.jquery.com/animate/ }\` * @since 1.0 */ animate(properties: JQuery.PlainObject, @@ -3258,7 +3432,7 @@ interface JQuery extends Iterable * * @param properties An object of CSS properties and values that the animation will move toward. * @param options A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/animate/} + * @see \`{@link https://api.jquery.com/animate/ }\` * @since 1.0 */ animate(properties: JQuery.PlainObject, @@ -3268,7 +3442,7 @@ interface JQuery extends Iterable * * @param properties An object of CSS properties and values that the animation will move toward. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/animate/} + * @see \`{@link https://api.jquery.com/animate/ }\` * @since 1.0 */ animate(properties: JQuery.PlainObject, @@ -3278,7 +3452,7 @@ interface JQuery extends Iterable * * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or * jQuery objects to insert at the end of each element in the set of matched elements. - * @see {@link https://api.jquery.com/append/} + * @see \`{@link https://api.jquery.com/append/ }\` * @since 1.0 */ append(...contents: Array>>): this; @@ -3289,7 +3463,7 @@ interface JQuery extends Iterable * the end of each element in the set of matched elements. Receives the index position of the element * in the set and the old HTML value of the element as arguments. Within the function, this refers to * the current element in the set. - * @see {@link https://api.jquery.com/append/} + * @see \`{@link https://api.jquery.com/append/ }\` * @since 1.4 */ append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; @@ -3298,7 +3472,7 @@ interface JQuery extends Iterable * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements * will be inserted at the end of the element(s) specified by this parameter. - * @see {@link https://api.jquery.com/appendTo/} + * @see \`{@link https://api.jquery.com/appendTo/ }\` * @since 1.0 */ appendTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; @@ -3309,7 +3483,7 @@ interface JQuery extends Iterable * @param value A value to set for the attribute. If null, the specified attribute will be removed (as in .removeAttr()). * A function returning the value to set. this is the current element. Receives the index position of * the element in the set and the old attribute value as arguments. - * @see {@link https://api.jquery.com/attr/} + * @see \`{@link https://api.jquery.com/attr/ }\` * @since 1.0 * @since 1.1 */ @@ -3319,7 +3493,7 @@ interface JQuery extends Iterable * Set one or more attributes for the set of matched elements. * * @param attributes An object of attribute-value pairs to set. - * @see {@link https://api.jquery.com/attr/} + * @see \`{@link https://api.jquery.com/attr/ }\` * @since 1.0 */ attr(attributes: JQuery.PlainObject): this; @@ -3327,7 +3501,7 @@ interface JQuery extends Iterable * Get the value of an attribute for the first element in the set of matched elements. * * @param attributeName The name of the attribute to get. - * @see {@link https://api.jquery.com/attr/} + * @see \`{@link https://api.jquery.com/attr/ }\` * @since 1.0 */ attr(attributeName: string): string | undefined; @@ -3336,7 +3510,7 @@ interface JQuery extends Iterable * * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or * jQuery objects to insert before each element in the set of matched elements. - * @see {@link https://api.jquery.com/before/} + * @see \`{@link https://api.jquery.com/before/ }\` * @since 1.0 */ before(...contents: Array>>): this; @@ -3347,7 +3521,7 @@ interface JQuery extends Iterable * before each element in the set of matched elements. Receives the index position of the element in * the set and the old HTML value of the element as arguments. Within the function, this refers to the * current element in the set. - * @see {@link https://api.jquery.com/before/} + * @see \`{@link https://api.jquery.com/before/ }\` * @since 1.4 * @since 1.10 */ @@ -3359,10 +3533,11 @@ interface JQuery extends Iterable * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/bind/} + * @see \`{@link https://api.jquery.com/bind/ }\` * @since 1.0 * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ bind(eventType: string, eventData: TData, @@ -3374,10 +3549,11 @@ interface JQuery extends Iterable * @param handler A function to execute each time the event is triggered. * Setting the second argument to false will attach a function that prevents the default action from * occurring and stops the event from bubbling. - * @see {@link https://api.jquery.com/bind/} + * @see \`{@link https://api.jquery.com/bind/ }\` * @since 1.0 * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ bind(eventType: string, handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false | null | undefined): this; @@ -3385,9 +3561,10 @@ interface JQuery extends Iterable * Attach a handler to an event for the elements. * * @param events An object containing one or more DOM event types and functions to execute for them. - * @see {@link https://api.jquery.com/bind/} + * @see \`{@link https://api.jquery.com/bind/ }\` * @since 1.4 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ bind(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; /** @@ -3395,9 +3572,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/blur/} + * @see \`{@link https://api.jquery.com/blur/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ blur(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3405,9 +3583,10 @@ interface JQuery extends Iterable * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/blur/} + * @see \`{@link https://api.jquery.com/blur/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ blur(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3415,9 +3594,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/change/} + * @see \`{@link https://api.jquery.com/change/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ change(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3425,16 +3605,17 @@ interface JQuery extends Iterable * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/change/} + * @see \`{@link https://api.jquery.com/change/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ change(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/children/} + * @see \`{@link https://api.jquery.com/children/ }\` * @since 1.0 */ children(selector?: JQuery.Selector): this; @@ -3442,7 +3623,7 @@ interface JQuery extends Iterable * Remove from the queue all items that have not yet been run. * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/clearQueue/} + * @see \`{@link https://api.jquery.com/clearQueue/ }\` * @since 1.4 */ clearQueue(queueName?: string): this; @@ -3451,9 +3632,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/click/} + * @see \`{@link https://api.jquery.com/click/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ click(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3461,9 +3643,10 @@ interface JQuery extends Iterable * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/click/} + * @see \`{@link https://api.jquery.com/click/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ click(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3474,7 +3657,7 @@ interface JQuery extends Iterable * to false in 1.5.1 and up. * @param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should * be copied. By default its value matches the first argument's value (which defaults to false). - * @see {@link https://api.jquery.com/clone/} + * @see \`{@link https://api.jquery.com/clone/ }\` * @since 1.0 * @since 1.5 */ @@ -3485,7 +3668,7 @@ interface JQuery extends Iterable * * @param selector A string containing a selector expression to match elements against. * @param context A DOM element within which a matching element may be found. - * @see {@link https://api.jquery.com/closest/} + * @see \`{@link https://api.jquery.com/closest/ }\` * @since 1.4 */ closest(selector: JQuery.Selector, context: Element): this; @@ -3496,7 +3679,7 @@ interface JQuery extends Iterable * @param selector A string containing a selector expression to match elements against. * A jQuery object to match elements against. * An element to match elements against. - * @see {@link https://api.jquery.com/closest/} + * @see \`{@link https://api.jquery.com/closest/ }\` * @since 1.3 * @since 1.6 */ @@ -3504,7 +3687,7 @@ interface JQuery extends Iterable /** * Get the children of each element in the set of matched elements, including text and comment nodes. * - * @see {@link https://api.jquery.com/contents/} + * @see \`{@link https://api.jquery.com/contents/ }\` * @since 1.2 */ contents(): JQuery; @@ -3513,9 +3696,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/contextmenu/} + * @see \`{@link https://api.jquery.com/contextmenu/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ contextmenu(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3523,9 +3707,10 @@ interface JQuery extends Iterable * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/contextmenu/} + * @see \`{@link https://api.jquery.com/contextmenu/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ contextmenu(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3535,7 +3720,7 @@ interface JQuery extends Iterable * @param value A value to set for the property. * A function returning the value to set. this is the current element. Receives the index position of * the element in the set and the old value as arguments. - * @see {@link https://api.jquery.com/css/} + * @see \`{@link https://api.jquery.com/css/ }\` * @since 1.0 * @since 1.4 */ @@ -3545,7 +3730,7 @@ interface JQuery extends Iterable * Set one or more CSS properties for the set of matched elements. * * @param properties An object of property-value pairs to set. - * @see {@link https://api.jquery.com/css/} + * @see \`{@link https://api.jquery.com/css/ }\` * @since 1.0 */ css(properties: JQuery.PlainObject string | number | void | undefined)>): this; @@ -3554,7 +3739,7 @@ interface JQuery extends Iterable * * @param propertyName A CSS property. * An array of one or more CSS properties. - * @see {@link https://api.jquery.com/css/} + * @see \`{@link https://api.jquery.com/css/ }\` * @since 1.0 */ css(propertyName: string): string; @@ -3562,7 +3747,7 @@ interface JQuery extends Iterable * Get the computed style properties for the first element in the set of matched elements. * * @param propertyNames An array of one or more CSS properties. - * @see {@link https://api.jquery.com/css/} + * @see \`{@link https://api.jquery.com/css/ }\` * @since 1.9 */ css(propertyNames: string[]): JQuery.PlainObject; @@ -3571,7 +3756,7 @@ interface JQuery extends Iterable * data(name, value) or by an HTML5 data-* attribute. * * @param key Name of the data stored. - * @see {@link https://api.jquery.com/data/} + * @see \`{@link https://api.jquery.com/data/ }\` * @since 1.2.3 */ data(key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures @@ -3580,7 +3765,7 @@ interface JQuery extends Iterable * * @param key A string naming the piece of data to set. * @param value The new data value; this can be any Javascript type except undefined. - * @see {@link https://api.jquery.com/data/} + * @see \`{@link https://api.jquery.com/data/ }\` * @since 1.2.3 */ data(key: string, value: any): this; @@ -3588,7 +3773,7 @@ interface JQuery extends Iterable * Store arbitrary data associated with the matched elements. * * @param obj An object of key-value pairs of data to update. - * @see {@link https://api.jquery.com/data/} + * @see \`{@link https://api.jquery.com/data/ }\` * @since 1.4.3 */ data(obj: JQuery.PlainObject): this; @@ -3597,7 +3782,7 @@ interface JQuery extends Iterable * data(name, value) or by an HTML5 data-* attribute. * * @param key Name of the data stored. - * @see {@link https://api.jquery.com/data/} + * @see \`{@link https://api.jquery.com/data/ }\` * @since 1.2.3 */ data(key: string): any; @@ -3605,7 +3790,7 @@ interface JQuery extends Iterable * Return the value at the named data store for the first element in the jQuery collection, as set by * data(name, value) or by an HTML5 data-* attribute. * - * @see {@link https://api.jquery.com/data/} + * @see \`{@link https://api.jquery.com/data/ }\` * @since 1.4 */ data(): JQuery.PlainObject; @@ -3614,9 +3799,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/dblclick/} + * @see \`{@link https://api.jquery.com/dblclick/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ dblclick(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3624,9 +3810,10 @@ interface JQuery extends Iterable * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/dblclick/} + * @see \`{@link https://api.jquery.com/dblclick/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ dblclick(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3634,7 +3821,7 @@ interface JQuery extends Iterable * * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/delay/} + * @see \`{@link https://api.jquery.com/delay/ }\` * @since 1.4 */ delay(duration: JQuery.Duration, queueName?: string): this; @@ -3647,9 +3834,10 @@ interface JQuery extends Iterable * "keydown," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/delegate/} + * @see \`{@link https://api.jquery.com/delegate/ }\` * @since 1.4.2 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ delegate(selector: JQuery.Selector, eventType: string, @@ -3663,9 +3851,10 @@ interface JQuery extends Iterable * @param eventType A string containing one or more space-separated JavaScript event types, such as "click" or * "keydown," or custom event names. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/delegate/} + * @see \`{@link https://api.jquery.com/delegate/ }\` * @since 1.4.2 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ delegate(selector: JQuery.Selector, eventType: string, @@ -3676,9 +3865,10 @@ interface JQuery extends Iterable * * @param selector A selector to filter the elements that trigger the event. * @param events A plain object of one or more event types and functions to execute for them. - * @see {@link https://api.jquery.com/delegate/} + * @see \`{@link https://api.jquery.com/delegate/ }\` * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. */ delegate(selector: JQuery.Selector, events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; @@ -3686,7 +3876,7 @@ interface JQuery extends Iterable * Execute the next function on the queue for the matched elements. * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/dequeue/} + * @see \`{@link https://api.jquery.com/dequeue/ }\` * @since 1.2 */ dequeue(queueName?: string): this; @@ -3694,7 +3884,7 @@ interface JQuery extends Iterable * Remove the set of matched elements from the DOM. * * @param selector A selector expression that filters the set of matched elements to be removed. - * @see {@link https://api.jquery.com/detach/} + * @see \`{@link https://api.jquery.com/detach/ }\` * @since 1.4 */ detach(selector?: JQuery.Selector): this; @@ -3702,14 +3892,14 @@ interface JQuery extends Iterable * Iterate over a jQuery object, executing a function for each matched element. * * @param fn A function to execute for each matched element. - * @see {@link https://api.jquery.com/each/} + * @see \`{@link https://api.jquery.com/each/ }\` * @since 1.0 */ each(fn: (this: TElement, index: number, element: TElement) => void | false): this; /** * Remove all child nodes of the set of matched elements from the DOM. * - * @see {@link https://api.jquery.com/empty/} + * @see \`{@link https://api.jquery.com/empty/ }\` * @since 1.0 */ empty(): this; @@ -3717,7 +3907,7 @@ interface JQuery extends Iterable * End the most recent filtering operation in the current chain and return the set of matched elements * to its previous state. * - * @see {@link https://api.jquery.com/end/} + * @see \`{@link https://api.jquery.com/end/ }\` * @since 1.0 */ end(): this; @@ -3726,7 +3916,7 @@ interface JQuery extends Iterable * * @param index An integer indicating the 0-based position of the element. * An integer indicating the position of the element, counting backwards from the last element in the set. - * @see {@link https://api.jquery.com/eq/} + * @see \`{@link https://api.jquery.com/eq/ }\` * @since 1.1.2 * @since 1.4 */ @@ -3735,7 +3925,7 @@ interface JQuery extends Iterable * Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. * * @param obj An object to merge onto the jQuery prototype. - * @see {@link https://api.jquery.com/jQuery.fn.extend/} + * @see \`{@link https://api.jquery.com/jQuery.fn.extend/ }\` * @since 1.0 */ extend(obj: object): this; @@ -3745,7 +3935,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeIn/} + * @see \`{@link https://api.jquery.com/fadeIn/ }\` * @since 1.4.3 */ fadeIn(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -3755,7 +3945,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeIn/} + * @see \`{@link https://api.jquery.com/fadeIn/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3767,7 +3957,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/fadeIn/} + * @see \`{@link https://api.jquery.com/fadeIn/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3778,7 +3968,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeOut/} + * @see \`{@link https://api.jquery.com/fadeOut/ }\` * @since 1.4.3 */ fadeOut(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -3788,7 +3978,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeOut/} + * @see \`{@link https://api.jquery.com/fadeOut/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3800,7 +3990,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/fadeOut/} + * @see \`{@link https://api.jquery.com/fadeOut/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3812,7 +4002,7 @@ interface JQuery extends Iterable * @param opacity A number between 0 and 1 denoting the target opacity. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeTo/} + * @see \`{@link https://api.jquery.com/fadeTo/ }\` * @since 1.4.3 */ fadeTo(duration: JQuery.Duration, opacity: number, easing: string, complete?: (this: TElement) => void): this; @@ -3822,7 +4012,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param opacity A number between 0 and 1 denoting the target opacity. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeTo/} + * @see \`{@link https://api.jquery.com/fadeTo/ }\` * @since 1.0 */ fadeTo(duration: JQuery.Duration, opacity: number, complete?: (this: TElement) => void): this; @@ -3832,7 +4022,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeToggle/} + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` * @since 1.4.4 */ fadeToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -3842,7 +4032,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/fadeToggle/} + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3854,7 +4044,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/fadeToggle/} + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` * @since 1.0 * @since 1.4.3 */ @@ -3866,7 +4056,7 @@ interface JQuery extends Iterable * One or more DOM elements to match the current set of elements against. * An existing jQuery object to match the current set of elements against. * A function used as a test for each element in the set. this is the current DOM element. - * @see {@link https://api.jquery.com/filter/} + * @see \`{@link https://api.jquery.com/filter/ }\` * @since 1.0 * @since 1.4 */ @@ -3877,7 +4067,7 @@ interface JQuery extends Iterable * * @param selector A string containing a selector expression to match elements against. * An element or a jQuery object to match elements against. - * @see {@link https://api.jquery.com/find/} + * @see \`{@link https://api.jquery.com/find/ }\` * @since 1.0 * @since 1.6 */ @@ -3887,14 +4077,14 @@ interface JQuery extends Iterable * the matched elements. * * @param queue The name of the queue in which to stop animations. - * @see {@link https://api.jquery.com/finish/} + * @see \`{@link https://api.jquery.com/finish/ }\` * @since 1.9 */ finish(queue?: string): this; /** * Reduce the set of matched elements to the first in the set. * - * @see {@link https://api.jquery.com/first/} + * @see \`{@link https://api.jquery.com/first/ }\` * @since 1.4 */ first(): this; @@ -3903,9 +4093,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focus/} + * @see \`{@link https://api.jquery.com/focus/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focus(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3913,9 +4104,10 @@ interface JQuery extends Iterable * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focus/} + * @see \`{@link https://api.jquery.com/focus/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focus(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3923,9 +4115,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focusin/} + * @see \`{@link https://api.jquery.com/focusin/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focusin(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3933,9 +4126,10 @@ interface JQuery extends Iterable * Bind an event handler to the "focusin" event. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focusin/} + * @see \`{@link https://api.jquery.com/focusin/ }\` * @since 1.4 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focusin(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -3943,9 +4137,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focusout/} + * @see \`{@link https://api.jquery.com/focusout/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focusout(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -3953,23 +4148,24 @@ interface JQuery extends Iterable * Bind an event handler to the "focusout" JavaScript event. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/focusout/} + * @see \`{@link https://api.jquery.com/focusout/ }\` * @since 1.4 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ focusout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** * Retrieve one of the elements matched by the jQuery object. * * @param index A zero-based integer indicating which element to retrieve. - * @see {@link https://api.jquery.com/get/} + * @see \`{@link https://api.jquery.com/get/ }\` * @since 1.0 */ get(index: number): TElement; /** * Retrieve the elements matched by the jQuery object. * - * @see {@link https://api.jquery.com/get/} + * @see \`{@link https://api.jquery.com/get/ }\` * @since 1.0 */ get(): TElement[]; @@ -3978,7 +4174,7 @@ interface JQuery extends Iterable * * @param selector A string containing a selector expression to match elements against. * A DOM element to match elements against. - * @see {@link https://api.jquery.com/has/} + * @see \`{@link https://api.jquery.com/has/ }\` * @since 1.4 */ has(selector: string | Element): this; @@ -3986,7 +4182,7 @@ interface JQuery extends Iterable * Determine whether any of the matched elements are assigned the given class. * * @param className The class name to search for. - * @see {@link https://api.jquery.com/hasClass/} + * @see \`{@link https://api.jquery.com/hasClass/ }\` * @since 1.2 */ hasClass(className: string): boolean; @@ -3997,7 +4193,7 @@ interface JQuery extends Iterable * appended (as a string). * A function returning the height to set. Receives the index position of the element in the set and * the old height as arguments. Within the function, this refers to the current element in the set. - * @see {@link https://api.jquery.com/height/} + * @see \`{@link https://api.jquery.com/height/ }\` * @since 1.0 * @since 1.4.1 */ @@ -4005,7 +4201,7 @@ interface JQuery extends Iterable /** * Get the current computed height for the first element in the set of matched elements. * - * @see {@link https://api.jquery.com/height/} + * @see \`{@link https://api.jquery.com/height/ }\` * @since 1.0 */ height(): number | undefined; @@ -4015,7 +4211,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/hide/} + * @see \`{@link https://api.jquery.com/hide/ }\` * @since 1.4.3 */ hide(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; @@ -4025,7 +4221,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing_complete A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/hide/} + * @see \`{@link https://api.jquery.com/hide/ }\` * @since 1.0 * @since 1.4.3 */ @@ -4036,7 +4232,7 @@ interface JQuery extends Iterable * @param duration_complete_options A string or number determining how long the animation will run. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/hide/} + * @see \`{@link https://api.jquery.com/hide/ }\` * @since 1.0 */ hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; @@ -4046,11 +4242,12 @@ interface JQuery extends Iterable * * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. - * @see {@link https://api.jquery.com/hover/} + * @see \`{@link https://api.jquery.com/hover/ }\` * @since 1.0 * @since 1.4 */ // HACK: The type parameter T is not used but ensures the 'event' callback parameter is typed correctly. + // tslint:disable-next-line:no-unnecessary-generics hover(handlerInOut: JQuery.EventHandler | JQuery.EventHandlerBase> | false, handlerOut?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4060,7 +4257,7 @@ interface JQuery extends Iterable * A function returning the HTML content to set. Receives the index position of the element in the set * and the old HTML value as arguments. jQuery empties the element before calling the function; use the * oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - * @see {@link https://api.jquery.com/html/} + * @see \`{@link https://api.jquery.com/html/ }\` * @since 1.0 * @since 1.4 */ @@ -4068,7 +4265,7 @@ interface JQuery extends Iterable /** * Get the HTML contents of the first element in the set of matched elements. * - * @see {@link https://api.jquery.com/html/} + * @see \`{@link https://api.jquery.com/html/ }\` * @since 1.0 */ html(): string; @@ -4077,7 +4274,7 @@ interface JQuery extends Iterable * * @param element The DOM element or first element within the jQuery object to look for. * A selector representing a jQuery collection in which to look for an element. - * @see {@link https://api.jquery.com/index/} + * @see \`{@link https://api.jquery.com/index/ }\` * @since 1.0 * @since 1.4 */ @@ -4090,7 +4287,7 @@ interface JQuery extends Iterable * A function returning the inner height (including padding but not border) to set. Receives the index * position of the element in the set and the old inner height as arguments. Within the function, this * refers to the current element in the set. - * @see {@link https://api.jquery.com/innerHeight/} + * @see \`{@link https://api.jquery.com/innerHeight/ }\` * @since 1.8.0 */ innerHeight(value: string | number | ((this: TElement, index: number, height: number) => string | number)): this; @@ -4098,7 +4295,7 @@ interface JQuery extends Iterable * Get the current computed height for the first element in the set of matched elements, including * padding but not border. * - * @see {@link https://api.jquery.com/innerHeight/} + * @see \`{@link https://api.jquery.com/innerHeight/ }\` * @since 1.2.6 */ innerHeight(): number | undefined; @@ -4110,7 +4307,7 @@ interface JQuery extends Iterable * A function returning the inner width (including padding but not border) to set. Receives the index * position of the element in the set and the old inner width as arguments. Within the function, this * refers to the current element in the set. - * @see {@link https://api.jquery.com/innerWidth/} + * @see \`{@link https://api.jquery.com/innerWidth/ }\` * @since 1.8.0 */ innerWidth(value: string | number | ((this: TElement, index: number, width: number) => string | number)): this; @@ -4118,7 +4315,7 @@ interface JQuery extends Iterable * Get the current computed inner width for the first element in the set of matched elements, including * padding but not border. * - * @see {@link https://api.jquery.com/innerWidth/} + * @see \`{@link https://api.jquery.com/innerWidth/ }\` * @since 1.2.6 */ innerWidth(): number | undefined; @@ -4127,7 +4324,7 @@ interface JQuery extends Iterable * * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements * will be inserted after the element(s) specified by this parameter. - * @see {@link https://api.jquery.com/insertAfter/} + * @see \`{@link https://api.jquery.com/insertAfter/ }\` * @since 1.0 */ insertAfter(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; @@ -4136,7 +4333,7 @@ interface JQuery extends Iterable * * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements * will be inserted before the element(s) specified by this parameter. - * @see {@link https://api.jquery.com/insertBefore/} + * @see \`{@link https://api.jquery.com/insertBefore/ }\` * @since 1.0 */ insertBefore(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; @@ -4150,7 +4347,7 @@ interface JQuery extends Iterable * function, this refers to the current DOM element. * An existing jQuery object to match the current set of elements against. * One or more elements to match the current set of elements against. - * @see {@link https://api.jquery.com/is/} + * @see \`{@link https://api.jquery.com/is/ }\` * @since 1.0 * @since 1.6 */ @@ -4160,9 +4357,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keydown/} + * @see \`{@link https://api.jquery.com/keydown/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keydown(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4170,9 +4368,10 @@ interface JQuery extends Iterable * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keydown/} + * @see \`{@link https://api.jquery.com/keydown/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keydown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4180,9 +4379,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keypress/} + * @see \`{@link https://api.jquery.com/keypress/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keypress(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4190,9 +4390,10 @@ interface JQuery extends Iterable * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keypress/} + * @see \`{@link https://api.jquery.com/keypress/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keypress(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4200,9 +4401,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keyup/} + * @see \`{@link https://api.jquery.com/keyup/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keyup(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4210,15 +4412,16 @@ interface JQuery extends Iterable * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/keyup/} + * @see \`{@link https://api.jquery.com/keyup/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ keyup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** * Reduce the set of matched elements to the final one in the set. * - * @see {@link https://api.jquery.com/last/} + * @see \`{@link https://api.jquery.com/last/ }\` * @since 1.4 */ last(): this; @@ -4228,7 +4431,7 @@ interface JQuery extends Iterable * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param complete A callback function that is executed when the request completes. - * @see {@link https://api.jquery.com/load/} + * @see \`{@link https://api.jquery.com/load/ }\` * @since 1.0 */ load(url: string, @@ -4240,7 +4443,7 @@ interface JQuery extends Iterable * @param url A string containing the URL to which the request is sent. * @param complete_data A callback function that is executed when the request completes. * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/load/} + * @see \`{@link https://api.jquery.com/load/ }\` * @since 1.0 */ load(url: string, @@ -4250,18 +4453,19 @@ interface JQuery extends Iterable * containing the return values. * * @param callback A function object that will be invoked for each element in the current set. - * @see {@link https://api.jquery.com/map/} + * @see \`{@link https://api.jquery.com/map/ }\` * @since 1.2 */ - map(callback: (this: TElement, index: number, domElement: TElement) => any | any[] | null | undefined): this; + map(callback: (this: TElement, index: number, domElement: TElement) => JQuery.TypeOrArray | null | undefined): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mousedown/} + * @see \`{@link https://api.jquery.com/mousedown/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mousedown(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4269,9 +4473,10 @@ interface JQuery extends Iterable * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mousedown/} + * @see \`{@link https://api.jquery.com/mousedown/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mousedown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4279,9 +4484,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseenter/} + * @see \`{@link https://api.jquery.com/mouseenter/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseenter(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4289,9 +4495,10 @@ interface JQuery extends Iterable * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseenter/} + * @see \`{@link https://api.jquery.com/mouseenter/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseenter(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4299,9 +4506,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseleave/} + * @see \`{@link https://api.jquery.com/mouseleave/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseleave(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4309,9 +4517,10 @@ interface JQuery extends Iterable * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseleave/} + * @see \`{@link https://api.jquery.com/mouseleave/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseleave(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4319,9 +4528,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mousemove/} + * @see \`{@link https://api.jquery.com/mousemove/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mousemove(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4329,9 +4539,10 @@ interface JQuery extends Iterable * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mousemove/} + * @see \`{@link https://api.jquery.com/mousemove/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mousemove(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4339,9 +4550,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseout/} + * @see \`{@link https://api.jquery.com/mouseout/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseout(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4349,9 +4561,10 @@ interface JQuery extends Iterable * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseout/} + * @see \`{@link https://api.jquery.com/mouseout/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4359,9 +4572,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseover/} + * @see \`{@link https://api.jquery.com/mouseover/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseover(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4369,9 +4583,10 @@ interface JQuery extends Iterable * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseover/} + * @see \`{@link https://api.jquery.com/mouseover/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseover(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4379,9 +4594,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseup/} + * @see \`{@link https://api.jquery.com/mouseup/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseup(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -4389,9 +4605,10 @@ interface JQuery extends Iterable * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/mouseup/} + * @see \`{@link https://api.jquery.com/mouseup/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ mouseup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -4399,7 +4616,7 @@ interface JQuery extends Iterable * is provided, it retrieves the next sibling only if it matches that selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/next/} + * @see \`{@link https://api.jquery.com/next/ }\` * @since 1.0 */ next(selector?: JQuery.Selector): this; @@ -4407,7 +4624,7 @@ interface JQuery extends Iterable * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/nextAll/} + * @see \`{@link https://api.jquery.com/nextAll/ }\` * @since 1.2 */ nextAll(selector?: string): this; @@ -4418,7 +4635,7 @@ interface JQuery extends Iterable * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. * A DOM node or jQuery object indicating where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/nextUntil/} + * @see \`{@link https://api.jquery.com/nextUntil/ }\` * @since 1.4 * @since 1.6 */ @@ -4431,7 +4648,7 @@ interface JQuery extends Iterable * element's index in the jQuery collection, and element, which is the DOM element. Within the * function, this refers to the current DOM element. * An existing jQuery object to match the current set of elements against. - * @see {@link https://api.jquery.com/not/} + * @see \`{@link https://api.jquery.com/not/ }\` * @since 1.0 * @since 1.4 */ @@ -4443,7 +4660,7 @@ interface JQuery extends Iterable * "click", "keydown.myPlugin", or ".myPlugin". * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/off/} + * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; @@ -4454,7 +4671,7 @@ interface JQuery extends Iterable * "click", "keydown.myPlugin", or ".myPlugin". * @param selector_handler A selector which should match the one originally passed to .on() when attaching event handlers. * A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/off/} + * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; @@ -4464,7 +4681,7 @@ interface JQuery extends Iterable * @param events An object where the string keys represent one or more space-separated event types and optional * namespaces, and the values represent handler functions previously attached for the event(s). * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @see {@link https://api.jquery.com/off/} + * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ off(events: JQuery.PlainObject> | false>, selector?: JQuery.Selector): this; @@ -4472,7 +4689,7 @@ interface JQuery extends Iterable * Remove an event handler. * * @param event A jQuery.Event object. - * @see {@link https://api.jquery.com/off/} + * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ off(event?: JQuery.Event): this; @@ -4484,21 +4701,21 @@ interface JQuery extends Iterable * A function to return the coordinates to set. Receives the index of the element in the collection as * the first argument and the current coordinates as the second argument. The function should return an * object with the new top and left properties. - * @see {@link https://api.jquery.com/offset/} + * @see \`{@link https://api.jquery.com/offset/ }\` * @since 1.4 */ offset(coordinates: JQuery.Coordinates | ((this: TElement, index: number, coords: JQuery.Coordinates) => JQuery.Coordinates)): this; /** * Get the current coordinates of the first element in the set of matched elements, relative to the document. * - * @see {@link https://api.jquery.com/offset/} + * @see \`{@link https://api.jquery.com/offset/ }\` * @since 1.2 */ offset(): JQuery.Coordinates | undefined; /** * Get the closest ancestor element that is positioned. * - * @see {@link https://api.jquery.com/offsetParent/} + * @see \`{@link https://api.jquery.com/offsetParent/ }\` * @since 1.2.6 */ offsetParent(): this; @@ -4510,7 +4727,7 @@ interface JQuery extends Iterable * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, @@ -4525,13 +4742,13 @@ interface JQuery extends Iterable * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures + on(events: string, + selector: JQuery.Selector | null, + data: any, + handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures /** * Attach an event handler function for one or more events to the selected elements. * @@ -4540,7 +4757,7 @@ interface JQuery extends Iterable * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, @@ -4553,19 +4770,19 @@ interface JQuery extends Iterable * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, - selector: JQuery.Selector, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures + selector: JQuery.Selector, + handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, @@ -4577,19 +4794,19 @@ interface JQuery extends Iterable * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: string, - data: TData, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures + on(events: string, + data: any, // tslint:disable-line:unified-signatures + handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, @@ -4599,11 +4816,11 @@ interface JQuery extends Iterable * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: string, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures + handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures /** * Attach an event handler function for one or more events to the selected elements. * @@ -4612,7 +4829,7 @@ interface JQuery extends Iterable * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If * the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4625,7 +4842,7 @@ interface JQuery extends Iterable * namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If * the selector is null or omitted, the handler is always called when it reaches the selected element. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4636,7 +4853,7 @@ interface JQuery extends Iterable * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). * @param data Data to be passed to the handler in event.data when an event occurs. - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4646,7 +4863,7 @@ interface JQuery extends Iterable * * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). - * @see {@link https://api.jquery.com/on/} + * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; @@ -4658,7 +4875,7 @@ interface JQuery extends Iterable * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: string, @@ -4673,7 +4890,7 @@ interface JQuery extends Iterable * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: string, @@ -4685,7 +4902,7 @@ interface JQuery extends Iterable * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: string, @@ -4697,7 +4914,7 @@ interface JQuery extends Iterable * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: string, @@ -4710,7 +4927,7 @@ interface JQuery extends Iterable * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If * the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4723,7 +4940,7 @@ interface JQuery extends Iterable * namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If * the selector is null or omitted, the handler is always called when it reaches the selected element. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4734,7 +4951,7 @@ interface JQuery extends Iterable * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). * @param data Data to be passed to the handler in event.data when an event occurs. - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, @@ -4744,7 +4961,7 @@ interface JQuery extends Iterable * * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). - * @see {@link https://api.jquery.com/one/} + * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; @@ -4753,7 +4970,7 @@ interface JQuery extends Iterable * * @param value A number representing the number of pixels, or a number along with an optional unit of measure * appended (as a string). - * @see {@link https://api.jquery.com/outerHeight/} + * @see \`{@link https://api.jquery.com/outerHeight/ }\` * @since 1.8.0 */ outerHeight(value: string | number | ((this: TElement, index: number, height: number) => string | number)): this; @@ -4762,7 +4979,7 @@ interface JQuery extends Iterable * first element in the set of matched elements. * * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - * @see {@link https://api.jquery.com/outerHeight/} + * @see \`{@link https://api.jquery.com/outerHeight/ }\` * @since 1.2.6 */ outerHeight(includeMargin?: boolean): number | undefined; @@ -4773,7 +4990,7 @@ interface JQuery extends Iterable * appended (as a string). * A function returning the outer width to set. Receives the index position of the element in the set * and the old outer width as arguments. Within the function, this refers to the current element in the set. - * @see {@link https://api.jquery.com/outerWidth/} + * @see \`{@link https://api.jquery.com/outerWidth/ }\` * @since 1.8.0 */ outerWidth(value: string | number | ((this: TElement, index: number, width: number) => string | number)): this; @@ -4782,7 +4999,7 @@ interface JQuery extends Iterable * first element in the set of matched elements. * * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - * @see {@link https://api.jquery.com/outerWidth/} + * @see \`{@link https://api.jquery.com/outerWidth/ }\` * @since 1.2.6 */ outerWidth(includeMargin?: boolean): number | undefined; @@ -4790,7 +5007,7 @@ interface JQuery extends Iterable * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/parent/} + * @see \`{@link https://api.jquery.com/parent/ }\` * @since 1.0 */ parent(selector?: JQuery.Selector): this; @@ -4798,7 +5015,7 @@ interface JQuery extends Iterable * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/parents/} + * @see \`{@link https://api.jquery.com/parents/ }\` * @since 1.0 */ parents(selector?: JQuery.Selector): this; @@ -4809,7 +5026,7 @@ interface JQuery extends Iterable * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. * A DOM node or jQuery object indicating where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/parentsUntil/} + * @see \`{@link https://api.jquery.com/parentsUntil/ }\` * @since 1.4 * @since 1.6 */ @@ -4817,7 +5034,7 @@ interface JQuery extends Iterable /** * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. * - * @see {@link https://api.jquery.com/position/} + * @see \`{@link https://api.jquery.com/position/ }\` * @since 1.2 */ position(): JQuery.Coordinates; @@ -4826,7 +5043,7 @@ interface JQuery extends Iterable * * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or * jQuery objects to insert at the beginning of each element in the set of matched elements. - * @see {@link https://api.jquery.com/prepend/} + * @see \`{@link https://api.jquery.com/prepend/ }\` * @since 1.0 */ prepend(...contents: Array>>): this; @@ -4837,7 +5054,7 @@ interface JQuery extends Iterable * the beginning of each element in the set of matched elements. Receives the index position of the * element in the set and the old HTML value of the element as arguments. Within the function, this * refers to the current element in the set. - * @see {@link https://api.jquery.com/prepend/} + * @see \`{@link https://api.jquery.com/prepend/ }\` * @since 1.4 */ prepend(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; @@ -4846,7 +5063,7 @@ interface JQuery extends Iterable * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements * will be inserted at the beginning of the element(s) specified by this parameter. - * @see {@link https://api.jquery.com/prependTo/} + * @see \`{@link https://api.jquery.com/prependTo/ }\` * @since 1.0 */ prependTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; @@ -4855,7 +5072,7 @@ interface JQuery extends Iterable * is provided, it retrieves the previous sibling only if it matches that selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/prev/} + * @see \`{@link https://api.jquery.com/prev/ }\` * @since 1.0 */ prev(selector?: JQuery.Selector): this; @@ -4863,7 +5080,7 @@ interface JQuery extends Iterable * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/prevAll/} + * @see \`{@link https://api.jquery.com/prevAll/ }\` * @since 1.2 */ prevAll(selector?: JQuery.Selector): this; @@ -4874,7 +5091,7 @@ interface JQuery extends Iterable * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. * A DOM node or jQuery object indicating where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/prevUntil/} + * @see \`{@link https://api.jquery.com/prevUntil/ }\` * @since 1.4 * @since 1.6 */ @@ -4885,7 +5102,7 @@ interface JQuery extends Iterable * * @param type The type of queue that needs to be observed. * @param target Object onto which the promise methods have to be attached - * @see {@link https://api.jquery.com/promise/} + * @see \`{@link https://api.jquery.com/promise/ }\` * @since 1.6 */ promise(type: string, target: T): T & JQuery.Promise; @@ -4894,7 +5111,7 @@ interface JQuery extends Iterable * queued or not, have finished. * * @param target Object onto which the promise methods have to be attached - * @see {@link https://api.jquery.com/promise/} + * @see \`{@link https://api.jquery.com/promise/ }\` * @since 1.6 */ promise(target: T): T & JQuery.Promise; @@ -4903,7 +5120,7 @@ interface JQuery extends Iterable * queued or not, have finished. * * @param type The type of queue that needs to be observed. - * @see {@link https://api.jquery.com/promise/} + * @see \`{@link https://api.jquery.com/promise/ }\` * @since 1.6 */ promise(type?: string): JQuery.Promise; @@ -4913,7 +5130,7 @@ interface JQuery extends Iterable * @param propertyName The name of the property to set. * @param value A function returning the value to set. Receives the index position of the element in the set and the * old property value as arguments. Within the function, the keyword this refers to the current element. - * @see {@link https://api.jquery.com/prop/} + * @see \`{@link https://api.jquery.com/prop/ }\` * @since 1.6 */ prop(propertyName: string, value: (this: TElement, index: number, oldPropertyValue: any) => any): this; @@ -4922,7 +5139,7 @@ interface JQuery extends Iterable * * @param propertyName The name of the property to set. * @param value A value to set for the property. - * @see {@link https://api.jquery.com/prop/} + * @see \`{@link https://api.jquery.com/prop/ }\` * @since 1.6 */ prop(propertyName: string, value: any): this; // tslint:disable-line:unified-signatures @@ -4930,7 +5147,7 @@ interface JQuery extends Iterable * Set one or more properties for the set of matched elements. * * @param properties An object of property-value pairs to set. - * @see {@link https://api.jquery.com/prop/} + * @see \`{@link https://api.jquery.com/prop/ }\` * @since 1.6 */ prop(properties: JQuery.PlainObject): this; @@ -4938,7 +5155,7 @@ interface JQuery extends Iterable * Get the value of a property for the first element in the set of matched elements. * * @param propertyName The name of the property to get. - * @see {@link https://api.jquery.com/prop/} + * @see \`{@link https://api.jquery.com/prop/ }\` * @since 1.6 */ prop(propertyName: string): any | undefined; @@ -4948,7 +5165,7 @@ interface JQuery extends Iterable * @param elements An array of elements to push onto the stack and make into a new jQuery object. * @param name The name of a jQuery method that generated the array of elements. * @param args The arguments that were passed in to the jQuery method (for serialization). - * @see {@link https://api.jquery.com/pushStack/} + * @see \`{@link https://api.jquery.com/pushStack/ }\` * @since 1.3 */ pushStack(elements: ArrayLike, name: string, args: any[]): this; @@ -4956,7 +5173,7 @@ interface JQuery extends Iterable * Add a collection of DOM elements onto the jQuery stack. * * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @see {@link https://api.jquery.com/pushStack/} + * @see \`{@link https://api.jquery.com/pushStack/ }\` * @since 1.0 */ pushStack(elements: ArrayLike): this; @@ -4966,7 +5183,7 @@ interface JQuery extends Iterable * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. * An array of functions to replace the current queue contents. - * @see {@link https://api.jquery.com/queue/} + * @see \`{@link https://api.jquery.com/queue/ }\` * @since 1.2 */ queue(queueName: string, newQueue: JQuery.TypeOrArray>): this; @@ -4975,7 +5192,7 @@ interface JQuery extends Iterable * * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. * An array of functions to replace the current queue contents. - * @see {@link https://api.jquery.com/queue/} + * @see \`{@link https://api.jquery.com/queue/ }\` * @since 1.2 */ queue(newQueue: JQuery.TypeOrArray>): this; @@ -4983,7 +5200,7 @@ interface JQuery extends Iterable * Show the queue of functions to be executed on the matched elements. * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/queue/} + * @see \`{@link https://api.jquery.com/queue/ }\` * @since 1.2 */ queue(queueName?: string): JQuery.Queue; @@ -4991,16 +5208,17 @@ interface JQuery extends Iterable * Specify a function to execute when the DOM is fully loaded. * * @param handler A function to execute after the DOM is ready. - * @see {@link https://api.jquery.com/ready/} + * @see \`{@link https://api.jquery.com/ready/ }\` * @since 1.0 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use `jQuery(function() { })`. */ - ready(handler: ($: JQueryStatic) => void): this; + ready(handler: ($: JQueryStatic) => void): this; /** * Remove the set of matched elements from the DOM. * * @param selector A selector expression that filters the set of matched elements to be removed. - * @see {@link https://api.jquery.com/remove/} + * @see \`{@link https://api.jquery.com/remove/ }\` * @since 1.0 */ remove(selector?: string): this; @@ -5008,7 +5226,7 @@ interface JQuery extends Iterable * Remove an attribute from each element in the set of matched elements. * * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - * @see {@link https://api.jquery.com/removeAttr/} + * @see \`{@link https://api.jquery.com/removeAttr/ }\` * @since 1.0 */ removeAttr(attributeName: string): this; @@ -5019,7 +5237,7 @@ interface JQuery extends Iterable * An array of classes to be removed from the class attribute of each matched element. * A function returning one or more space-separated class names to be removed. Receives the index * position of the element in the set and the old class value as arguments. - * @see {@link https://api.jquery.com/removeClass/} + * @see \`{@link https://api.jquery.com/removeClass/ }\` * @since 1.0 * @since 1.4 * @since 3.3 @@ -5030,7 +5248,7 @@ interface JQuery extends Iterable * * @param name A string naming the piece of data to delete. * An array or space-separated string naming the pieces of data to delete. - * @see {@link https://api.jquery.com/removeData/} + * @see \`{@link https://api.jquery.com/removeData/ }\` * @since 1.2.3 * @since 1.7 */ @@ -5039,7 +5257,7 @@ interface JQuery extends Iterable * Remove a property for the set of matched elements. * * @param propertyName The name of the property to remove. - * @see {@link https://api.jquery.com/removeProp/} + * @see \`{@link https://api.jquery.com/removeProp/ }\` * @since 1.6 */ removeProp(propertyName: string): this; @@ -5047,7 +5265,7 @@ interface JQuery extends Iterable * Replace each target element with the set of matched elements. * * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - * @see {@link https://api.jquery.com/replaceAll/} + * @see \`{@link https://api.jquery.com/replaceAll/ }\` * @since 1.2 */ replaceAll(target: JQuery.Selector | JQuery | JQuery.TypeOrArray): this; @@ -5057,7 +5275,7 @@ interface JQuery extends Iterable * * @param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. * A function that returns content with which to replace the set of matched elements. - * @see {@link https://api.jquery.com/replaceWith/} + * @see \`{@link https://api.jquery.com/replaceWith/ }\` * @since 1.2 * @since 1.4 */ @@ -5067,9 +5285,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/resize/} + * @see \`{@link https://api.jquery.com/resize/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ resize(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -5077,9 +5296,10 @@ interface JQuery extends Iterable * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/resize/} + * @see \`{@link https://api.jquery.com/resize/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ resize(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -5087,9 +5307,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/scroll/} + * @see \`{@link https://api.jquery.com/scroll/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ scroll(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -5097,23 +5318,24 @@ interface JQuery extends Iterable * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/scroll/} + * @see \`{@link https://api.jquery.com/scroll/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ scroll(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** * Set the current horizontal position of the scroll bar for each of the set of matched elements. * * @param value An integer indicating the new position to set the scroll bar to. - * @see {@link https://api.jquery.com/scrollLeft/} + * @see \`{@link https://api.jquery.com/scrollLeft/ }\` * @since 1.2.6 */ scrollLeft(value: number): this; /** * Get the current horizontal position of the scroll bar for the first element in the set of matched elements. * - * @see {@link https://api.jquery.com/scrollLeft/} + * @see \`{@link https://api.jquery.com/scrollLeft/ }\` * @since 1.2.6 */ scrollLeft(): number | undefined; @@ -5121,7 +5343,7 @@ interface JQuery extends Iterable * Set the current vertical position of the scroll bar for each of the set of matched elements. * * @param value A number indicating the new position to set the scroll bar to. - * @see {@link https://api.jquery.com/scrollTop/} + * @see \`{@link https://api.jquery.com/scrollTop/ }\` * @since 1.2.6 */ scrollTop(value: number): this; @@ -5129,7 +5351,7 @@ interface JQuery extends Iterable * Get the current vertical position of the scroll bar for the first element in the set of matched * elements or set the vertical position of the scroll bar for every matched element. * - * @see {@link https://api.jquery.com/scrollTop/} + * @see \`{@link https://api.jquery.com/scrollTop/ }\` * @since 1.2.6 */ scrollTop(): number | undefined; @@ -5138,9 +5360,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/select/} + * @see \`{@link https://api.jquery.com/select/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ select(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -5148,22 +5371,23 @@ interface JQuery extends Iterable * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/select/} + * @see \`{@link https://api.jquery.com/select/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ select(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** * Encode a set of form elements as a string for submission. * - * @see {@link https://api.jquery.com/serialize/} + * @see \`{@link https://api.jquery.com/serialize/ }\` * @since 1.0 */ serialize(): string; /** * Encode a set of form elements as an array of names and values. * - * @see {@link https://api.jquery.com/serializeArray/} + * @see \`{@link https://api.jquery.com/serializeArray/ }\` * @since 1.2 */ serializeArray(): JQuery.NameValuePair[]; @@ -5173,7 +5397,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/show/} + * @see \`{@link https://api.jquery.com/show/ }\` * @since 1.4.3 */ show(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; @@ -5183,7 +5407,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing_complete A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/show/} + * @see \`{@link https://api.jquery.com/show/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5194,7 +5418,7 @@ interface JQuery extends Iterable * @param duration_complete_options A string or number determining how long the animation will run. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/show/} + * @see \`{@link https://api.jquery.com/show/ }\` * @since 1.0 */ show(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; @@ -5202,7 +5426,7 @@ interface JQuery extends Iterable * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @see {@link https://api.jquery.com/siblings/} + * @see \`{@link https://api.jquery.com/siblings/ }\` * @since 1.0 */ siblings(selector?: JQuery.Selector): this; @@ -5213,7 +5437,7 @@ interface JQuery extends Iterable * it indicates an offset from the end of the set. * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, * it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - * @see {@link https://api.jquery.com/slice/} + * @see \`{@link https://api.jquery.com/slice/ }\` * @since 1.1.4 */ slice(start: number, end?: number): this; @@ -5223,7 +5447,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideDown/} + * @see \`{@link https://api.jquery.com/slideDown/ }\` * @since 1.4.3 */ slideDown(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -5233,7 +5457,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideDown/} + * @see \`{@link https://api.jquery.com/slideDown/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5245,7 +5469,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/slideDown/} + * @see \`{@link https://api.jquery.com/slideDown/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5256,7 +5480,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideToggle/} + * @see \`{@link https://api.jquery.com/slideToggle/ }\` * @since 1.4.3 */ slideToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -5266,7 +5490,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideToggle/} + * @see \`{@link https://api.jquery.com/slideToggle/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5278,7 +5502,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/slideToggle/} + * @see \`{@link https://api.jquery.com/slideToggle/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5289,7 +5513,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideUp/} + * @see \`{@link https://api.jquery.com/slideUp/ }\` * @since 1.4.3 */ slideUp(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -5299,7 +5523,7 @@ interface JQuery extends Iterable * @param duration_easing A string or number determining how long the animation will run. * A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/slideUp/} + * @see \`{@link https://api.jquery.com/slideUp/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5311,7 +5535,7 @@ interface JQuery extends Iterable * A string indicating which easing function to use for the transition. * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. - * @see {@link https://api.jquery.com/slideUp/} + * @see \`{@link https://api.jquery.com/slideUp/ }\` * @since 1.0 * @since 1.4.3 */ @@ -5322,7 +5546,7 @@ interface JQuery extends Iterable * @param queue The name of the queue in which to stop animations. * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - * @see {@link https://api.jquery.com/stop/} + * @see \`{@link https://api.jquery.com/stop/ }\` * @since 1.7 */ stop(queue: string, clearQueue?: boolean, jumpToEnd?: boolean): this; @@ -5331,7 +5555,7 @@ interface JQuery extends Iterable * * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - * @see {@link https://api.jquery.com/stop/} + * @see \`{@link https://api.jquery.com/stop/ }\` * @since 1.2 */ stop(clearQueue?: boolean, jumpToEnd?: boolean): this; @@ -5340,9 +5564,10 @@ interface JQuery extends Iterable * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/submit/} + * @see \`{@link https://api.jquery.com/submit/ }\` * @since 1.4.3 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ submit(eventData: TData, handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; @@ -5350,9 +5575,10 @@ interface JQuery extends Iterable * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/submit/} + * @see \`{@link https://api.jquery.com/submit/ }\` * @since 1.0 - * @deprecated 3.3 + * + * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. */ submit(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; /** @@ -5362,7 +5588,7 @@ interface JQuery extends Iterable * be converted to a String representation. * A function returning the text content to set. Receives the index position of the element in the set * and the old text value as arguments. - * @see {@link https://api.jquery.com/text/} + * @see \`{@link https://api.jquery.com/text/ }\` * @since 1.0 * @since 1.4 */ @@ -5370,14 +5596,14 @@ interface JQuery extends Iterable /** * Get the combined text contents of each element in the set of matched elements, including their descendants. * - * @see {@link https://api.jquery.com/text/} + * @see \`{@link https://api.jquery.com/text/ }\` * @since 1.0 */ text(): string; /** * Retrieve all the elements contained in the jQuery set, as an array. * - * @see {@link https://api.jquery.com/toArray/} + * @see \`{@link https://api.jquery.com/toArray/ }\` * @since 1.4 */ toArray(): TElement[]; @@ -5387,7 +5613,7 @@ interface JQuery extends Iterable * @param duration A string or number determining how long the animation will run. * @param easing A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/toggle/} + * @see \`{@link https://api.jquery.com/toggle/ }\` * @since 1.4.3 */ toggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; @@ -5396,7 +5622,7 @@ interface JQuery extends Iterable * * @param duration A string or number determining how long the animation will run. * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/toggle/} + * @see \`{@link https://api.jquery.com/toggle/ }\` * @since 1.0 */ toggle(duration: JQuery.Duration, complete: (this: TElement) => void): this; @@ -5407,7 +5633,7 @@ interface JQuery extends Iterable * A function to call once the animation is complete, called once per matched element. * A map of additional options to pass to the method. * Use true to show the element or false to hide it. - * @see {@link https://api.jquery.com/toggle/} + * @see \`{@link https://api.jquery.com/toggle/ }\` * @since 1.0 * @since 1.3 */ @@ -5421,7 +5647,7 @@ interface JQuery extends Iterable * A function that returns class names to be toggled in the class attribute of each element in the * matched set. Receives the index position of the element in the set, the old class value, and the state as arguments. * @param state A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - * @see {@link https://api.jquery.com/toggleClass/} + * @see \`{@link https://api.jquery.com/toggleClass/ }\` * @since 1.0 * @since 1.3 * @since 1.4 @@ -5434,9 +5660,10 @@ interface JQuery extends Iterable * either the class's presence or the value of the state argument. * * @param state A boolean value to determine whether the class should be added or removed. - * @see {@link https://api.jquery.com/toggleClass/} + * @see \`{@link https://api.jquery.com/toggleClass/ }\` * @since 1.4 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. See \`{@link https://github.com/jquery/jquery/pull/2618 }\`. */ toggleClass(state?: boolean): this; /** @@ -5445,7 +5672,7 @@ interface JQuery extends Iterable * @param eventType A string containing a JavaScript event type, such as click or submit. * A jQuery.Event object. * @param extraParameters Additional parameters to pass along to the event handler. - * @see {@link https://api.jquery.com/trigger/} + * @see \`{@link https://api.jquery.com/trigger/ }\` * @since 1.0 * @since 1.3 */ @@ -5456,7 +5683,7 @@ interface JQuery extends Iterable * @param eventType A string containing a JavaScript event type, such as click or submit. * A jQuery.Event object. * @param extraParameters Additional parameters to pass along to the event handler. - * @see {@link https://api.jquery.com/triggerHandler/} + * @see \`{@link https://api.jquery.com/triggerHandler/ }\` * @since 1.2 * @since 1.3 */ @@ -5466,10 +5693,11 @@ interface JQuery extends Iterable * * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/unbind/} + * @see \`{@link https://api.jquery.com/unbind/ }\` * @since 1.0 * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. */ unbind(event: string, handler: JQuery.EventHandlerBase> | false): this; /** @@ -5477,9 +5705,10 @@ interface JQuery extends Iterable * * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * A jQuery.Event object. - * @see {@link https://api.jquery.com/unbind/} + * @see \`{@link https://api.jquery.com/unbind/ }\` * @since 1.0 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. */ unbind(event?: string | JQuery.Event): this; /** @@ -5489,9 +5718,10 @@ interface JQuery extends Iterable * @param selector A selector which will be used to filter the event results. * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" * @param handler A function to execute each time the event is triggered. - * @see {@link https://api.jquery.com/undelegate/} + * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. */ undelegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandlerBase> | false): this; /** @@ -5501,10 +5731,11 @@ interface JQuery extends Iterable * @param selector A selector which will be used to filter the event results. * @param eventTypes A string containing a JavaScript event type, such as "click" or "keydown" * An object of one or more event types and previously bound functions to unbind from them. - * @see {@link https://api.jquery.com/undelegate/} + * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 * @since 1.4.3 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. */ undelegate(selector: JQuery.Selector, eventTypes: string | JQuery.PlainObject> | false>): this; /** @@ -5512,10 +5743,11 @@ interface JQuery extends Iterable * specific set of root elements. * * @param namespace A selector which will be used to filter the event results. - * @see {@link https://api.jquery.com/undelegate/} + * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 * @since 1.6 - * @deprecated 3.0 + * + * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. */ undelegate(namespace?: string): this; /** @@ -5523,7 +5755,7 @@ interface JQuery extends Iterable * * @param selector A selector to check the parent element against. If an element's parent does not match the selector, * the element won't be unwrapped. - * @see {@link https://api.jquery.com/unwrap/} + * @see \`{@link https://api.jquery.com/unwrap/ }\` * @since 1.4 * @since 3.0 */ @@ -5535,7 +5767,7 @@ interface JQuery extends Iterable * element to set as selected/checked. * A function returning the value to set. this is the current element. Receives the index position of * the element in the set and the old value as arguments. - * @see {@link https://api.jquery.com/val/} + * @see \`{@link https://api.jquery.com/val/ }\` * @since 1.0 * @since 1.4 */ @@ -5543,7 +5775,7 @@ interface JQuery extends Iterable /** * Get the current value of the first element in the set of matched elements. * - * @see {@link https://api.jquery.com/val/} + * @see \`{@link https://api.jquery.com/val/ }\` * @since 1.0 */ val(): string | number | string[] | undefined; @@ -5554,7 +5786,7 @@ interface JQuery extends Iterable * appended (as a string). * A function returning the width to set. Receives the index position of the element in the set and the * old width as arguments. Within the function, this refers to the current element in the set. - * @see {@link https://api.jquery.com/width/} + * @see \`{@link https://api.jquery.com/width/ }\` * @since 1.0 * @since 1.4.1 */ @@ -5562,7 +5794,7 @@ interface JQuery extends Iterable /** * Get the current computed width for the first element in the set of matched elements. * - * @see {@link https://api.jquery.com/width/} + * @see \`{@link https://api.jquery.com/width/ }\` * @since 1.0 */ width(): number | undefined; @@ -5575,7 +5807,7 @@ interface JQuery extends Iterable * A callback function returning the HTML content or jQuery object to wrap around the matched elements. * Receives the index position of the element in the set as an argument. Within the function, this * refers to the current element in the set. - * @see {@link https://api.jquery.com/wrap/} + * @see \`{@link https://api.jquery.com/wrap/ }\` * @since 1.0 * @since 1.4 */ @@ -5588,7 +5820,7 @@ interface JQuery extends Iterable * elements. Within the function, this refers to the first element in the set. Prior to jQuery 3.0, the * callback was incorrectly called for every element in the set and received the index position of the * element in the set as an argument. - * @see {@link https://api.jquery.com/wrapAll/} + * @see \`{@link https://api.jquery.com/wrapAll/ }\` * @since 1.2 * @since 1.4 */ @@ -5601,7 +5833,7 @@ interface JQuery extends Iterable * A callback function which generates a structure to wrap around the content of the matched elements. * Receives the index position of the element in the set as an argument. Within the function, this * refers to the current element in the set. - * @see {@link https://api.jquery.com/wrapInner/} + * @see \`{@link https://api.jquery.com/wrapInner/ }\` * @since 1.2 * @since 1.4 */ @@ -5611,6 +5843,7 @@ interface JQuery extends Iterable } // ES5 compatibility +// tslint:disable-next-line:no-empty-interface interface Iterable { } declare namespace JQuery { @@ -5679,7 +5912,7 @@ declare namespace JQuery { type TextStatus = SuccessTextStatus | ErrorTextStatus; interface SuccessCallback { - (this: TContext, data: any, textStatus: SuccessTextStatus, jqXHR: JQuery.jqXHR): void; + (this: TContext, data: any, textStatus: SuccessTextStatus, jqXHR: jqXHR): void; } interface ErrorCallback { @@ -5691,7 +5924,7 @@ declare namespace JQuery { } /** - * @see {@link http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings} + * @see \`{@link http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings }\` */ interface AjaxSettingsBase { /** @@ -5730,7 +5963,7 @@ declare namespace JQuery { * "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of * functions. Each function will be called in turn. This is an Ajax Event. */ - complete?: TypeOrArray>; + complete?: TypeOrArray>; /** * An object of string/regular-expression pairs that determine how jQuery will parse the response, * given its content type. @@ -5819,7 +6052,7 @@ declare namespace JQuery { * 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: * This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. */ - error?: TypeOrArray>; + error?: TypeOrArray>; /** * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to * prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to @@ -5905,7 +6138,7 @@ declare namespace JQuery { * XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each * function will be called in turn. This is an Ajax Event. */ - success?: TypeOrArray>; + success?: TypeOrArray>; /** * Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This * will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the @@ -6363,7 +6596,9 @@ declare namespace JQuery { }; // Writable properties on XMLHttpRequest - interface XHRFields extends Partial> { } + interface XHRFields extends Partial> { + msCaching?: string; + } } interface Transport { @@ -6378,7 +6613,7 @@ declare namespace JQuery { } /** - * @see {@link http://api.jquery.com/jquery.ajax/#jqXHR} + * @see \`{@link http://api.jquery.com/jquery.ajax/#jqXHR }\` */ interface jqXHR extends Promise3, never, Ajax.SuccessTextStatus, Ajax.ErrorTextStatus, never, @@ -6391,7 +6626,7 @@ declare namespace JQuery { /** * Determine the current state of a Deferred object. * - * @see {@link https://api.jquery.com/deferred.state/} + * @see \`{@link https://api.jquery.com/deferred.state/ }\` * @since 1.7 */ state(): 'pending' | 'resolved' | 'rejected'; @@ -6399,19 +6634,10 @@ declare namespace JQuery { } namespace jqXHR { - /** - * @deprecated - */ interface DoneCallback> extends Deferred.Callback3 { } - /** - * @deprecated - */ interface FailCallback extends Deferred.Callback3 { } - /** - * @deprecated - */ interface AlwaysCallback> extends Deferred.Callback3 { } } @@ -6419,34 +6645,35 @@ declare namespace JQuery { // region Callbacks + // tslint:disable-next-line:ban-types interface Callbacks { /** * Add a callback or a collection of callbacks to a callback list. * * @param callback A function, or array of functions, that are to be added to the callback list. * @param callbacks A function, or array of functions, that are to be added to the callback list. - * @see {@link https://api.jquery.com/callbacks.add/} + * @see \`{@link https://api.jquery.com/callbacks.add/ }\` * @since 1.7 */ add(callback: TypeOrArray, ...callbacks: Array>): this; /** * Disable a callback list from doing anything more. * - * @see {@link https://api.jquery.com/callbacks.disable/} + * @see \`{@link https://api.jquery.com/callbacks.disable/ }\` * @since 1.7 */ disable(): this; /** * Determine if the callbacks list has been disabled. * - * @see {@link https://api.jquery.com/callbacks.disabled/} + * @see \`{@link https://api.jquery.com/callbacks.disabled/ }\` * @since 1.7 */ disabled(): boolean; /** * Remove all of the callbacks from a list. * - * @see {@link https://api.jquery.com/callbacks.empty/} + * @see \`{@link https://api.jquery.com/callbacks.empty/ }\` * @since 1.7 */ empty(): this; @@ -6454,7 +6681,7 @@ declare namespace JQuery { * Call all of the callbacks with the given arguments. * * @param args The argument or list of arguments to pass back to the callback list. - * @see {@link https://api.jquery.com/callbacks.fire/} + * @see \`{@link https://api.jquery.com/callbacks.fire/ }\` * @since 1.7 */ fire(...args: any[]): this; @@ -6463,14 +6690,14 @@ declare namespace JQuery { * * @param context A reference to the context in which the callbacks in the list should be fired. * @param args An argument, or array of arguments, to pass to the callbacks in the list. - * @see {@link https://api.jquery.com/callbacks.fireWith/} + * @see \`{@link https://api.jquery.com/callbacks.fireWith/ }\` * @since 1.7 */ fireWith(context: object, args?: ArrayLike): this; /** * Determine if the callbacks have already been called at least once. * - * @see {@link https://api.jquery.com/callbacks.fired/} + * @see \`{@link https://api.jquery.com/callbacks.fired/ }\` * @since 1.7 */ fired(): boolean; @@ -6479,21 +6706,21 @@ declare namespace JQuery { * argument, determine whether it is in a list. * * @param callback The callback to search for. - * @see {@link https://api.jquery.com/callbacks.has/} + * @see \`{@link https://api.jquery.com/callbacks.has/ }\` * @since 1.7 */ has(callback?: T): boolean; /** * Lock a callback list in its current state. * - * @see {@link https://api.jquery.com/callbacks.lock/} + * @see \`{@link https://api.jquery.com/callbacks.lock/ }\` * @since 1.7 */ lock(): this; /** * Determine if the callbacks list has been locked. * - * @see {@link https://api.jquery.com/callbacks.locked/} + * @see \`{@link https://api.jquery.com/callbacks.locked/ }\` * @since 1.7 */ locked(): boolean; @@ -6501,7 +6728,7 @@ declare namespace JQuery { * Remove a callback or a collection of callbacks from a callback list. * * @param callbacks A function, or array of functions, that are to be removed from the callback list. - * @see {@link https://api.jquery.com/callbacks.remove/} + * @see \`{@link https://api.jquery.com/callbacks.remove/ }\` * @since 1.7 */ remove(...callbacks: T[]): this; @@ -6525,6 +6752,28 @@ declare namespace JQuery { */ interface Thenable extends PromiseLike { } + // NOTE: This is a private copy of the global Promise interface. It is used by JQuery.PromiseBase to indicate compatibility with other Promise implementations. + // The global Promise interface cannot be used directly as it may be modified, as in the case of @types/bluebird-global. + /** + * Represents the completion of an asynchronous operation + */ + interface _Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): _Promise; + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): _Promise; + } + // Type parameter guide // -------------------- // Each type parameter represents a parameter in one of the three possible callbacks. @@ -6544,8 +6793,7 @@ declare namespace JQuery { * This object provides a subset of the methods of the Deferred object (then, done, fail, always, * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. * - * @see {@link http://api.jquery.com/Types/#Promise} - * @deprecated Experimental. Avoid referncing this type directly in your code. + * @see \`{@link http://api.jquery.com/Types/#Promise }\` */ interface PromiseBase>, @@ -6566,7 +6814,7 @@ declare namespace JQuery { * * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - * @see {@link https://api.jquery.com/deferred.done/} + * @see \`{@link https://api.jquery.com/deferred.done/ }\` * @since 1.5 */ done(doneCallback: TypeOrArray>, @@ -6576,7 +6824,7 @@ declare namespace JQuery { * * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.fail/} + * @see \`{@link https://api.jquery.com/deferred.fail/ }\` * @since 1.5 */ fail(failCallback: TypeOrArray>, @@ -6587,7 +6835,7 @@ declare namespace JQuery { * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates * progress notifications. - * @see {@link https://api.jquery.com/deferred.progress/} + * @see \`{@link https://api.jquery.com/deferred.progress/ }\` * @since 1.7 */ progress(progressCallback: TypeOrArray>, @@ -6596,21 +6844,21 @@ declare namespace JQuery { * Return a Deferred's Promise object. * * @param target Object onto which the promise methods have to be attached - * @see {@link https://api.jquery.com/deferred.promise/} + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` * @since 1.5 */ promise(target: TTarget): this & TTarget; /** * Return a Deferred's Promise object. * - * @see {@link https://api.jquery.com/deferred.promise/} + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` * @since 1.5 */ promise(): this; /** * Determine the current state of a Deferred object. * - * @see {@link https://api.jquery.com/deferred.state/} + * @see \`{@link https://api.jquery.com/deferred.state/ }\` * @since 1.7 */ state(): 'pending' | 'resolved' | 'rejected'; @@ -6623,10 +6871,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6661,10 +6910,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6692,10 +6942,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6723,21 +6974,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: null, - failFilter: null, - progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: null, + progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6747,10 +6999,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; @@ -6778,21 +7031,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; @@ -6802,21 +7056,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. */ pipe - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; @@ -6831,7 +7086,7 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6867,7 +7122,7 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6896,7 +7151,7 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6925,19 +7180,19 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: null, - progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: null, + progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -6947,7 +7202,7 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; @@ -6976,19 +7231,19 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; @@ -6998,19 +7253,19 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; @@ -7021,17 +7276,17 @@ declare namespace JQuery { * Add handlers to be called when the Deferred object is rejected. * * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} + * @see \`{@link https://api.jquery.com/deferred.catch/ }\` * @since 3.0 */ catch - (failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase( + failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; @@ -7041,7 +7296,7 @@ declare namespace JQuery { * This object provides a subset of the methods of the Deferred object (then, done, fail, always, * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. * - * @see {@link http://api.jquery.com/Types/#Promise} + * @see \`{@link http://api.jquery.com/Types/#Promise }\` */ interface Promise3 extends PromiseBase extends PromiseBase(beforeStart?: (this: JQuery.Deferred, deferred: JQuery.Deferred) => void): JQuery.Deferred; + (beforeStart?: (this: Deferred, deferred: Deferred) => void): Deferred; } interface Deferred { @@ -7084,7 +7339,7 @@ declare namespace JQuery { * Call the progressCallbacks on a Deferred object with the given args. * * @param args Optional arguments that are passed to the progressCallbacks. - * @see {@link https://api.jquery.com/deferred.notify/} + * @see \`{@link https://api.jquery.com/deferred.notify/ }\` * @since 1.7 */ notify(...args: TN[]): this; @@ -7093,7 +7348,7 @@ declare namespace JQuery { * * @param context Context passed to the progressCallbacks as the this object. * @param args An optional array of arguments that are passed to the progressCallbacks. - * @see {@link https://api.jquery.com/deferred.notifyWith/} + * @see \`{@link https://api.jquery.com/deferred.notifyWith/ }\` * @since 1.7 */ notifyWith(context: object, args?: ArrayLike): this; @@ -7101,7 +7356,7 @@ declare namespace JQuery { * Reject a Deferred object and call any failCallbacks with the given args. * * @param args Optional arguments that are passed to the failCallbacks. - * @see {@link https://api.jquery.com/deferred.reject/} + * @see \`{@link https://api.jquery.com/deferred.reject/ }\` * @since 1.5 */ reject(...args: TJ[]): this; @@ -7110,7 +7365,7 @@ declare namespace JQuery { * * @param context Context passed to the failCallbacks as the this object. * @param args An optional array of arguments that are passed to the failCallbacks. - * @see {@link https://api.jquery.com/deferred.rejectWith/} + * @see \`{@link https://api.jquery.com/deferred.rejectWith/ }\` * @since 1.5 */ rejectWith(context: object, args?: ArrayLike): this; @@ -7118,7 +7373,7 @@ declare namespace JQuery { * Resolve a Deferred object and call any doneCallbacks with the given args. * * @param args Optional arguments that are passed to the doneCallbacks. - * @see {@link https://api.jquery.com/deferred.resolve/} + * @see \`{@link https://api.jquery.com/deferred.resolve/ }\` * @since 1.5 */ resolve(...args: TR[]): this; @@ -7127,7 +7382,7 @@ declare namespace JQuery { * * @param context Context passed to the doneCallbacks as the this object. * @param args An optional array of arguments that are passed to the doneCallbacks. - * @see {@link https://api.jquery.com/deferred.resolveWith/} + * @see \`{@link https://api.jquery.com/deferred.resolveWith/ }\` * @since 1.5 */ resolveWith(context: object, args?: ArrayLike): this; @@ -7137,7 +7392,7 @@ declare namespace JQuery { * * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - * @see {@link https://api.jquery.com/deferred.always/} + * @see \`{@link https://api.jquery.com/deferred.always/ }\` * @since 1.6 */ always(alwaysCallback: TypeOrArray>, @@ -7147,7 +7402,7 @@ declare namespace JQuery { * * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - * @see {@link https://api.jquery.com/deferred.done/} + * @see \`{@link https://api.jquery.com/deferred.done/ }\` * @since 1.5 */ done(doneCallback: TypeOrArray>, @@ -7157,7 +7412,7 @@ declare namespace JQuery { * * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.fail/} + * @see \`{@link https://api.jquery.com/deferred.fail/ }\` * @since 1.5 */ fail(failCallback: TypeOrArray>, @@ -7168,7 +7423,7 @@ declare namespace JQuery { * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates * progress notifications. - * @see {@link https://api.jquery.com/deferred.progress/} + * @see \`{@link https://api.jquery.com/deferred.progress/ }\` * @since 1.7 */ progress(progressCallback: TypeOrArray>, @@ -7177,21 +7432,21 @@ declare namespace JQuery { * Return a Deferred's Promise object. * * @param target Object onto which the promise methods have to be attached - * @see {@link https://api.jquery.com/deferred.promise/} + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` * @since 1.5 */ - promise(target: TTarget): JQuery.Promise & TTarget; + promise(target: TTarget): Promise & TTarget; /** * Return a Deferred's Promise object. * - * @see {@link https://api.jquery.com/deferred.promise/} + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` * @since 1.5 */ - promise(): JQuery.Promise; + promise(): Promise; /** * Determine the current state of a Deferred object. * - * @see {@link https://api.jquery.com/deferred.state/} + * @see \`{@link https://api.jquery.com/deferred.state/ }\` * @since 1.7 */ state(): 'pending' | 'resolved' | 'rejected'; @@ -7204,10 +7459,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7242,10 +7498,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7273,10 +7530,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7304,21 +7562,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: null, - failFilter: null, - progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: null, + progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7328,10 +7587,11 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; @@ -7359,21 +7619,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; @@ -7383,21 +7644,22 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` * @since 1.6 * @since 1.7 - * @deprecated 1.8 + * + * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. */ pipe - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; @@ -7412,7 +7674,7 @@ declare namespace JQuery { * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7448,7 +7710,7 @@ declare namespace JQuery { * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7477,7 +7739,7 @@ declare namespace JQuery { * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7506,19 +7768,19 @@ declare namespace JQuery { * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: null, - progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase( + doneFilter: null, + failFilter: null, + progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; @@ -7528,7 +7790,7 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; @@ -7557,19 +7819,19 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; @@ -7579,19 +7841,19 @@ declare namespace JQuery { * @param doneFilter An optional function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} + * @see \`{@link https://api.jquery.com/deferred.then/ }\` * @since 1.8 */ then - (doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; @@ -7602,17 +7864,17 @@ declare namespace JQuery { * Add handlers to be called when the Deferred object is rejected. * * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} + * @see \`{@link https://api.jquery.com/deferred.catch/ }\` * @since 3.0 */ catch - (failFilter?: ((...t: TJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase( + failFilter?: ((...t: TJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; @@ -7630,22 +7892,22 @@ declare namespace JQuery { } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. */ interface DoneCallback extends Callback { } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. */ interface FailCallback extends Callback { } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. */ interface AlwaysCallback extends Callback { } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. */ interface ProgressCallback extends Callback { } } @@ -7663,14 +7925,14 @@ declare namespace JQuery { } /** - * @see {@link https://api.jquery.com/animate/#animate-properties-options} + * @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\` */ interface EffectsOptions { /** * A function to be called when the animation on an element completes or stops without completing (its * Promise object is either resolved or rejected). */ - always?(this: TElement, animation: JQuery.Promise, jumpedToEnd: boolean): void; + always?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; /** * A function that is called once the animation on an element is complete. */ @@ -7678,7 +7940,7 @@ declare namespace JQuery { /** * A function to be called when the animation on an element completes (its Promise object is resolved). */ - done?(this: TElement, animation: JQuery.Promise, jumpedToEnd: boolean): void; + done?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; /** * A string or number determining how long the animation will run. */ @@ -7690,12 +7952,12 @@ declare namespace JQuery { /** * A function to be called when the animation on an element fails to complete (its Promise object is rejected). */ - fail?(this: TElement, animation: JQuery.Promise, jumpedToEnd: boolean): void; + fail?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; /** * A function to be called after each step of the animation, only once per animated element regardless * of the number of animated properties. */ - progress?(this: TElement, animation: JQuery.Promise, progress: number, remainingMs: number): void; + progress?(this: TElement, animation: Promise, progress: number, remainingMs: number): void; /** * A Boolean indicating whether to place the animation in the effects queue. If false, the animation * will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case @@ -7711,7 +7973,7 @@ declare namespace JQuery { /** * A function to call when the animation on an element begins. */ - start?(this: TElement, animation: JQuery.Promise): void; + start?(this: TElement, animation: Promise): void; /** * A function to be called for each animated property of each animated element. This function provides * an opportunity to modify the Tween object to change the value of the property before it is set. @@ -7751,7 +8013,7 @@ declare namespace JQuery { } interface AnimationHook { - (fx: JQuery.Tween): void; + (fx: Tween): void; } // endregion @@ -7763,11 +8025,15 @@ declare namespace JQuery { // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. // Static members - interface EventStatic { - (event: string, properties?: T): JQuery.Event & T; - (properties: T): JQuery.Event & T; - new (event: string, properties?: T): JQuery.Event & T; - new (properties: T): JQuery.Event & T; + interface EventStatic { + // tslint:disable-next-line:no-unnecessary-generics + (event: string, properties?: T): Event & T; + // tslint:disable-next-line:no-unnecessary-generics + (properties: T): Event & T; + // tslint:disable-next-line:no-unnecessary-generics + new (event: string, properties?: T): Event & T; + // tslint:disable-next-line:no-unnecessary-generics + new (properties: T): Event & T; } // Instance members @@ -7775,98 +8041,98 @@ declare namespace JQuery { /** * Indicates whether the META key was pressed when the event fired. * - * @see {@link https://api.jquery.com/event.metaKey/} + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` * @since 1.0.4 */ metaKey: boolean; /** * The namespace specified when the event was triggered. * - * @see {@link https://api.jquery.com/event.namespace/} + * @see \`{@link https://api.jquery.com/event.namespace/ }\` * @since 1.4.3 */ namespace: string; /** * The mouse position relative to the left edge of the document. * - * @see {@link https://api.jquery.com/event.pageX/} + * @see \`{@link https://api.jquery.com/event.pageX/ }\` * @since 1.0.4 */ pageX: number; /** * The mouse position relative to the top edge of the document. * - * @see {@link https://api.jquery.com/event.pageY/} + * @see \`{@link https://api.jquery.com/event.pageY/ }\` * @since 1.0.4 */ pageY: number; /** * The last value returned by an event handler that was triggered by this event, unless the value was undefined. * - * @see {@link https://api.jquery.com/event.result/} + * @see \`{@link https://api.jquery.com/event.result/ }\` * @since 1.3 */ result: any; /** * The difference in milliseconds between the time the browser created the event and January 1, 1970. * - * @see {@link https://api.jquery.com/event.timeStamp/} + * @see \`{@link https://api.jquery.com/event.timeStamp/ }\` * @since 1.2.6 */ timeStamp: number; /** * Describes the nature of the event. * - * @see {@link https://api.jquery.com/event.type/} + * @see \`{@link https://api.jquery.com/event.type/ }\` * @since 1.0 */ type: string; /** * For key or mouse events, this property indicates the specific key or button that was pressed. * - * @see {@link https://api.jquery.com/event.which/} + * @see \`{@link https://api.jquery.com/event.which/ }\` * @since 1.1.3 */ which: number; /** * Returns whether event.preventDefault() was ever called on this event object. * - * @see {@link https://api.jquery.com/event.isDefaultPrevented/} + * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` * @since 1.3 */ isDefaultPrevented(): boolean; /** * Returns whether event.stopImmediatePropagation() was ever called on this event object. * - * @see {@link https://api.jquery.com/event.isImmediatePropagationStopped/} + * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` * @since 1.3 */ isImmediatePropagationStopped(): boolean; /** * Returns whether event.stopPropagation() was ever called on this event object. * - * @see {@link https://api.jquery.com/event.isPropagationStopped/} + * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` * @since 1.3 */ isPropagationStopped(): boolean; /** * If this method is called, the default action of the event will not be triggered. * - * @see {@link https://api.jquery.com/event.preventDefault/} + * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` * @since 1.0 */ preventDefault(): void; /** * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. * - * @see {@link https://api.jquery.com/event.stopImmediatePropagation/} + * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` * @since 1.3 */ stopImmediatePropagation(): void; /** * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. * - * @see {@link https://api.jquery.com/event.stopPropagation/} + * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` * @since 1.0 */ stopPropagation(): void; @@ -7881,21 +8147,21 @@ declare namespace JQuery { /** * The current DOM element within the event bubbling phase. * - * @see {@link https://api.jquery.com/event.currentTarget/} + * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` * @since 1.3 */ currentTarget: TTarget; /** * An optional object of data passed to an event method when the current executing handler is bound. * - * @see {@link https://api.jquery.com/event.data/} + * @see \`{@link https://api.jquery.com/event.data/ }\` * @since 1.1 */ data: TData; /** * The element where the currently-called jQuery event handler was attached. * - * @see {@link https://api.jquery.com/event.delegateTarget/} + * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` * @since 1.7 */ delegateTarget: TTarget; @@ -7903,14 +8169,14 @@ declare namespace JQuery { /** * The other DOM element involved in the event, if any. * - * @see {@link https://api.jquery.com/event.relatedTarget/} + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` * @since 1.1.4 */ relatedTarget: TTarget | null; /** * The DOM element that initiated the event. * - * @see {@link https://api.jquery.com/event.target/} + * @see \`{@link https://api.jquery.com/event.target/ }\` * @since 1.0 */ target: TTarget; @@ -7922,14 +8188,15 @@ declare namespace JQuery { // endregion - interface EventHandler extends EventHandlerBase> { } + interface EventHandler extends EventHandlerBase> { } - interface EventHandlerBase { + interface EventHandlerBase { // Extra parameters can be passed from trigger() (this: TContext, t: T, ...args: any[]): void | false | any; } // Provided for convenience for use with jQuery.Event.which + // tslint:disable-next-line:no-const-enum const enum Mouse { None = 0, Left = 1, @@ -7938,6 +8205,7 @@ declare namespace JQuery { } // Provided for convenience for use with jQuery.Event.which + // tslint:disable-next-line:no-const-enum const enum Key { Backspace = 8, Tab = 9, @@ -8074,33 +8342,40 @@ declare namespace JQuery { // region Legacy types -interface JQueryCallback extends JQuery.Callbacks { } +// tslint:disable-next-line:no-empty-interface +interface JQueryCallback extends JQuery.Callbacks { } interface JQueryDeferred extends JQuery.Deferred { } -interface JQueryEventConstructor extends JQuery.Event { } +// tslint:disable-next-line:no-empty-interface +interface JQueryEventConstructor extends JQuery.EventStatic { } interface JQueryDeferred extends JQuery.Deferred { } +// tslint:disable-next-line:no-empty-interface interface JQueryAjaxSettings extends JQuery.AjaxSettings { } interface JQueryAnimationOptions extends JQuery.EffectsOptions { } +// tslint:disable-next-line:no-empty-interface interface JQueryCoordinates extends JQuery.Coordinates { } interface JQueryGenericPromise extends JQuery.Thenable { } +// tslint:disable-next-line:no-empty-interface interface JQueryXHR extends JQuery.jqXHR { } interface JQueryPromise extends JQuery.Promise { } +// tslint:disable-next-line:no-empty-interface interface JQuerySerializeArrayElement extends JQuery.NameValuePair { } /** - * @deprecated 1.9 + * @deprecated Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. */ +// tslint:disable-next-line:no-empty-interface interface JQuerySupport extends JQuery.PlainObject { } // Legacy types that are not represented in the current type definitions are marked deprecated. /** - * @deprecated + * @deprecated Use \`{@link JQuery.Deferred.Callback }\` or \`{@link JQuery.Deferred.CallbackBase }\`. */ interface JQueryPromiseCallback { (value?: T, ...args: any[]): void; } /** - * @deprecated + * @deprecated Use \`{@link JQueryStatic.param JQueryStatic['param']}\`. */ interface JQueryParam { /** @@ -8112,102 +8387,102 @@ interface JQueryParam { (obj: any, traditional?: boolean): string; } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Event }\`. */ interface BaseJQueryEventObject extends Event { /** * The current DOM element within the event bubbling phase. - * @see {@link https://api.jquery.com/event.currentTarget/} + * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` */ currentTarget: Element; /** * An optional object of data passed to an event method when the current executing handler is bound. - * @see {@link https://api.jquery.com/event.data/} + * @see \`{@link https://api.jquery.com/event.data/ }\` */ data: any; /** * The element where the currently-called jQuery event handler was attached. - * @see {@link https://api.jquery.com/event.delegateTarget/} + * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` */ delegateTarget: Element; /** * Returns whether event.preventDefault() was ever called on this event object. - * @see {@link https://api.jquery.com/event.isDefaultPrevented/} + * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` */ isDefaultPrevented(): boolean; /** * Returns whether event.stopImmediatePropagation() was ever called on this event object. - * @see {@link https://api.jquery.com/event.isImmediatePropagationStopped/} + * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` */ isImmediatePropagationStopped(): boolean; /** * Returns whether event.stopPropagation() was ever called on this event object. - * @see {@link https://api.jquery.com/event.isPropagationStopped/} + * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` */ isPropagationStopped(): boolean; /** * The namespace specified when the event was triggered. - * @see {@link https://api.jquery.com/event.namespace/} + * @see \`{@link https://api.jquery.com/event.namespace/ }\` */ namespace: string; /** * The browser's original Event object. - * @see {@link https://api.jquery.com/category/events/event-object/} + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` */ originalEvent: Event; /** * If this method is called, the default action of the event will not be triggered. - * @see {@link https://api.jquery.com/event.preventDefault/} + * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` */ preventDefault(): any; /** * The other DOM element involved in the event, if any. - * @see {@link https://api.jquery.com/event.relatedTarget/} + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` */ relatedTarget: Element; /** * The last value returned by an event handler that was triggered by this event, unless the value was undefined. - * @see {@link https://api.jquery.com/event.result/} + * @see \`{@link https://api.jquery.com/event.result/ }\` */ result: any; /** * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. - * @see {@link https://api.jquery.com/event.stopImmediatePropagation/} + * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` */ stopImmediatePropagation(): void; /** * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. - * @see {@link https://api.jquery.com/event.stopPropagation/} + * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` */ stopPropagation(): void; /** * The DOM element that initiated the event. - * @see {@link https://api.jquery.com/event.target/} + * @see \`{@link https://api.jquery.com/event.target/ }\` */ target: Element; /** * The mouse position relative to the left edge of the document. - * @see {@link https://api.jquery.com/event.pageX/} + * @see \`{@link https://api.jquery.com/event.pageX/ }\` */ pageX: number; /** * The mouse position relative to the top edge of the document. - * @see {@link https://api.jquery.com/event.pageY/} + * @see \`{@link https://api.jquery.com/event.pageY/ }\` */ pageY: number; /** * For key or mouse events, this property indicates the specific key or button that was pressed. - * @see {@link https://api.jquery.com/event.which/} + * @see \`{@link https://api.jquery.com/event.which/ }\` */ which: number; /** * Indicates whether the META key was pressed when the event fired. - * @see {@link https://api.jquery.com/event.metaKey/} + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` */ metaKey: boolean; } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Event }\`. */ interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; @@ -8216,7 +8491,7 @@ interface JQueryInputEventObject extends BaseJQueryEventObject { shiftKey: boolean; } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Event }\`. */ interface JQueryMouseEventObject extends JQueryInputEventObject { button: number; @@ -8230,7 +8505,7 @@ interface JQueryMouseEventObject extends JQueryInputEventObject { screenY: number; } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Event }\`. */ interface JQueryKeyEventObject extends JQueryInputEventObject { char: any; @@ -8239,7 +8514,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } /** - * @deprecated + * @deprecated Use \`{@link JQuery.Event }\`. */ interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } /** @@ -8250,13 +8525,13 @@ interface JQueryPromiseOperator { ...callbacksN: Array>>): JQueryPromise; } /** - * @deprecated + * @deprecated Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. */ interface JQueryEasingFunction { (percent: number): number; } /** - * @deprecated + * @deprecated Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. */ interface JQueryEasingFunctions { [name: string]: JQueryEasingFunction; diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 47a85b80d2..c569758fb0 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1,8 +1,4 @@ function JQueryStatic() { - function type_assertion() { - const $Canvas = $ as JQueryStatic; - } - function type_annotation() { const jq: JQueryStatic = $; } @@ -21,6 +17,9 @@ function JQueryStatic() { } }); + // $ExpectType JQuery + $('

'); + // $ExpectType JQuery $('span', new HTMLElement()); @@ -33,31 +32,77 @@ function JQueryStatic() { // $ExpectType JQuery $('span'); - // $ExpectType JQuery - $('

'); + // $ExpectType JQuery + $('.mysvgline'); - // $ExpectType JQuery - $(new HTMLElement()); + // $ExpectType JQuery + $(new HTMLParagraphElement()); - // $ExpectType JQuery - $([new HTMLElement()]); + // $ExpectType JQuery + $([new HTMLParagraphElement()]); - // $ExpectType JQuery + // $ExpectType JQuery<{ foo: string; hello: string; }> $({ foo: 'bar', hello: 'world' }); - // $ExpectType JQuery - $($('p')); + // $ExpectType JQuery + $($(document.createElementNS("http://www.w3.org/2000/svg", "svg"))); // $ExpectType JQuery $(function($) { // $ExpectType Document this; - // $ExpectType JQueryStatic + // $ExpectType JQueryStatic + $; + }); + + // $ExpectType JQuery + $(function($) { + // $ExpectType Document + this; + // $ExpectType JQueryStatic $; }); // $ExpectType JQuery $(); + + // $ExpectType JQuery + $(); + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/19597#issuecomment-378218432 + function issue_19597_378218432() { + const myDiv = $(document.createElement('div')); + // $ExpectType JQuery + myDiv; + myDiv.on('click', (evt) => { + const target = evt.target; + // $ExpectType HTMLDivElement + target; + }); + const myDiv1 = $(document.createElement('div')); + + const myForcedDiv: JQuery = $(document.createElement('div')) as any; + myForcedDiv.on('click', (evt) => { + const target = evt.target; // HTMLDivElement + // $ExpectType HTMLDivElement + target; + }); + const myDoc = $(document); + // $ExpectType JQuery + myDoc; + myDoc.on('click', (evt) => { + const target = evt.target; + // $ExpectType Document + target; + }); + const myDocForced: JQuery = $(document); + const myWindow = $(window); + // $ExpectType JQuery + myWindow; + const myWindowForced: JQuery = $(window); + // $ExpectType JQuery + myWindowForced; + } } function ajaxSettings() { @@ -66,7 +111,7 @@ function JQueryStatic() { } function Event() { - // $ExpectType EventStatic + // $ExpectType EventStatic $.Event; } @@ -103,7 +148,7 @@ function JQueryStatic() { } function ready() { - // $ExpectType Thenable> + // $ExpectType Thenable $.ready; } @@ -699,7 +744,9 @@ function JQueryStatic() { function map() { // $ExpectType number[] - $.map([1, 2, 3], (elementOfArray, indexInArray) => { + $.map([1, 2, 3], function(elementOfArray, indexInArray) { + // $ExpectType Window + this; // $ExpectType number elementOfArray; // $ExpectType number @@ -708,11 +755,49 @@ function JQueryStatic() { return 200 + 10; }); + // $ExpectType number[] + $.map([1, 2, 3], function(elementOfArray, indexInArray) { + // $ExpectType Window + this; + // $ExpectType number + elementOfArray; + // $ExpectType number + indexInArray; + + return [200, 10]; + }); + + // $ExpectType (number | null)[] + $.map([1, 2, 3], function(elementOfArray, indexInArray) { + // $ExpectType Window + this; + // $ExpectType number + elementOfArray; + // $ExpectType number + indexInArray; + + return [200, 10, null]; + }); + + // $ExpectType (number | undefined)[] + $.map([1, 2, 3], function(elementOfArray, indexInArray) { + // $ExpectType Window + this; + // $ExpectType number + elementOfArray; + // $ExpectType number + indexInArray; + + return [200, 10, undefined]; + }); + // $ExpectType (false | 1)[] $.map({ myProp: true, name: 'Rogers', - }, (propertyOfObject, key) => { + }, function(propertyOfObject, key) { + // $ExpectType Window + this; // $ExpectType string | boolean propertyOfObject; // $ExpectType "myProp" | "name" @@ -725,6 +810,67 @@ function JQueryStatic() { return false; } }); + + // $ExpectType (string | number | boolean)[] + $.map({ + myProp: true, + name: 'Rogers', + }, function(propertyOfObject, key) { + // $ExpectType Window + this; + // $ExpectType string | boolean + propertyOfObject; + // $ExpectType "myProp" | "name" + key; + + return [propertyOfObject, 24]; + }); + + // $ExpectType (false | 1)[] + $.map({ + myProp: true, + name: 'Rogers', + anotherProp: 70, + }, function(propertyOfObject, key) { + // $ExpectType Window + this; + // $ExpectType string | number | boolean + propertyOfObject; + // $ExpectType "myProp" | "name" | "anotherProp" + key; + + switch (key) { + case 'myProp': + return 1; + case 'name': + return false; + } + + return null; + }); + + // $ExpectType (false | 1)[] + $.map({ + myProp: true, + name: 'Rogers', + anotherProp: 70, + }, function(propertyOfObject, key) { + // $ExpectType Window + this; + // $ExpectType string | number | boolean + propertyOfObject; + // $ExpectType "myProp" | "name" | "anotherProp" + key; + + switch (key) { + case 'myProp': + return 1; + case 'name': + return false; + } + + return undefined; + }); } function merge() { @@ -733,10 +879,10 @@ function JQueryStatic() { } function noConflict() { - // $ExpectType JQueryStatic + // $ExpectType JQueryStatic $.noConflict(true); - // $ExpectType JQueryStatic + // $ExpectType JQueryStatic $.noConflict(); } @@ -2021,9 +2167,8 @@ function JQueryStatic() { } function JQuery() { - function type_assertion() { - const $el = $(document.createElement('canvas')); - const $canvas = $el as JQuery; + function type_annotation() { + const $canvas: JQuery = $(document.createElement('canvas')); } function iterable() { @@ -2041,7 +2186,7 @@ function JQuery() { function ajax() { function ajaxComplete() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; @@ -2057,7 +2202,7 @@ function JQuery() { } function ajaxError() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; @@ -2075,7 +2220,7 @@ function JQuery() { } function ajaxSend() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; @@ -2091,7 +2236,7 @@ function JQuery() { } function ajaxStart() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxStart(function() { // $ExpectType Document this; @@ -2101,7 +2246,7 @@ function JQuery() { } function ajaxStop() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxStop(function() { // $ExpectType Document this; @@ -2111,7 +2256,7 @@ function JQuery() { } function ajaxSuccess() { - // $ExpectType JQuery + // $ExpectType JQuery $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; @@ -5208,7 +5353,7 @@ function JQuery() { function ready() { // $ExpectType JQuery $('p').ready(($) => { - // $ExpectType JQueryStatic + // $ExpectType JQueryStatic $; }); } @@ -5898,8 +6043,9 @@ function JQuery() { } function contents() { - // $ExpectType JQuery - $('p').contents(); + // TODO: Flaky test due to type ordering. + // // $ExpectType JQuery + // $('p').contents(); } function end() { @@ -6131,7 +6277,7 @@ function JQuery() { } function map() { - // $ExpectType JQuery + // $ExpectType JQuery $('p').map(function(index, domElement) { // $ExpectType HTMLElement this; @@ -6143,7 +6289,7 @@ function JQuery() { return 'myVal'; }); - // $ExpectType JQuery + // $ExpectType JQuery $('p').map(function(index, domElement) { // $ExpectType HTMLElement this; @@ -6155,7 +6301,7 @@ function JQuery() { return ['myVal1', 'myVal2']; }); - // $ExpectType JQuery + // $ExpectType JQuery $('p').map(function(index, domElement) { // $ExpectType HTMLElement this; @@ -6164,10 +6310,10 @@ function JQuery() { // $ExpectType HTMLElement domElement; - return null; + return ['myVal1', 'myVal2', null]; }); - // $ExpectType JQuery + // $ExpectType JQuery $('p').map(function(index, domElement) { // $ExpectType HTMLElement this; @@ -6176,8 +6322,72 @@ function JQuery() { // $ExpectType HTMLElement domElement; - return undefined; + return ['myVal1', 'myVal2', undefined]; }); + + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + let value: string; + + if (index % 2 === 0) { + return null; + } + + value = 'myVal'; + + return value; + }); + + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + let value: string; + + if (index % 2 === 0) { + return undefined; + } + + value = 'myVal'; + + return value; + }); + + // // $ExpectType JQuery + // $('p').map(function(index, domElement) { + // // $ExpectType HTMLElement + // this; + // // $ExpectType number + // index; + // // $ExpectType HTMLElement + // domElement; + // + // return null; + // }); + + // // $ExpectType JQuery + // $('p').map(function(index, domElement) { + // // $ExpectType HTMLElement + // this; + // // $ExpectType number + // index; + // // $ExpectType HTMLElement + // domElement; + // + // return undefined; + // }); } function slice() { @@ -6857,7 +7067,7 @@ function JQuery_jqXHR() { } } - function compatibleWithPromise(): Promise { + function compatibleWithPromise(): JQuery._Promise { return p; } @@ -6877,6 +7087,7 @@ function JQuery_Promise3() { interface I8 { kind: 'I8'; } interface I9 { kind: 'I9'; } + // tslint:disable-next-line:ban-types const p: JQuery.Promise3 = {} as any; const p1: JQuery.Promise3 = {} as any; const p2: JQuery.Promise3 = {} as any; @@ -6987,7 +7198,7 @@ function JQuery_Promise3() { p.then(() => { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(() => { @@ -7017,7 +7228,7 @@ function JQuery_Promise3() { p.then(null, () => { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(null, () => { @@ -7254,7 +7465,7 @@ function JQuery_Promise3() { }); // $ExpectType PromiseBase, never, SuccessTextStatus, ErrorTextStatus, never, jqXHR, string, never, never, never, never> a; - const b: JQuery.Promise3, never, JQuery.Ajax.SuccessTextStatus, JQuery.Ajax.ErrorTextStatus, never, JQuery.jqXHR, string, never> = a; + const b: JQuery.Promise3 = a; } // $ExpectType PromiseBase @@ -7275,11 +7486,12 @@ function JQuery_Promise3() { } async function testAsync(p: JQuery.Promise3): Promise { + // tslint:disable-next-line:await-promise const s: string = await p; return s; } - function compatibleWithPromise(): Promise { + function compatibleWithPromise(): JQuery._Promise { return p; } @@ -7373,7 +7585,7 @@ function JQuery_Promise2(p: JQuery.Promise2 { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(() => { @@ -7400,7 +7612,7 @@ function JQuery_Promise2(p: JQuery.Promise2 { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(null, () => { @@ -7419,11 +7631,12 @@ function JQuery_Promise2(p: JQuery.Promise2): Promise { + // tslint:disable-next-line:await-promise const s: string = await p; return s; } - function compatibleWithPromise(): Promise { + function compatibleWithPromise(): JQuery._Promise { return p; } @@ -7500,7 +7713,7 @@ function JQuery_Promise(p: JQuery.Promise) { p.then(() => { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(() => { @@ -7524,7 +7737,7 @@ function JQuery_Promise(p: JQuery.Promise) { p.then(null, () => { return $.ready; }).then((a) => { - a; // $ExpectType JQueryStatic + a; // $ExpectType JQueryStatic }); p.then(null, () => { @@ -7544,7 +7757,7 @@ function JQuery_Promise(p: JQuery.Promise) { return s; } - function compatibleWithPromise(): Promise { + function compatibleWithPromise(): JQuery._Promise { return p; } } diff --git a/types/jquery/test/bluebird-global-tests.ts b/types/jquery/test/bluebird-global-tests.ts new file mode 100644 index 0000000000..3b7f58e9cd --- /dev/null +++ b/types/jquery/test/bluebird-global-tests.ts @@ -0,0 +1,4 @@ +/// + +// Pulls in bluebird-global to test compatibility. +// Fixes https://github.com/DefinitelyTyped/DefinitelyTyped/issues/26328. diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 728a42b3d6..f725cb2bcb 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -3428,7 +3428,7 @@ function examples() { function map_0() { $('p') .append($('input').map(function() { - return $(this).val(); + return $(this).val() as string; }) .get() .join(', ')); diff --git a/types/jquery/test/jquery-no-window-module-tests.ts b/types/jquery/test/jquery-no-window-module-tests.ts index 2f2de4cc98..783031a672 100644 --- a/types/jquery/test/jquery-no-window-module-tests.ts +++ b/types/jquery/test/jquery-no-window-module-tests.ts @@ -1,5 +1,5 @@ import jQueryFactory = require('jquery'); const jq = jQueryFactory(window, true); -// $ExpectType JQueryStatic +// $ExpectType JQueryStatic jq; diff --git a/types/jquery/test/jquery-slim-no-window-module-tests.ts b/types/jquery/test/jquery-slim-no-window-module-tests.ts index 2e104af0eb..16793e0d2c 100644 --- a/types/jquery/test/jquery-slim-no-window-module-tests.ts +++ b/types/jquery/test/jquery-slim-no-window-module-tests.ts @@ -1,5 +1,5 @@ import jQueryFactory = require('jquery/dist/jquery.slim'); const jq = jQueryFactory(window, true); -// $ExpectType JQueryStatic +// $ExpectType JQueryStatic jq; diff --git a/types/jquery/test/jquery-slim-window-module-tests.ts b/types/jquery/test/jquery-slim-window-module-tests.ts index b47707cb23..bf4331d824 100644 --- a/types/jquery/test/jquery-slim-window-module-tests.ts +++ b/types/jquery/test/jquery-slim-window-module-tests.ts @@ -1,5 +1,5 @@ import jq = require('jquery/dist/jquery.slim'); const $window = jq(window); -// $ExpectType JQuery +// $ExpectType JQuery $window; diff --git a/types/jquery/test/jquery-window-module-tests.ts b/types/jquery/test/jquery-window-module-tests.ts index 6bc5486fb9..1d554f0861 100644 --- a/types/jquery/test/jquery-window-module-tests.ts +++ b/types/jquery/test/jquery-window-module-tests.ts @@ -1,18 +1,5 @@ import jq = require('jquery'); const $window = jq(window); -// $ExpectType JQuery +// $ExpectType JQuery $window; - -class CanvasLayersDirective { - private readonly $renderingCanvas: JQuery; - private readonly $offscreenCanvas: JQuery; - - constructor(elementRef: { nativeElement: any; }) { - // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where - // 'factory' is jQuery's factory function. - const $Canvas = $ as JQueryStatic; - this.$renderingCanvas = $Canvas(elementRef.nativeElement); - this.$offscreenCanvas = $Canvas(document.createElement('canvas')); - } -} diff --git a/types/jquery/tsconfig.json b/types/jquery/tsconfig.json index e481dc63c6..40a0bc76d4 100644 --- a/types/jquery/tsconfig.json +++ b/types/jquery/tsconfig.json @@ -21,6 +21,7 @@ "files": [ "index.d.ts", "jquery-tests.ts", + "test/bluebird-global-tests.ts", "test/example-tests.ts", "test/longdesc-tests.ts", "test/learn-tests.ts", @@ -29,4 +30,4 @@ "test/jquery-slim-no-window-module-tests.ts", "test/jquery-slim-window-module-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jquery/tslint.json b/types/jquery/tslint.json index deae83dc66..1d12f59138 100644 --- a/types/jquery/tslint.json +++ b/types/jquery/tslint.json @@ -1,23 +1,16 @@ { "extends": "dtslint/dt.json", "rules": { - // All are TODOs - "await-promise": false, - "ban-types": false, "callable-types": false, "interface-name": false, "no-any-union": false, + "no-declare-current-package": false, + + "ban-types": false, "no-arg": false, "no-boolean-literal-compare": false, - "no-const-enum": false, - "no-declare-current-package": false, - "no-empty-interface": false, - "no-misused-new": false, "no-object-literal-type-assertion": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, - "no-var": false, "no-var-keyword": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, @@ -28,9 +21,7 @@ "prefer-for-of": false, "prefer-switch": false, "prefer-template": false, - "space-before-function-paren": false, "space-within-parens": false, - "triple-equals": false, - "use-default-type-parameter": false + "triple-equals": false } } diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index 5ccdd33a65..cfb54fa25f 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -7,7 +7,7 @@ /// import { EventEmitter } from 'events'; -import { ElementLocation } from 'parse5'; +import { MarkupData } from 'parse5'; import * as tough from 'tough-cookie'; import { Script } from 'vm'; @@ -32,7 +32,7 @@ export class JSDOM { /** * The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node. */ - nodeLocation(node: Node): ElementLocation | null; + nodeLocation(node: Node): MarkupData.ElementLocation | null; /** * The built-in vm module of Node.js allows you to create Script instances, diff --git a/types/jsdom/package.json b/types/jsdom/package.json index c208056015..ef0b8c56fc 100644 --- a/types/jsdom/package.json +++ b/types/jsdom/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "parse5": "^3.0.2" + "parse5": "^4.0.0" } } diff --git a/types/jsdom/tsconfig.json b/types/jsdom/tsconfig.json index fe7f9dd41f..d75878188a 100644 --- a/types/jsdom/tsconfig.json +++ b/types/jsdom/tsconfig.json @@ -15,10 +15,13 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "paths": { + "parse5": [ "parse5/v4" ] + } }, "files": [ "index.d.ts", "jsdom-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jsreport-html-to-xlsx/index.d.ts b/types/jsreport-html-to-xlsx/index.d.ts index 84b37480aa..83ac765c1f 100644 --- a/types/jsreport-html-to-xlsx/index.d.ts +++ b/types/jsreport-html-to-xlsx/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsreport-html-to-xlsx 1.4 +// Type definitions for jsreport-html-to-xlsx 2.0 // Project: https://github.com/jsreport/jsreport-html-to-xlsx // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,9 @@ import { ExtensionDefinition } from 'jsreport-core'; import { Options as BaseOptions } from 'jsreport-xlsx'; declare module 'jsreport-core' { + type htmlEngine = 'phantom' | 'chrome'; interface Template { + htmlToXlsx: { htmlEngine: htmlEngine; }; recipe: 'html-to-xlsx' | string; } } diff --git a/types/jsreport-html-to-xlsx/v1/index.d.ts b/types/jsreport-html-to-xlsx/v1/index.d.ts new file mode 100644 index 0000000000..84b37480aa --- /dev/null +++ b/types/jsreport-html-to-xlsx/v1/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for jsreport-html-to-xlsx 1.4 +// Project: https://github.com/jsreport/jsreport-html-to-xlsx +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { ExtensionDefinition } from 'jsreport-core'; +import { Options as BaseOptions } from 'jsreport-xlsx'; + +declare module 'jsreport-core' { + interface Template { + recipe: 'html-to-xlsx' | string; + } +} + +declare namespace JsReportHtml2Xlsx { + interface Options extends BaseOptions { + strategy: string; + } +} + +declare function JsReportHtml2Xlsx(options?: Partial): ExtensionDefinition; + +export = JsReportHtml2Xlsx; diff --git a/types/jsreport-html-to-xlsx/v1/jsreport-html-to-xlsx-tests.ts b/types/jsreport-html-to-xlsx/v1/jsreport-html-to-xlsx-tests.ts new file mode 100644 index 0000000000..9540cf7929 --- /dev/null +++ b/types/jsreport-html-to-xlsx/v1/jsreport-html-to-xlsx-tests.ts @@ -0,0 +1,19 @@ +import JsReport = require('jsreport-core'); +import JsreportHtml2Xlsx = require('jsreport-html-to-xlsx'); +import JsreportXlsx = require('jsreport-xlsx'); + +const jsreport = JsReport(); +jsreport.use(JsreportXlsx()); +jsreport.use(JsreportHtml2Xlsx()); + +(async () => { + const content = `
test
`; + await jsreport.init(); + const resp = await jsreport.render({ + template: { + content, + engine: 'none', + recipe: 'xlsx' + } + }); +})(); diff --git a/types/jsreport-html-to-xlsx/v1/tsconfig.json b/types/jsreport-html-to-xlsx/v1/tsconfig.json new file mode 100644 index 0000000000..6b073aa725 --- /dev/null +++ b/types/jsreport-html-to-xlsx/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "esnext" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "jsreport-html-to-xlsx": [ "jsreport-html-to-xlsx/v1" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsreport-html-to-xlsx-tests.ts" + ] +} diff --git a/types/jsreport-html-to-xlsx/v1/tslint.json b/types/jsreport-html-to-xlsx/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsreport-html-to-xlsx/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/karma-chai/index.d.ts b/types/karma-chai/index.d.ts index 87910cb6e2..15c7010071 100644 --- a/types/karma-chai/index.d.ts +++ b/types/karma-chai/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for karma-chai 0.1 // Project: http://xdissent.github.io/karma-chai -// Definitions by: Jay Sherby +// Definitions by: JayAndCatchFire // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import chai = require('chai'); diff --git a/types/leaflet.locatecontrol/index.d.ts b/types/leaflet.locatecontrol/index.d.ts index 542461cec7..0afcd0d613 100644 --- a/types/leaflet.locatecontrol/index.d.ts +++ b/types/leaflet.locatecontrol/index.d.ts @@ -27,7 +27,7 @@ declare module 'leaflet' { drawMarker?: boolean; markerClass?: any; circleStyle?: PathOptions; - markerStyle?: PathOptions; + markerStyle?: PathOptions | MarkerOptions; followCircleStyle?: PathOptions; followMarkerStyle?: PathOptions; icon?: string; diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index ceeb1a3783..7fc9e9e2bf 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -1,114 +1,173 @@ -// Type definitions for Libxmljs v0.14.2 -// Project: https://github.com/polotek/libxmljs +// Type definitions for Libxmljs 0.18 +// Project: https://github.com/libxmljs/libxmljs // Definitions by: François de Campredon +// ComFreek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +import { EventEmitter } from 'events'; +export const version: string; +export const libxml_version: string; +export const libxml_parser_version: string; +// tslint:disable-next-line:strict-export-declare-modifiers +interface ParseOptions { + [optionName: string]: string; +} -import events = require('events'); +export function parseXml(source: string, options?: ParseOptions): Document; +export function parseXmlString(source: string, options?: ParseOptions): Document; -export declare function parseXml(source: string): XMLDocument; -export declare function parseHtml(source: string): HTMLDocument; -export declare function parseXmlString(source: string, options?: { [key: string]: string }): XMLDocument; -export declare function parseHtmlString(source: string): HTMLDocument; +export function parseHtml(source: string, options?: ParseOptions): Document; +export function parseHtmlString(source: string, options?: ParseOptions): Document; +export function parseHtmlFragment(source: string, options?: ParseOptions): Document; +export function memoryUsage(): number; +export function nodeCount(): number; -export declare class XMLDocument { - constructor(version: number, encoding: string); - child(idx: number): Element | undefined; +export class Document { + /** + * Create a new XML Document + * @param version XML document version, defaults to 1.0 + * @param encoding Encoding, defaults to utf8 + */ + constructor(version?: number, encoding?: string); + + errors: SyntaxError[]; + + child(idx: number): Element|null; childNodes(): Element[]; - errors(): SyntaxError[]; encoding(): string; - encoding(enc: string): void; + encoding(enc: string): this; find(xpath: string): Element[]; - get(xpath: string): Element | undefined; - node(name: string, content: string): Element; - root(): Element; - toString(): string; - validate(xsdDoc: XMLDocument): boolean; - validationErrors: XmlError[]; - version(): Number; + get(xpath: string): Element|null; + node(name: string, content?: string): Element; + root(): Element|null; + root(newRoot: Node): Node; + toString(formatted?: boolean): string; + type(): 'document'; + version(): string; + setDtd(name: string, ext: string, sys: string): void; + getDtd(): { + name: string; + externalId: string; + systemId: string; + }; } -export declare class HTMLDocument extends XMLDocument { +export class Node { + doc(): Document; + parent(): Element|Document; + /** + * The namespace or null in case of comment nodes + */ + namespace(): Namespace|null; + /** + * An array of namespaces that the object belongs to. + * + * @param local If it is true, only the namespace declarations local to this + * node are returned, rather than all of the namespaces in scope + * at this node (including the ones from the parent elements). + */ + namespaces(local?: boolean): Namespace[]; + + prevSibling(): Node|null; + nextSibling(): Node|null; + + type(): 'comment'|'element'|'text'|'attribute'; + remove(): this; + clone(): this; + /** + * Serializes the node to a string. The string will contain all contents of the node formatted as XML and can be used to print the node. + */ + toString(format?: boolean|{ + declaration: boolean; + selfCloseEmpty: boolean; + whitespace: boolean; + type: 'xml'|'html'|'xhtml' + }): string; } - -export declare class Element { - constructor(doc: XMLDocument, name: string, content?: string); +export class Element extends Node { + constructor(doc: Document, name: string, content?: string); + node(name: string, content?: string): Element; name(): string; - name(newName: string): void; + name(newName: string): this; text(): string; - attr(name: string): Attribute; - attr(attr: Attribute): void; - attr(attrObject: { [key: string]: string; }): void; + text(newText: string): this; + attr(name: string): Attribute|null; + attr(attrObject: { [key: string]: string; }): this; attrs(): Attribute[]; - parent(): Element; - doc(): XMLDocument; - child(idx: number): Element | undefined; - childNodes(): Element[]; - addChild(child: Element): Element; - nextSibling(): Element; - nextElement(): Element; - addNextSibling(siblingNode: Element): Element; - prevSibling(): Element; - prevElement(): Element; - addPrevSibling(siblingNode: Element): Element; - find(xpath: string): Element[]; - find(xpath: string, ns_uri: string): Element[]; - find(xpath: string, namespaces: { [key: string]: string; }): Element[]; - get(xpath: string): Element | undefined; - get(xpath: string, ns_uri: string): Element | undefined; - get(xpath: string, ns_uri: { [key: string]: string; }): Element | undefined; - defineNamespace(href: string): Namespace; - defineNamespace(prefix: string, href: string): Namespace; - namespace(): Namespace; - namespace(ns: Namespace): void; - namespace(href: string): void; - namespace(prefix: string, href: string): void; - remove(): void; + + doc(): Document; + child(idx: number): Node | null; + childNodes(): Node[]; + + /** + * @return The original element, not the child. + */ + addChild(child: Element): this; + + prevElement(): Element|null; + nextElement(): Element|null; + addNextSibling(siblingNode: Node): Node; + + find(xpath: string, ns_uri?: string): Node[]; + find(xpath: string, namespaces: { [key: string]: string; }): Node[]; + get(xpath: string, ns_uri?: string): Element|null; + + defineNamespace(prefixOrHref: string, hrefInCaseOfPrefix?: string): Namespace; + + namespace(): Namespace|null; + namespace(newNamespace: Namespace): this; + namespace(prefixOrHref: string, hrefInCaseOfPrefix?: string): Namespace; + + replace(replacement: string): string; + replace(replacement: Element): Element; + path(): string; - type(): string; } - -export declare class Attribute { - constructor(node: Element, name: string, value: string); - constructor(node: Element, name: string, value: string, ns: Namespace); +export class Attribute { name(): string; - namespace(): Namespace; - namespace(ns: Namespace): Namespace; - nextSibling(): Attribute; - node(): Element; - prevSibling(): Attribute; - remove(): void; value(): string; + value(newValue: string): Attribute; + namespace(): Namespace; + + remove(): void; } -export declare class Namespace { - constructor(node: Element, prefix: string, href: string); +export class Namespace { href(): string; prefix(): string; } -export declare class SaxParser extends events.EventEmitter { +export class SaxParser extends EventEmitter { + constructor(); parseString(source: string): boolean; } - -export declare class SaxPushParser extends events.EventEmitter { +export class SaxPushParser extends EventEmitter { + constructor(); push(source: string): boolean; } -export interface XmlError { - domain: number; - code: number; - message: string; - level: number; - file?: string; +export interface SyntaxError { + domain: number|null; + code: number|null; + message: string|null; + level: number|null; + file: string|null; + line: number|null; + /** + * 1-based column number, 0 if not applicable/available. + */ column: number; - line: number; + + str1: number|null; + str2: number|null; + str3: number|null; + int1: number|null; } diff --git a/types/libxmljs/libxmljs-tests.ts b/types/libxmljs/libxmljs-tests.ts index 87d634aab4..367d74c69d 100644 --- a/types/libxmljs/libxmljs-tests.ts +++ b/types/libxmljs/libxmljs-tests.ts @@ -1,7 +1,6 @@ +import * as libxmljs from 'libxmljs'; - -var libxmljs = require("libxmljs"); -var xml = '' + +const xml = '' + '' + '' + 'grandchild content' + @@ -9,40 +8,42 @@ var xml = '' + 'with content!' + ''; -var xmlDoc = libxmljs.parseXml(xml); +const xmlDoc = libxmljs.parseXml(xml); // xpath queries -var gchild = xmlDoc.get('//grandchild'); +const gchild = xmlDoc.get('//grandchild')!; console.log(gchild.text()); // prints "grandchild content" -var children = xmlDoc.root().childNodes(); -var child = children[0]; +const children = xmlDoc.root()!.childNodes(); +const child = children[0] as libxmljs.Element; -console.log(child.attr('foo').value()); // prints "bar" +console.log(child.attr('foo')!.value()); // prints "bar" -var parser = new libxmljs.SaxParser(); +const parser = new libxmljs.SaxParser(); -parser.on('startDocument', null); -parser.on('startElement', null); +parser.on('startDocument', () => 0); +parser.on('startElement', () => 0); -var parser2 = new libxmljs.SaxPushParser(); +const parser2 = new libxmljs.SaxPushParser(); // connect any callbacks here parser2 - .on('startDocument', null) - .on('startElement', null) + .on('startDocument', () => 0) + .on('startElement', () => 0); -var xmlChunk: any; +const xmlChunk = ''; -while(xmlChunk) { +while (xmlChunk) { parser2.push(xmlChunk); } -var doc = new libxmljs.Document(); - doc.node('root') +const doc = new libxmljs.Document(); + ((doc.node('root') .node('child').attr({foo: 'bar'}) .node('grandchild', 'grandchild content').attr({baz: 'fizbuzz'}) .parent() - .parent() + ) as libxmljs.Element).parent() .node('sibling', 'with content!'); + +const {name, externalId, systemId} = doc.getDtd(); diff --git a/types/libxmljs/tsconfig.json b/types/libxmljs/tsconfig.json index 7201fffe81..45835560c6 100644 --- a/types/libxmljs/tsconfig.json +++ b/types/libxmljs/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/libxmljs/tslint.json b/types/libxmljs/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/libxmljs/tslint.json +++ b/types/libxmljs/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/libxslt/index.d.ts b/types/libxslt/index.d.ts index 329525d7df..3b400d08e7 100644 --- a/types/libxslt/index.d.ts +++ b/types/libxslt/index.d.ts @@ -1,59 +1,37 @@ -// Type definitions for node-libxslt +// Type definitions for node-libxslt 0.7 // Project: https://github.com/albanm/node-libxslt // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.2 import * as xmljs from 'libxmljs'; +import { + ApplyCallback, + ApplyResult, + ApplyStringCallback, + OutputFormat, + ParseCallback +} from './internal-types'; export const libxmljs: typeof xmljs; -type OutputFormat = 'document' | 'string'; - export interface ApplyOptions { outputFormat?: OutputFormat; noWrapParams?: boolean; } -type ApplyResult = string | xmljs.XMLDocument; - -type ApplyCallback = (err: Error, result: ApplyResult) => void; - -type ApplyStringCallback = (err: Error, result: string) => void; - -type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; - export interface Stylesheet { - apply(source: string, params?: Object): string; - - apply(source: string, params: Object, options: ApplyOptions): ApplyResult; - - apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; - - apply(source: string, callback: ApplyStringCallback): void; - - apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; - - apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; - - apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; - - apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; - - applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; + apply(source: string, params?: object): string; + apply(source: string|xmljs.Document, params: object, options: ApplyOptions): ApplyResult; + apply(source: string|xmljs.Document, params: object, options: ApplyOptions, callback: ApplyCallback): void; + apply(source: string|xmljs.Document, callback: ApplyStringCallback): void; + apply(source: xmljs.Document, params?: object): xmljs.Document; + applyToFile(sourcePath: string, params: object, options: ApplyOptions, callback: ApplyStringCallback): void; applyToFile(sourcePath: string, callback: ApplyStringCallback): void; } -type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; - -export function parse(source: string): Stylesheet; - -export function parse(source: string, callback: ParseCallback): void; - -export function parse(source: xmljs.XMLDocument): Stylesheet; - -export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; +export function parse(source: string|xmljs.Document): Stylesheet; +export function parse(source: string|xmljs.Document, callback: ParseCallback): void; export function parseFile(sourcePath: string, callback: ParseCallback): void; diff --git a/types/libxslt/internal-types.d.ts b/types/libxslt/internal-types.d.ts new file mode 100644 index 0000000000..a0d4041e52 --- /dev/null +++ b/types/libxslt/internal-types.d.ts @@ -0,0 +1,11 @@ +import * as xmljs from 'libxmljs'; +import { Stylesheet } from './index'; + +export type OutputFormat = 'document' | 'string'; + +export type ApplyResult = string | xmljs.Document; +export type ApplyCallback = (err: Error, result: ApplyResult) => void; +export type ApplyStringCallback = (err: Error, result: string) => void; +export type ApplyDocumentCallback = (err: Error, result: xmljs.Document) => void; + +export type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; diff --git a/types/libxslt/libxslt-tests.ts b/types/libxslt/libxslt-tests.ts index bed54e5f52..1530ad0eb1 100644 --- a/types/libxslt/libxslt-tests.ts +++ b/types/libxslt/libxslt-tests.ts @@ -1,7 +1,7 @@ import * as libxslt from 'libxslt'; import * as libxmljs from 'libxmljs'; -const document: libxmljs.XMLDocument = libxslt.libxmljs.parseXmlString(''); +const document: libxmljs.Document = libxslt.libxmljs.parseXmlString(''); let stylesheet: libxslt.Stylesheet; @@ -36,7 +36,7 @@ applyOptions = { let transformedString: string; -let transformedDocument: libxmljs.XMLDocument; +let transformedDocument: libxmljs.Document; transformedString = stylesheet.apply(''); diff --git a/types/libxslt/tsconfig.json b/types/libxslt/tsconfig.json index a7f7f94ffc..00f8d27037 100644 --- a/types/libxslt/tsconfig.json +++ b/types/libxslt/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "internal-types.d.ts", "libxslt-tests.ts" ] } \ No newline at end of file diff --git a/types/libxslt/tslint.json b/types/libxslt/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/libxslt/tslint.json +++ b/types/libxslt/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/lingui__core/formats.d.ts b/types/lingui__core/formats.d.ts new file mode 100644 index 0000000000..841f6404e8 --- /dev/null +++ b/types/lingui__core/formats.d.ts @@ -0,0 +1,2 @@ +export function date(language: string, format?: Intl.DateTimeFormatOptions): (value: Date) => string; +export function number(language: string, format?: Intl.NumberFormatOptions): (value: number) => string; diff --git a/types/lingui__core/i18n.d.ts b/types/lingui__core/i18n.d.ts new file mode 100644 index 0000000000..49f663a6a8 --- /dev/null +++ b/types/lingui__core/i18n.d.ts @@ -0,0 +1,69 @@ +import { SelectProps, PluralProps } from "./select"; + +// In flowtype, MessageOptions is declared as exact type +export interface MessageOptions { + defaults?: string; + formats?: object; +} + +export interface LanguageData { + plurals?: (n: number, pluralType?: "cardinal" | "ordinal") => string; +} + +export interface Messages { + [key: string]: string | ((context: (name: string, type?: string, format?: any) => string) => (string | string[])); +} + +export interface Catalog { + messages: Messages; + languageData?: LanguageData; +} + +export interface Catalogs { + [key: string]: Catalog; +} + +export interface setupI18nProps { + language?: string; + catalogs?: Catalogs; + development?: object; +} + +export class I18n { + t(strings: TemplateStringsArray, ...values: any[]): string; + + t(id: string): (strings: TemplateStringsArray, ...values: any[]) => string; + + select(config: SelectProps): string; + + select(id: string, config: SelectProps): string; + + plural(config: PluralProps): string; + + plural(id: string, config: PluralProps): string; + + selectOrdinal(config: PluralProps): string; + + selectOrdinal(id: string, config: PluralProps): string; + + constructor(); + + availableLanguages: string[]; + language: string; + messages: Messages; + languageData: LanguageData; + + load(catalogs: Catalogs): void; + + activate(language: string): void; + + use(language: string): I18n; + + _(id: string, values?: object, messageOptions?: MessageOptions): string; + + pluralForm(n: number, pluralType?: "cardinal" | "ordinal"): string; +} + +export function setupI18n(params?: setupI18nProps): I18n; + +export const i18n: I18n; diff --git a/types/lingui__core/index.d.ts b/types/lingui__core/index.d.ts new file mode 100644 index 0000000000..c0aa933bee --- /dev/null +++ b/types/lingui__core/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for @lingui/core 2.1 +// Project: https://lingui.github.io/js-lingui/ +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/lingui-typings + +export { + i18n, + setupI18n, + Catalog, + Catalogs, + MessageOptions, + LanguageData, + I18n +} from './i18n'; + +export { + date, + number +} from './formats'; + +export function i18nMark(id: string): string; diff --git a/types/lingui__core/lingui__core-tests.ts b/types/lingui__core/lingui__core-tests.ts new file mode 100644 index 0000000000..799bc5812b --- /dev/null +++ b/types/lingui__core/lingui__core-tests.ts @@ -0,0 +1,89 @@ +import { + i18n, + setupI18n, + Catalog, + Catalogs, + MessageOptions, + LanguageData, + I18n, + date, + number, + i18nMark +} from '@lingui/core'; + +const age = 12; +const templateResult: string = i18n.t`${age} years old`; +const templateIdResult: string = i18n.t('templateId')`${age} years old`; +const translateResult: string = i18n._('age', { age }, { defaults: '{age} years old' }); + +const count = 42; + +const pluralResult: string = i18n.plural({ + value: count, + 0: 'no books', + one: '# book', + other: '# books' +}); +const pluralIdResult: string = i18n.plural('pluralId', { + value: count, + 0: 'no books', + one: '# book', + other: '# books' +}); + +const selectOrdinalResult: string = i18n.selectOrdinal({ + value: count, + 0: 'Zeroth book', + one: '#st book', + two: '#nd book', + few: '#rd book', + other: '#th book' +}); +const selectOrdinalIdResult: string = i18n.selectOrdinal('selectOrdinalId', { + value: count, + 0: 'Zeroth book', + one: '#st book', + two: '#nd book', + few: '#rd book', + other: '#th book' +}); + +const gender = 'female'; +const numOfGuests = 2; +const host = 'Amy'; +const guest = 'Bob'; +const selectResult = i18n.select({ + value: gender, + female: i18n.plural({ + value: numOfGuests, + offset: 1, + 0: i18n.t`${host} does not give a party.`, + 1: i18n.t`${host} invites ${guest} to her party.`, + 2: i18n.t`${host} invites ${guest} and one other person to her party.`, + other: i18n.t`${host} invites ${guest} and # other people to her party.` + }), + male: 'male', + other: 'other' +}); + +const selectIdResult = i18n.select('selectId', { + value: gender, + female: 'female', + male: 'male', + other: 'other' +}); + +const catalog: Catalog = { + messages: { + age(a) { + return [a('age'), 'años de edad']; + } + } +}; +const catalogs: Catalogs = { es: catalog }; +const setupResult: I18n = setupI18n({ catalogs, language: 'es' }); + +const formattedDate: string = date('en', { timeZone: 'UTC' })(new Date()); +const formattedNumber: string = number('en', { style: 'currency', currency: 'EUR' })(1234.56); + +const mark: string = i18nMark('mark'); diff --git a/types/lingui__core/select.d.ts b/types/lingui__core/select.d.ts new file mode 100644 index 0000000000..6a2eb51db9 --- /dev/null +++ b/types/lingui__core/select.d.ts @@ -0,0 +1,20 @@ +export interface PluralForms { + zero?: string; + one?: string; + two?: string; + few?: string; + many?: string; + other: string; + [exact: number]: string; +} + +export interface PluralProps extends PluralForms { + value: number; + offset?: number; +} + +export interface SelectProps { + value: string; + other: string; + [selectForm: string]: string; +} diff --git a/types/lingui__core/tsconfig.json b/types/lingui__core/tsconfig.json new file mode 100644 index 0000000000..e01d974c46 --- /dev/null +++ b/types/lingui__core/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@lingui/core": [ + "lingui__core" + ] + } + }, + "files": [ + "index.d.ts", + "lingui__core-tests.ts" + ] +} diff --git a/types/lingui__core/tslint.json b/types/lingui__core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lingui__core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lingui__react/I18nProvider.d.ts b/types/lingui__react/I18nProvider.d.ts new file mode 100644 index 0000000000..9eb0158fac --- /dev/null +++ b/types/lingui__react/I18nProvider.d.ts @@ -0,0 +1,14 @@ +import { Component, ReactNode } from 'react'; +import { I18n, Catalogs } from '@lingui/core'; + +// tslint:disable-next-line:interface-name +export interface I18nProviderProps { + children?: ReactNode; + language: string; + catalogs?: Catalogs; + i18n?: I18n; + + defaultRender?: ReactNode; +} + +export default class I18nProvider extends Component { } diff --git a/types/lingui__react/Render.d.ts b/types/lingui__react/Render.d.ts new file mode 100644 index 0000000000..d9ccf003c0 --- /dev/null +++ b/types/lingui__react/Render.d.ts @@ -0,0 +1,6 @@ +import { ReactNode } from 'react'; + +export interface RenderProps { + render?: ReactNode; + className?: string; +} diff --git a/types/lingui__react/Select.d.ts b/types/lingui__react/Select.d.ts new file mode 100644 index 0000000000..044d4bf473 --- /dev/null +++ b/types/lingui__react/Select.d.ts @@ -0,0 +1,26 @@ +import { Component, ReactNode } from 'react'; +import { RenderProps } from './Render'; + +export interface PluralPropsWithoutI18n extends RenderProps { + id?: string; + value: number | string; + offset?: number | string; + zero?: ReactNode; + one?: ReactNode; + two?: ReactNode; + few?: ReactNode; + many?: ReactNode; + other: ReactNode; + [exact: string]: ReactNode; +} + +export interface SelectPropsWithoutI18n extends RenderProps { + id?: string; + value: string; + other: ReactNode; + [exact: string]: ReactNode; +} + +export class Select extends Component { } +export class Plural extends Component { } +export class SelectOrdinal extends Component { } diff --git a/types/lingui__react/Trans.d.ts b/types/lingui__react/Trans.d.ts new file mode 100644 index 0000000000..c1834b770d --- /dev/null +++ b/types/lingui__react/Trans.d.ts @@ -0,0 +1,13 @@ +import { Component, ReactElement, ReactNode } from 'react'; +import { RenderProps } from './Render'; + +export interface TransPropsWithoutI18n extends RenderProps { + id?: string; + defaults?: string; + values?: object; + formats?: object; + components?: ReadonlyArray>; + children?: ReactNode; +} + +export default class Trans extends Component { } diff --git a/types/lingui__react/createFormat.d.ts b/types/lingui__react/createFormat.d.ts new file mode 100644 index 0000000000..49bebb079e --- /dev/null +++ b/types/lingui__react/createFormat.d.ts @@ -0,0 +1,6 @@ +import { RenderProps } from './Render'; + +export interface FormatPropsWithoutI18n extends RenderProps { + value: V; + format?: FormatOptions; +} diff --git a/types/lingui__react/index.d.ts b/types/lingui__react/index.d.ts new file mode 100644 index 0000000000..1fbe1e5c05 --- /dev/null +++ b/types/lingui__react/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for @lingui/react 2.1 +// Project: https://lingui.github.io/js-lingui/ +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/lingui-typings +// TypeScript Version: 2.8 + +import { ComponentClass } from 'react'; + +import { FormatPropsWithoutI18n } from './createFormat'; + +export { default as withI18n, withI18nProps } from './withI18n'; + +export { default as I18nProvider } from './I18nProvider'; +export { default as Trans } from './Trans'; +export { Plural, Select, SelectOrdinal } from './Select'; + +export const DateFormat: ComponentClass>; +export const NumberFormat: ComponentClass>; + +export function i18nMark(id: string): string; diff --git a/types/lingui__react/lingui__react-tests.tsx b/types/lingui__react/lingui__react-tests.tsx new file mode 100644 index 0000000000..3fc8cebebb --- /dev/null +++ b/types/lingui__react/lingui__react-tests.tsx @@ -0,0 +1,102 @@ +import * as React from 'react'; +import { Catalog, Catalogs, I18n } from '@lingui/core'; +import { + withI18n, + I18nProvider, + Trans, + Plural, + Select, + SelectOrdinal, + DateFormat, + NumberFormat, + i18nMark +} from '@lingui/react'; + +const catalog: Catalog = { + messages: { + ageId(a) { + return [a('age'), 'años de edad']; + } + } +}; +const catalogs: Catalogs = { es: catalog }; + +interface LocalizeAttributeBaseProps { + i18n: I18n; + age: number; +} + +const LocalizeAttributeBase = (props: LocalizeAttributeBaseProps) => { + const { i18n, age } = props; + return ( + Attributes + ); +}; + +const LocalizeAttribute = withI18n()(LocalizeAttributeBase); +const LocalizeOptionAttribute = withI18n({ update: true, withRef: true, withHash: true })(LocalizeAttributeBase); + +const App = () => { + const name = 'Ken'; + const numBooks = 58; + const gender = 'male'; + const price = 21.35; + const lastLogin = new Date(); + return ( + + + + Name {name} in Trans. + Name {name} in Trans with id. + {name} has no books} + one={{name} has # book} + other={{name} has # books} + _999999="Just a string" + /> + {name} has no books} + one={{name} has # book} + other={{name} has # books} + _999999="Just a string" + /> + {name} and his friends} + female={{name} and her friends} + other={{name} and their friends} + _999999="Just a string" + /> + No books from {name}} + one={#st book from {name}} + two={#nd book from {name}} + other={#th book from {name}} + _999999="Just a string" + /> + No books from {name}} + one={#st book from {name}} + two={#nd book from {name}} + other={#th book from {name}} + _999999="Just a string" + /> + Last login on . + + Price of book: . + + + ); +}; + +const mark: string = i18nMark('mark'); diff --git a/types/lingui__react/tsconfig.json b/types/lingui__react/tsconfig.json new file mode 100644 index 0000000000..3b53ee659c --- /dev/null +++ b/types/lingui__react/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@lingui/core": [ + "lingui__core" + ], + "@lingui/react": [ + "lingui__react" + ] + } + }, + "files": [ + "index.d.ts", + "lingui__react-tests.tsx" + ] +} diff --git a/types/lingui__react/tslint.json b/types/lingui__react/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lingui__react/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lingui__react/withI18n.d.ts b/types/lingui__react/withI18n.d.ts new file mode 100644 index 0000000000..00595ee2d5 --- /dev/null +++ b/types/lingui__react/withI18n.d.ts @@ -0,0 +1,18 @@ +import { ComponentClass, StatelessComponent } from 'react'; +import { I18n } from '@lingui/core'; +import { withI18nProps } from './withI18n'; + +export type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export interface withI18nOptions { + update?: boolean; + withRef?: boolean; + withHash?: boolean; +} + +export interface withI18nProps { + i18n: I18n; +} + +export default function withI18n(options?: withI18nOptions): +

(WrappedComponent: ComponentConstructor

) => ComponentClass>>; diff --git a/types/lodash/fp.d.ts b/types/lodash/fp.d.ts index da68ea250e..c799bd734b 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -4760,6 +4760,6 @@ declare namespace _ { zipObjectDeep: LodashZipObjectDeep; zipWith: LodashZipWith; __: lodash.__; - placehodler: lodash.__; + placeholder: lodash.__; } } diff --git a/types/lodash/scripts/generate-fp.ts b/types/lodash/scripts/generate-fp.ts index 9a03fef544..817b485cf2 100644 --- a/types/lodash/scripts/generate-fp.ts +++ b/types/lodash/scripts/generate-fp.ts @@ -118,7 +118,7 @@ async function main() { " interface LoDashFp {", ...interfaceGroups.map(g => ` ${g.functionName}: ${g.interfaces[0].name};`), " __: lodash.__;", - " placehodler: lodash.__;", + " placeholder: lodash.__;", " }", "}", "", diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index d0f50ae783..203eaa93b6 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -67,7 +67,7 @@ export declare class Element { getText(): string; - getChildText(name: string, xmlns: any): string; + getChildText(name: string, xmlns?: any): string; /** * Return all direct descendents that are Elements. diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 1e617ad27d..522b7673c8 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -2,6 +2,11 @@ import * as ltx from 'ltx'; ltx.parse(''); +const getChildTextElement = ltx.parse('body text') as ltx.Element; +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error("body does not match"); +} + const p = new ltx.Parser(); p.on('tree', (ignored: any) => {}); diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index d90ba90b13..94623c5abb 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -208,6 +208,7 @@ declare module 'luxon' { toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; toObject(options?: { includeConfig?: boolean }): DateObject; + toMillis(): number; toRFC2822(): string; toSQL(options?: Object): string; toSQLDate(): string; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index ce9d09ac8f..4396e8d7a2 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -54,6 +54,8 @@ DateTime.utc(); DateTime.local().toUTC(); DateTime.utc().toLocal(); +DateTime.fromMillis(1527780819458).toMillis(); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index a4dc048cc8..034c0cca18 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Marked 0.3 +// Type definitions for Marked 0.4 // Project: https://github.com/chjj/marked // Definitions by: William Orr // BendingBender +// CrossR // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace marked; @@ -202,21 +203,9 @@ declare namespace marked { interface MarkedOptions { /** - * Type: object Default: new Renderer() - * - * An object containing functions to render tokens to HTML. + * A prefix URL for any relative link. */ - renderer?: Renderer; - - /** - * Enable GitHub flavored markdown. - */ - gfm?: boolean; - - /** - * Enable GFM tables. This option requires the gfm option to be true. - */ - tables?: boolean; + baseUrl?: string; /** * Enable GFM line breaks. This option requires the gfm option to be true. @@ -224,34 +213,19 @@ declare namespace marked { breaks?: boolean; /** - * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + * Enable GitHub flavored markdown. */ - pedantic?: boolean; + gfm?: boolean; /** - * Sanitize the output. Ignore any HTML that has been input. + * Include an id attribute when emitting headings. */ - sanitize?: boolean; + headerIds?: boolean; /** - * Optionally sanitize found HTML with a sanitizer function. + * Set the prefix for header tag ids. */ - sanitizer?(html: string): string; - - /** - * Mangle autolinks (). - */ - mangle?: boolean; - - /** - * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. - */ - smartLists?: boolean; - - /** - * Shows an HTML error message when rendering fails. - */ - silent?: boolean; + headerPrefix?: string; /** * A function to highlight code blocks. The function takes three arguments: code, lang, and callback. @@ -263,15 +237,52 @@ declare namespace marked { */ langPrefix?: string; + /** + * Mangle autolinks (). + */ + mangle?: boolean; + + /** + * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + */ + pedantic?: boolean; + + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: Renderer; + + /** + * Sanitize the output. Ignore any HTML that has been input. + */ + sanitize?: boolean; + + /** + * Optionally sanitize found HTML with a sanitizer function. + */ + sanitizer?(html: string): string; + + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean; + + /** + * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. + */ + smartLists?: boolean; + /** * Use "smart" typograhic punctuation for things like quotes and dashes. */ smartypants?: boolean; /** - * Set the prefix for header tag ids. + * Enable GFM tables. This option requires the gfm option to be true. */ - headerPrefix?: string; + tables?: boolean; /** * Generate closing slash for self-closing tags (
instead of
) diff --git a/types/marked/marked-tests.ts b/types/marked/marked-tests.ts index 9499de3a56..e1cb63042c 100644 --- a/types/marked/marked-tests.ts +++ b/types/marked/marked-tests.ts @@ -1,6 +1,7 @@ import * as marked from 'marked'; const options: marked.MarkedOptions = { + baseUrl: '', gfm: true, tables: true, breaks: false, @@ -16,23 +17,24 @@ const options: marked.MarkedOptions = { renderer: new marked.Renderer() }; -function callback() { - console.log('callback called'); +function callback(err: string, markdown: string) { + console.log("Callback called!"); + return markdown; } const myOldMarked: typeof marked = marked.setOptions(options); -console.log(marked('i am using __markdown__.')); -console.log(marked('i am using __markdown__.', options)); -console.log(marked('i am using __markdown__.', callback)); -console.log(marked('i am using __markdown__.', options, callback)); +console.log(marked('1) I am using __markdown__.')); +console.log(marked('2) I am using __markdown__.', options)); +console.log(marked('3) I am using __markdown__.', callback)); +console.log(marked('4) I am using __markdown__.', options, callback)); -console.log(marked.parse('i am using __markdown__.')); -console.log(marked.parse('i am using __markdown__.', options)); -console.log(marked.parse('i am using __markdown__.', callback)); -console.log(marked.parse('i am using __markdown__.', options, callback)); +console.log(marked.parse('5) I am using __markdown__.')); +console.log(marked.parse('6) I am using __markdown__.', options)); +console.log(marked.parse('7) I am using __markdown__.', callback)); +console.log(marked.parse('8) I am using __markdown__.', options, callback)); -const text = 'something'; +const text = 'Something'; const tokens: marked.TokensList = marked.lexer(text, options); console.log(marked.parser(tokens)); diff --git a/types/materialize-css/test/inputfields.test.ts b/types/materialize-css/test/inputfields.test.ts index ecde571537..15ea61c1ee 100644 --- a/types/materialize-css/test/inputfields.test.ts +++ b/types/materialize-css/test/inputfields.test.ts @@ -1,6 +1,6 @@ import * as materialize from "materialize-css"; -const elem = document.querySelector('.whatever')!; +const elem = document.querySelector('.whatever') as HTMLElement; M.textareaAutoResize(elem); M.textareaAutoResize($(elem)); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index cdecc3e1b4..eda68ade10 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,2252 +1,4546 @@ -// Type definitions for mathjs 3.21 +// Type definitions for mathjs 4.4 // Project: http://mathjs.org/ // Definitions by: Ilya Shestakov , -// Andy Patterson +// Andy Patterson , +// Brad Besserman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 -import { Decimal } from 'decimal.js'; +import { Decimal } from "decimal.js"; -declare const math: math.MathJsStatic; // tslint:disable-line strict-export-declare-modifiers -export as namespace math; // tslint:disable-line strict-export-declare-modifiers -export = math; // tslint:disable-line strict-export-declare-modifiers +declare const math: math.MathJsStatic; +export as namespace math; +export = math; -declare namespace math { // tslint:disable-line strict-export-declare-modifiers - type MathArray = number[]|number[][]; - type MathType = number|BigNumber|Fraction|Complex|Unit|MathArray|Matrix; - type MathExpression = string|string[]|MathArray|Matrix; +declare namespace math { + type MathArray = number[] | number[][]; + type MathType = + | number + | BigNumber + | Fraction + | Complex + | Unit + | MathArray + | Matrix; + type MathExpression = string | string[] | MathArray | Matrix; - interface MathJsStatic { - e: number; - pi: number; - i: number; - Infinity: number; - LN2: number; - LN10: number; - LOG2E: number; - LOG10E: number; - NaN: number; - null: number; - phi: number; - SQRT1_2: number; - SQRT2: number; - tau: number; + interface MathJsStatic { + e: number; + pi: number; + i: number; + Infinity: number; + LN2: number; + LN10: number; + LOG2E: number; + LOG10E: number; + NaN: number; + null: number; + phi: number; + SQRT1_2: number; + SQRT2: number; + tau: number; - uninitialized: any; - version: string; + uninitialized: any; + version: string; - expression: MathNode; + expression: MathNode; + json: MathJsJson; - config: (options: any) => void; + /************************************************************************* + * Core functions + ************************************************************************/ - /** - * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. - * @param L A N x N matrix or array (L) - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - lsolve(L: Matrix|MathArray, b: Matrix|MathArray): Matrix|MathArray; + /** + * Set configuration options for math.js, and get current options. Will + * emit a ‘config’ event, with arguments (curr, prev, changes). + * @param options Available options: {number} epsilon Minimum relative + * difference between two compared values, used by all comparison + * functions. {string} matrix A string ‘Matrix’ (default) or ‘Array’. + * {string} number A string ‘number’ (default), ‘BigNumber’, or + * ‘Fraction’ {number} precision The number of significant digits for + * BigNumbers. Not applicable for Numbers. {string} parenthesis How to + * display parentheses in LaTeX and string output. {string} randomSeed + * Random seed for seeded pseudo random number generator. Set to null to + * randomly seed. + * @returns Returns the current configuration + */ + config: (options: ConfigOptions) => ConfigOptions; + /** + * Create a typed-function which checks the types of the arguments and + * can match them against multiple provided signatures. The + * typed-function automatically converts inputs in order to find a + * matching signature. Typed functions throw informative errors in case + * of wrong input arguments. + * @param name Optional name for the typed-function + * @param signatures Object with one or multiple function signatures + * @returns The created typed-function. + */ + typed: (name: string, signatures: Record any>) => ((...args: any[]) => any); - /** - * Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in two matrices (L, U) - * and a row permutation vector p where A[p,:] = L * U - * @param A A two dimensional matrix or array for which to get the LUP decomposition. - * @returns The lower triangular matrix, the upper triangular matrix and the permutation matrix. - */ - lup(A?: Matrix|MathArray): MathArray; + /************************************************************************* + * Construction functions + ************************************************************************/ - /** - * Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector. - * @param A Invertible Matrix or the Matrix LU decomposition - * @param b Column Vector - * @returns Column vector with the solution to the linear system A * x = b - */ - lusolve(A: Matrix|MathArray|number, b: Matrix|MathArray): Matrix|MathArray; + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to + * BigNumber. + * @param x Value for the big number, 0 by default. + * @returns The created bignumber + */ + bignumber( + x?: + | number + | string + | Fraction + | BigNumber + | MathArray + | Matrix + | boolean + | Fraction + | null + ): BigNumber; - /** - * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix A is decomposed in - * two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U - * @param A A two dimensional sparse matrix for which to get the LU decomposition. - * @param order The Symbolic Ordering and Analysis order: 0 - Natural ordering, no permutation vector q is - * returned 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A' 2 - Symbolic - * ordering and analysis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. - * This is appropriate for LU factorization of non-symmetric matrices. 3 - Symbolic ordering and analysis is performed - * on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. A dense row is a row with - * more than 10*sqr(columns) entries. - * @param threshold Partial pivoting threshold (1 for partial pivoting) - * @returns The lower triangular matrix, the upper triangular matrix and the permutation vectors. - */ - slu(A: Matrix, order: number, threshold: number): any; + /** + * Create a boolean or convert a string or number to a boolean. In case + * of a number, true is returned for non-zero numbers, and false in case + * of zero. Strings can be 'true' or 'false', or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + * @param x A value of any type + * @returns The boolean value + */ + boolean( + x: string | number | boolean | MathArray | Matrix | null + ): boolean | MathArray | Matrix; - /** - * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. U * x = b - * @param U A N x N matrix or array (U) - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - usolve(U: Matrix|MathArray, b: Matrix|MathArray): Matrix|MathArray; + /** + * Wrap any value in a chain, allowing to perform chained operations on + * the value. All methods available in the math.js library can be called + * upon the chain, and then will be evaluated with the value itself as + * first argument. The chain can be closed by executing chain.done(), + * which returns the final value. The chain has a number of special + * functions: done() Finalize the chain and return the chain's value. + * valueOf() The same as done() toString() Executes math.format() onto + * the chain's value, returning a string representation of the value. + * @param value A value of any type on which to start a chained + * operation. + * @returns The created chain + */ + chain(value?: any): MathJsChain; - /** - * Calculate the absolute value of a number. For matrices, the function is evaluated element wise. - * @param x A number or matrix for which to get the absolute value - * @returns Absolute value of x - */ - abs(x: number): number; - abs(x: BigNumber): BigNumber; - abs(x: Fraction): Fraction; - abs(x: Complex): Complex; - abs(x: MathArray): MathArray; - abs(x: Matrix): Matrix; - abs(x: Unit): Unit; + /** + * Create a complex value or convert a value to a complex value. + * @param args Arguments specifying the real and imaginary part of the + * complex number + * @returns Returns a complex value + */ + complex(arg?: Complex | string | PolarCoordinates): Complex; + complex(arg?: MathArray | Matrix): MathArray | Matrix; + /** + * @param re Argument specifying the real part of the complex number + * @param im Argument specifying the imaginary part of the complex + * number + * @returns Returns a complex value + */ + complex(re: number, im: number): Complex; - /** - * Add two values, x + y. For matrices, the function is evaluated element wise. - * @param x First value to add - * @param y Second value to add - * @returns Sum of x and y - */ - add(x: MathType, y: MathType): MathType; + /** + * Create a user-defined unit and register it with the Unit type. + * @param name The name of the new unit. Must be unique. Example: ‘knot’ + * @param definition Definition of the unit in terms of existing units. + * For example, ‘0.514444444 m / s’. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + * @returns The new unit + */ + createUnit( + name: string, + definition?: string | UnitDefinition, + options?: CreateUnitOptions + ): Unit; + /** + * Create a user-defined unit and register it with the Unit type. + * @param units Definition of the unit + * @param options + * @returns The new unit + */ + createUnit( + units: Record, + options?: CreateUnitOptions + ): Unit; - /** - * Calculate the cubic root of a value. For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the cubic root. - * @param allRoots Optional, false by default. Only applicable when x is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned. - * @returns Returns the cubic root of x - */ - cbrt(x: number, allRoots?: boolean): number; - cbrt(x: BigNumber, allRoots?: boolean): BigNumber; - cbrt(x: Fraction, allRoots?: boolean): Fraction; - cbrt(x: Complex, allRoots?: boolean): Complex; - cbrt(x: MathArray, allRoots?: boolean): MathArray; - cbrt(x: Matrix, allRoots?: boolean): Matrix; - cbrt(x: Unit, allRoots?: boolean): Unit; + /** + * Create a fraction convert a value to a fraction. + * @param args Arguments specifying the numerator and denominator of the + * fraction + * @returns Returns a fraction + */ + fraction( + args: Fraction | MathArray | Matrix + ): Fraction | MathArray | Matrix; + /** + * @param numerator Argument specifying the numerator of the fraction + * @param denominator Argument specifying the denominator of the + * fraction + * @returns Returns a fraction + */ + fraction( + numerator: number | string | MathArray | Matrix, + denominator?: number | string | MathArray | Matrix + ): Fraction | MathArray | Matrix; - /** - * Round a value towards plus infinity If x is complex, both real and imaginary part are rounded towards plus infinity. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @returns Rounded value - */ - ceil(x: number): number; - ceil(x: BigNumber): BigNumber; - ceil(x: Fraction): Fraction; - ceil(x: Complex): Complex; - ceil(x: MathArray): MathArray; - ceil(x: Matrix): Matrix; - ceil(x: Unit): Unit; + /** + * Create an index. An Index can store ranges having start, step, and + * end for multiple dimensions. Matrix.get, Matrix.set, and math.subset + * accept an Index as input. + * @param ranges Zero or more ranges or numbers. + * @returns Returns the created index + */ + index(...ranges: any[]): Index; - /** - * Compute the cube of a value, x * x * x. For matrices, the function is evaluated element wise. - * @param x Number for which to calculate the cube - * @returns Cube of x - */ - cube(x: number): number; - cube(x: BigNumber): BigNumber; - cube(x: Fraction): Fraction; - cube(x: Complex): Complex; - cube(x: MathArray): MathArray; - cube(x: Matrix): Matrix; - cube(x: Unit): Unit; + /** + * Create a Matrix. The function creates a new math.type.Matrix object + * from an Array. A Matrix has utility functions to manipulate the data + * in the matrix, like getting the size and getting or setting values in + * the matrix. Supported storage formats are 'dense' and 'sparse'. + * @param format The Matrix storage format + * @returns The created Matrix + */ + matrix(format?: "sparse" | "dense"): Matrix; + /** + * @param data A multi dimensional array + * @param format The Matrix storage format + * @param dataType The Matrix data type + * @returns The created Matrix + */ + matrix( + data: MathArray | Matrix, + format?: "sparse" | "dense", + dataType?: string + ): Matrix; - /** - * Divide two values, x / y. To divide matrices, x is multiplied with the inverse of y: x * inv(y). - * @param x Numerator - * @param y Denominator - * @returns Quotient, x / y - */ - divide(x: Unit, y: Unit): Unit; - divide(x: number, y: number): number; - divide(x: MathType, y: MathType): MathType; + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * @param value Value to be converted + * @returns The created number + */ + number( + value?: + | string + | number + | BigNumber + | Fraction + | boolean + | MathArray + | Matrix + | Unit + | null + ): number | MathArray | Matrix; + /** + * @param value Value to be converted + * @param valuelessUnit A valueless unit, used to convert a unit to a + * number + * @returns The created number + */ + number(unit: Unit, valuelessUnit: Unit | string): number; - /** - * Divide two matrices element wise. The function accepts both matrices and scalar values. - * @param x Numerator - * @param y Denominator - * @returns Quotient, x ./ y - */ - dotDivide(x: MathType, y: MathType): MathType; + /** + * Create a Sparse Matrix. The function creates a new math.type.Matrix + * object from an Array. A Matrix has utility functions to manipulate + * the data in the matrix, like getting the size and getting or setting + * values in the matrix. + * @param data A two dimensional array + * @param dataType Sparse Matrix data type + * @returns The created matrix + */ + sparse(data?: MathArray | Matrix, dataType?: string): Matrix; - /** - * Multiply two matrices element wise. The function accepts both matrices and scalar values. - * @param x Left hand value - * @param y Right hand value - * @returns Multiplication of x and y - */ - dotMultiply(x: MathType, y: MathType): MathType; + /** + * Split a unit in an array of units whose sum is equal to the original + * unit. + * @param unit A unit to be split + * @param parts An array of strings or valueless units + * @returns An array of units + */ + splitUnit(unit: Unit, parts: Unit[]): Unit[]; - /** - * Calculates the power of x to y element wise. - * @param x The base - * @param y The exponent - * @returns The value of x to the power y - */ - dotPow(x: MathType, y: MathType): MathType; + /** + * Create a string or convert any object into a string. Elements of + * Arrays and Matrices are processed element wise. + * @param value A value to convert to a string + * @returns The created string + */ + string( + value: MathType | null + ): string | MathArray | Matrix; - /** - * Calculate the exponent of a value. For matrices, the function is evaluated element wise. - * @param x A number or matrix to exponentiate - * #returns Exponent of x - */ - exp(x: number): number; - exp(x: BigNumber): BigNumber ; - exp(x: Complex): Complex ; - exp(x: MathArray): MathArray ; - exp(x: Matrix): Matrix; + /** + * Create a unit. Depending on the passed arguments, the function will + * create and return a new math.type.Unit object. When a matrix is + * provided, all elements will be converted to units. + * @param unit The unit to be created + * @returns The created unit + */ + unit(unit: string): Unit; + /** + * @param value The value of the unit to be created + * @param unit The unit to be created + * @returns The created unit + */ + unit(value: number | MathArray | Matrix, unit: string): Unit; - /** - * Round a value towards zero. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @returns Rounded value - */ - fix(x: number): number; - fix(x: BigNumber): BigNumber ; - fix(x: Fraction): Fraction ; - fix(x: Complex): Complex ; - fix(x: MathArray): MathArray ; - fix(x: Matrix): Matrix; + /************************************************************************* + * Expression functions + ************************************************************************/ - /** - * Round a value towards minus infinity. For matrices, the function is evaluated element wise. - * @param Number to be rounded - * @returns Rounded value - */ - floor(x: number): number; - floor(x: BigNumber): BigNumber ; - floor(x: Fraction): Fraction ; - floor(x: Complex): Complex ; - floor(x: MathArray): MathArray ; - floor(x: Matrix): Matrix; + /** + * Parse and compile an expression. Returns a an object with a function + * eval([scope]) to evaluate the compiled expression. + * @param expr The expression to be compiled + * @returns An object with the compiled expression + */ + compile(expr: MathExpression): EvalFunction; + /** + * @param exprs The expressions to be compiled + * @returns An array of objects with the compiled expressions + */ + compile(exprs: MathExpression[]): EvalFunction[]; - /** - * Calculate the greatest common divisor for two or more values or arrays. For matrices, the function is evaluated element wise. - */ - gcd(...args: number[]): number; - gcd(...args: BigNumber[]): BigNumber ; - gcd(...args: Fraction[]): Fraction ; - gcd(...args: MathArray[]): MathArray ; - gcd(...args: Matrix[]): Matrix; + /** + * Evaluate an expression. + * @param expr The expression to be evaluated + * @param scope Scope to read/write variables + * @returns The result of the expression + */ + eval( + expr: MathExpression | MathExpression[] | Matrix, + scope?: object + ): any; - /** - * Calculate the hypotenusa of a list with values. The hypotenusa is defined as: - * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) - * For matrix input, the hypotenusa is calculated for all values in the matrix. - */ - hypot(...args: number[]): number; - hypot(...args: BigNumber[]): BigNumber; + /** + * Retrieve help on a function or data type. Help files are retrieved + * from the documentation in math.expression.docs. + * @param search A function or function name for which to get help + * @returns A help object + */ + help(search: () => any): Help; + + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.eval(); + * @param expr Expression to be parsed + * @param options Available options: nodes - a set of custome nodes + * @returns A node + */ + parse(expr: MathExpression, options?: any): MathNode; + /** + * @param exprs Expressions to be parsed + * @param options Available options: nodes - a set of custome nodes + * @returns An arry of nodes + */ + parse(exprs: MathExpression[], options?: any): MathNode[]; + + /** + * Create a parser. The function creates a new math.expression.Parser + * object. + * @returns A Parser object + */ + parser(): Parser; + + /************************************************************************* + * Algebra functions + ************************************************************************/ + /** + * @param expr The expression to differentiate + * @param variable The variable over which to differentiate + * @param options There is one option available, simplify, which is true + * by default. When false, output will not be simplified. + * @returns The derivative of expr + */ + derivative( + expr: MathNode | string, + variable: MathNode | string, + options?: {simplify: boolean} + ): MathNode; + + /** + * Solves the linear equation system by forwards substitution. Matrix + * must be a lower triangular matrix. + * @param L A N x N matrix or array (L) + * @param b A column vector with the b values + * @returns A column vector with the linear system solution (x) + */ + lsolve( + L: Matrix | MathArray, + b: Matrix | MathArray + ): Matrix | MathArray; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix A + * is decomposed in two matrices (L, U) and a row permutation vector p + * where A[p,:] = L * U + * @param A A two dimensional matrix or array for which to get the LUP + * decomposition. + * @returns The lower triangular matrix, the upper triangular matrix and + * the permutation matrix. + */ + lup( + A?: Matrix | MathArray + ): { L: MathArray | Matrix; U: MathArray | Matrix; P: number[] }; + + /** + * Solves the linear system A * x = b where A is an [n x n] matrix and b + * is a [n] column vector. + * @param A Invertible Matrix or the Matrix LU decomposition + * @param b Column Vector + * @param order The Symbolic Ordering and Analysis order, see slu for + * details. Matrix must be a SparseMatrix + * @param threshold Partial pivoting threshold (1 for partial pivoting), + * see slu for details. Matrix must be a SparseMatrix. + * @returns Column vector with the solution to the linear system A * x = + * b + */ + lusolve( + A: Matrix | MathArray | number, + b: Matrix | MathArray, + order?: number, + threshold?: number + ): Matrix | MathArray; + + /** + * Calculate the Matrix QR decomposition. Matrix A is decomposed in two + * matrices (Q, R) where Q is an orthogonal matrix and R is an upper + * triangular matrix. + * @param A A two dimensional matrix or array for which to get the QR + * decomposition. + * @returns Q: the orthogonal matrix and R: the upper triangular matrix + */ + qr( + A: Matrix | MathArray + ): { Q: MathArray | Matrix; R: MathArray | Matrix }; + + /** + * Transform a rationalizable expression in a rational fraction. If + * rational fraction is one variable polynomial then converts the + * numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * @param expr The expression to check if is a polynomial expression + * @param optional scope of expression or true for already evaluated + * rational expression at input + * @param detailed optional True if return an object, false if return + * expression node (default) + * @returns The rational polynomial of expr + */ + rationalize(expr: MathNode | string, optional?: object | boolean, detailed?: true): { expression: MathNode | string, variables: string[], coefficients: MathType[] }; + rationalize(expr: MathNode | string, optional?: object | boolean, detailed?: false): MathNode; + + /** + * Simplify an expression tree. + * @param expr The expression to be simplified + * @param rules A list of rules are applied to an expression, repeating + * over the list until no further changes are made. It’s possible to + * pass a custom set of rules to the function as second argument. A rule + * can be specified as an object, string, or function. + * @param scope Scope to variables + * @returns Returns the simplified form of expr + */ + simplify( + expr: MathNode | string, + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, + scope?: object + ): MathNode; + + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. + * Sparse Matrix A is decomposed in two matrices (L, U) and two + * permutation vectors (pinv, q) where P * A * Q = L * U + * @param A A two dimensional sparse matrix for which to get the LU + * decomposition. + * @param order The Symbolic Ordering and Analysis order: 0 - Natural + * ordering, no permutation vector q is returned 1 - Matrix must be + * square, symbolic ordering and analisis is performed on M = A + A' 2 - + * Symbolic ordering and analysis is performed on M = A' * A. Dense + * columns from A' are dropped, A recreated from A'. This is appropriate + * for LU factorization of non-symmetric matrices. 3 - Symbolic ordering + * and analysis is performed on M = A' * A. This is best used for LU + * factorization is matrix M has no dense rows. A dense row is a row + * with more than 10*sqr(columns) entries. + * @param threshold Partial pivoting threshold (1 for partial pivoting) + * @returns The lower triangular matrix, the upper triangular matrix and + * the permutation vectors. + */ + slu(A: Matrix, order: number, threshold: number): object; + + /** + * Solves the linear equation system by backward substitution. Matrix + * must be an upper triangular matrix. U * x = b + * @param U A N x N matrix or array (U) + * @param b A column vector with the b values + * @returns A column vector with the linear system solution (x) + */ + usolve( + U: Matrix | MathArray, + b: Matrix | MathArray + ): Matrix | MathArray; + + /************************************************************************* + * Arithmetic functions + ************************************************************************/ + + /** + * Calculate the absolute value of a number. For matrices, the function + * is evaluated element wise. + * @param x A number or matrix for which to get the absolute value + * @returns Absolute value of x + */ + abs(x: number): number; + abs(x: BigNumber): BigNumber; + abs(x: Fraction): Fraction; + abs(x: Complex): Complex; + abs(x: MathArray): MathArray; + abs(x: Matrix): Matrix; + abs(x: Unit): Unit; + + /** + * Add two values, x + y. For matrices, the function is evaluated + * element wise. + * @param x First value to add + * @param y Second value to add + * @returns Sum of x and y + */ + add(x: MathType, y: MathType): MathType; + + /** + * Calculate the cubic root of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the cubic root. + * @param allRoots Optional, false by default. Only applicable when x is + * a number or complex number. If true, all complex roots are returned, + * if false (default) the principal root is returned. + * @returns Returns the cubic root of x + */ + cbrt(x: number, allRoots?: boolean): number; + cbrt(x: BigNumber, allRoots?: boolean): BigNumber; + cbrt(x: Fraction, allRoots?: boolean): Fraction; + cbrt(x: Complex, allRoots?: boolean): Complex; + cbrt(x: MathArray, allRoots?: boolean): MathArray; + cbrt(x: Matrix, allRoots?: boolean): Matrix; + cbrt(x: Unit, allRoots?: boolean): Unit; + + /** + * Round a value towards plus infinity If x is complex, both real and + * imaginary part are rounded towards plus infinity. For matrices, the + * function is evaluated element wise. + * @param x Number to be rounded + * @returns Rounded value + */ + ceil(x: number): number; + ceil(x: BigNumber): BigNumber; + ceil(x: Fraction): Fraction; + ceil(x: Complex): Complex; + ceil(x: MathArray): MathArray; + ceil(x: Matrix): Matrix; + ceil(x: Unit): Unit; + + /** + * Compute the cube of a value, x * x * x. For matrices, the function is + * evaluated element wise. + * @param x Number for which to calculate the cube + * @returns Cube of x + */ + cube(x: number): number; + cube(x: BigNumber): BigNumber; + cube(x: Fraction): Fraction; + cube(x: Complex): Complex; + cube(x: MathArray): MathArray; + cube(x: Matrix): Matrix; + cube(x: Unit): Unit; + + /** + * Divide two values, x / y. To divide matrices, x is multiplied with + * the inverse of y: x * inv(y). + * @param x Numerator + * @param y Denominator + * @returns Quotient, x / y + */ + divide(x: Unit, y: Unit): Unit; + divide(x: number, y: number): number; + divide(x: MathType, y: MathType): MathType; + + /** + * Divide two matrices element wise. The function accepts both matrices + * and scalar values. + * @param x Numerator + * @param y Denominator + * @returns Quotient, x ./ y + */ + dotDivide(x: MathType, y: MathType): MathType; + + /** + * Multiply two matrices element wise. The function accepts both + * matrices and scalar values. + * @param x Left hand value + * @param y Right hand value + * @returns Multiplication of x and y + */ + dotMultiply(x: MathType, y: MathType): MathType; + + /** + * Calculates the power of x to y element wise. + * @param x The base + * @param y The exponent + * @returns The value of x to the power y + */ + dotPow(x: MathType, y: MathType): MathType; + + /** + * Calculate the exponent of a value. For matrices, the function is + * evaluated element wise. + * @param x A number or matrix to exponentiate + * @returns Exponent of x + */ + exp(x: number): number; + exp(x: BigNumber): BigNumber; + exp(x: Complex): Complex; + exp(x: MathArray): MathArray; + exp(x: Matrix): Matrix; + + /** + * Calculate the value of subtracting 1 from the exponential value. For + * matrices, the function is evaluated element wise. + * @param x A number or matrix to apply expm1 + * @returns Exponent of x + */ + expm1(x: number): number; + expm1(x: BigNumber): BigNumber; + expm1(x: Complex): Complex; + expm1(x: MathArray): MathArray; + expm1(x: Matrix): Matrix; + + /** + * Round a value towards zero. For matrices, the function is evaluated + * element wise. + * @param x Number to be rounded + * @returns Rounded value + */ + fix(x: number): number; + fix(x: BigNumber): BigNumber; + fix(x: Fraction): Fraction; + fix(x: Complex): Complex; + fix(x: MathArray): MathArray; + fix(x: Matrix): Matrix; + + /** + * Round a value towards minus infinity. For matrices, the function is + * evaluated element wise. + * @param Number to be rounded + * @returns Rounded value + */ + floor(x: number): number; + floor(x: BigNumber): BigNumber; + floor(x: Fraction): Fraction; + floor(x: Complex): Complex; + floor(x: MathArray): MathArray; + floor(x: Matrix): Matrix; + + /** + * Calculate the greatest common divisor for two or more values or + * arrays. For matrices, the function is evaluated element wise. + * @param args Two or more integer numbers + * @returns The greatest common divisor + */ + gcd(...args: number[]): number; + gcd(...args: BigNumber[]): BigNumber; + gcd(...args: Fraction[]): Fraction; + gcd(...args: MathArray[]): MathArray; + gcd(...args: Matrix[]): Matrix; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is + * defined as: hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) For + * matrix input, the hypotenusa is calculated for all values in the + * matrix. + * @param args A list with numeric values or an Array or Matrix. Matrix + * and Array input is flattened and returns a single number for the + * whole matrix. + * @returns Returns the hypothenuse of the input values. + */ + hypot(...args: number[]): number; + hypot(...args: BigNumber[]): BigNumber; + + /** + * Calculate the least common multiple for two or more values or arrays. + * lcm is defined as: lcm(a, b) = abs(a * b) / gcd(a, b) For matrices, + * the function is evaluated element wise. + * @param a An integer number + * @param b An integer number + * @returns The least common multiple + */ + lcm(a: number, b: number): number; + lcm(a: BigNumber, b: BigNumber): BigNumber; + lcm(a: MathArray, b: MathArray): MathArray; + lcm(a: Matrix, b: Matrix): Matrix; + + /** + * Calculate the logarithm of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @param base Optional base for the logarithm. If not provided, the + * natural logarithm of x is calculated. Default value: e. + * @returns Returns the logarithm of x + */ + log( + x: number | BigNumber | Complex | MathArray | Matrix, + base?: number | BigNumber | Complex + ): number | BigNumber | Complex | MathArray | Matrix; + + /** + * Calculate the 10-base of a value. This is the same as calculating + * log(x, 10). For matrices, the function is evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the 10-base logarithm of x + */ + log10(x: number): number; + log10(x: BigNumber): BigNumber; + log10(x: Complex): Complex; + log10(x: MathArray): MathArray; + log10(x: Matrix): Matrix; + + /** + * Calculate the logarithm of a value+1. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the logarithm of x+1 + */ + log1p(x: number, base?: number | BigNumber | Complex): number; + log1p(x: BigNumber, base?: number | BigNumber | Complex): BigNumber; + log1p(x: Complex, base?: number | BigNumber | Complex): Complex; + log1p(x: MathArray, base?: number | BigNumber | Complex): MathArray; + log1p(x: Matrix, base?: number | BigNumber | Complex): Matrix; + + /** + * Calculate the 2-base of a value. This is the same as calculating + * log(x, 2). For matrices, the function is evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the 2-base logarithm of x + */ + log2(x: number): number; + log2(x: BigNumber): BigNumber; + log2(x: Complex): Complex; + log2(x: MathArray): MathArray; + log2(x: Matrix): Matrix; + + /** + * Calculates the modulus, the remainder of an integer division. For + * matrices, the function is evaluated element wise. The modulus is + * defined as: x - y * floor(x / y) + * @see http://en.wikipedia.org/wiki/Modulo_operation. + * @param x Dividend + * @param y Divisor + * @returns Returns the remainder of x divided by y + */ + mod( + x: number | BigNumber | Fraction | MathArray | Matrix, + y: number | BigNumber | Fraction | MathArray | Matrix + ): number | BigNumber | Fraction | MathArray | Matrix; + + /** + * Multiply two values, x * y. The result is squeezed. For matrices, the + * matrix product is calculated. + * @param x The first value to multiply + * @param y The second value to multiply + * @returns Multiplication of x and y + */ + multiply(x: Matrix | MathArray, y: MathType): Matrix | MathArray; + multiply(x: Unit, y: Unit): Unit; + multiply(x: number, y: number): number; + multiply(x: MathType, y: MathType): MathType; + + /** + * Calculate the norm of a number, vector or matrix. The second + * parameter p is optional. If not provided, it defaults to 2. + * @param x Value for which to calculate the norm + * @param p Vector space. Supported numbers include Infinity and + * -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The + * Frobenius norm) Default value: 2. + * @returns the p-norm + */ + norm( + x: number | BigNumber | Complex | MathArray | Matrix, + p?: number | BigNumber | string + ): number | BigNumber; + + /** + * Calculate the nth root of a value. The principal nth root of a + * positive real number A, is the positive real solution of the equation + * x^root = A For matrices, the function is evaluated element wise. + * @param a Value for which to calculate the nth root + * @param root The root. Default value: 2. + * @return The nth root of a + */ + nthRoot( + a: number | BigNumber | MathArray | Matrix | Complex, + root?: number | BigNumber + ): number | Complex | MathArray | Matrix; + + /** + * Calculates the power of x to y, x ^ y. Matrix exponentiation is + * supported for square matrices x, and positive integer exponents y. + * @param x The base + * @param y The exponent + * @returns x to the power y + */ + pow(x: MathType, y: number | BigNumber | Complex): MathType; + + /** + * Round a value towards the nearest integer. For matrices, the function + * is evaluated element wise. + * @param x Number to be rounded + * @param n Number of decimals Default value: 0. + * @returns Rounded value of x + */ + round( + x: number | BigNumber | Fraction | Complex | MathArray | Matrix, + n?: number | BigNumber | MathArray + ): number | BigNumber | Fraction | Complex | MathArray | Matrix; + + /** + * Compute the sign of a value. The sign of a value x is: 1 when x > 1 + * -1 when x < 0 0 when x == 0 For matrices, the function is evaluated + * element wise. + * @param x The number for which to determine the sign + * @returns The sign of x + */ + sign(x: number): number; + sign(x: BigNumber): BigNumber; + sign(x: Fraction): Fraction; + sign(x: Complex): Complex; + sign(x: MathArray): MathArray; + sign(x: Matrix): Matrix; + sign(x: Unit): Unit; + + /** + * Calculate the square root of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the square root + * @returns Returns the square root of x + */ + sqrt(x: number): number; + sqrt(x: BigNumber): BigNumber; + sqrt(x: Complex): Complex; + sqrt(x: MathArray): MathArray; + sqrt(x: Matrix): Matrix; + sqrt(x: Unit): Unit; + + /** + * Compute the square of a value, x * x. For matrices, the function is + * evaluated element wise. + * @param x Number for which to calculate the square + * @returns Squared value + */ + square(x: number): number; + square(x: BigNumber): BigNumber; + square(x: Fraction): Fraction; + square(x: Complex): Complex; + square(x: MathArray): MathArray; + square(x: Matrix): Matrix; + square(x: Unit): Unit; + + /** + * Subtract two values, x - y. For matrices, the function is evaluated + * element wise. + * @param x Initial value + * @param y Value to subtract from x + * @returns Subtraction of x and y + */ + subtract(x: MathType, y: MathType): MathType; + + /** + * Inverse the sign of a value, apply a unary minus operation. For + * matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real + * and complex value are inverted. + * @param x Number to be inverted + * @returns Retursn the value with inverted sign + */ + unaryMinus(x: number): number; + unaryMinus(x: BigNumber): BigNumber; + unaryMinus(x: Fraction): Fraction; + unaryMinus(x: Complex): Complex; + unaryMinus(x: MathArray): MathArray; + unaryMinus(x: Matrix): Matrix; + unaryMinus(x: Unit): Unit; + + /** + * Unary plus operation. Boolean values and strings will be converted to + * a number, numeric values will be returned as is. For matrices, the + * function is evaluated element wise. + * @param x Input value + * @returns Returns the input value when numeric, converts to a number + * when input is non-numeric. + */ + unaryPlus(x: number): number; + unaryPlus(x: BigNumber): BigNumber; + unaryPlus(x: Fraction): Fraction; + unaryPlus(x: string): string; + unaryPlus(x: Complex): Complex; + unaryPlus(x: MathArray): MathArray; + unaryPlus(x: Matrix): Matrix; + unaryPlus(x: Unit): Unit; + + /** + * Calculate the extended greatest common divisor for two values. See + * http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * @param a An integer number + * @param b An integer number + * @returns Returns an array containing 3 integers [div, m, n] where div + * = gcd(a, b) and a*m + b*n = div + */ + xgcd(a: number | BigNumber, b: number | BigNumber): MathArray; + + /************************************************************************* + * Bitwise functions + ************************************************************************/ + + /** + * Bitwise AND two values, x & y. For matrices, the function is + * evaluated element wise. + * @param x First value to and + * @param y Second value to and + * @returns AND of x and y + */ + bitAnd( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise NOT value, ~x. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the best prefix + * base. + * @param x Value to not + * @returns NOT of x + */ + bitNot(x: number): number; + bitNot(x: BigNumber): BigNumber; + bitNot(x: MathArray): MathArray; + bitNot(x: Matrix): Matrix; + + /** + * Bitwise OR two values, x | y. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the lowest + * print base. + * @param x First value to or + * @param y Second value to or + * @returns OR of x and y + */ + bitOr(x: number, y: number): number; + bitOr(x: BigNumber, y: BigNumber): BigNumber; + bitOr(x: MathArray, y: MathArray): MathArray; + bitOr(x: Matrix, y: Matrix): Matrix; + + /** + * Bitwise XOR two values, x ^ y. For matrices, the function is + * evaluated element wise. + * @param x First value to xor + * @param y Second value to xor + * @returns XOR of x and y + */ + bitXor( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise left logical shift of a value x by y number of bits, x << y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x shifted left y times + */ + leftShift( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise right arithmetic shift of a value x by y number of bits, x >> + * y. For matrices, the function is evaluated element wise. For units, + * the function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x sign-filled shifted right y times + */ + rightArithShift( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise right logical shift of value x by y number of bits, x >>> y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x zero-filled shifted right y times + */ + rightLogShift( + x: number | MathArray | Matrix, + y: number + ): number | MathArray | Matrix; + + /************************************************************************* + * Combinatorics functions + ************************************************************************/ + + /** + * The Bell Numbers count the number of partitions of a set. A partition + * is a pairwise disjoint subset of S whose union is S. bellNumbers only + * takes integer arguments. The following condition must be enforced: n + * >= 0 + * @param n Total number of objects in the set + * @returns B(n) + */ + bellNumbers(n: number): number; + bellNumbers(n: BigNumber): BigNumber; + + /** + * The Catalan Numbers enumerate combinatorial structures of many + * different types. catalan only takes integer arguments. The following + * condition must be enforced: n >= 0 + * @param n nth Catalan number + * @returns Cn(n) + */ + catalan(n: number): number; + catalan(n: BigNumber): BigNumber; + + /** + * The composition counts of n into k parts. Composition only takes + * integer arguments. The following condition must be enforced: k <= n. + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns Returns the composition counts of n into k parts. + */ + composition( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /** + * The Stirling numbers of the second kind, counts the number of ways to + * partition a set of n labelled objects into k nonempty unlabelled + * subsets. stirlingS2 only takes integer arguments. The following + * condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = + * 1 + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns S(n,k) + */ + stirlingS2( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /************************************************************************* + * Complex functions + ************************************************************************/ + + /** + * Compute the argument of a complex value. For a complex number a + bi, + * the argument is computed as atan2(b, a). For matrices, the function + * is evaluated element wise. + * @param x A complex number or array with complex numbers + * @returns The argument of x + */ + arg(x: number | Complex): number; + arg(x: BigNumber | Complex): BigNumber; + arg(x: MathArray): MathArray; + arg(x: Matrix): Matrix; + + /** + * Compute the complex conjugate of a complex value. If x = a+bi, the + * complex conjugate of x is a - bi. For matrices, the function is + * evaluated element wise. + * @param x A complex number or array with complex numbers + * @returns The complex conjugate of x + */ + conj( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | Complex | MathArray | Matrix; + + /** + * Get the imaginary part of a complex number. For a complex number a + + * bi, the function returns b. For matrices, the function is evaluated + * element wise. + * @param x A complex number or array with complex numbers + * @returns The imaginary part of x + */ + im( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Get the real part of a complex number. For a complex number a + bi, + * the function returns a. For matrices, the function is evaluated + * element wise. + * @param x A complex number or array of complex numbers + * @returns The real part of x + */ + re( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /************************************************************************* + * Geometry functions + ************************************************************************/ + + /** + * Calculates: The eucledian distance between two points in 2 and 3 + * dimensional spaces. Distance between point and a line in 2 and 3 + * dimensional spaces. Pairwise distance between a set of 2D or 3D + * points NOTE: When substituting coefficients of a line(a, b and c), + * use ax + by + c = 0 instead of ax + by = c For parametric equation of + * a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, + * c) + * @param x Coordinates of the first point + * @param y Coordinates of the second point + * @returns Returns the distance from two/three points + */ + distance( + x: MathArray | Matrix | object, + y: MathArray | Matrix | object + ): number | BigNumber; + + /** + * Calculates the point of intersection of two lines in two or three + * dimensions and of a line and a plane in three dimensions. The inputs + * are in the form of arrays or 1 dimensional matrices. The line + * intersection functions return null if the lines do not meet. Note: + * Fill the plane coefficients as x + y + z = c and not as x + y + z + c + * = 0. + * @param w Co-ordinates of first end-point of first line + * @param x Co-ordinates of second end-point of first line + * @param y Co-ordinates of first end-point of second line OR + * Coefficients of the plane's equation + * @param z Co-ordinates of second end-point of second line OR null if + * the calculation is for line and plane + * @returns Returns the point of intersection of lines/lines-planes + */ + intersect( + w: MathArray | Matrix, + x: MathArray | Matrix, + y: MathArray | Matrix, + z: MathArray | Matrix + ): MathArray; + + /************************************************************************* + * Logical functions + ************************************************************************/ + + /** + * Logical and. Test whether two values are both defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to and + * @param y Second value to and + * @returns Returns true when both inputs are defined with a + * nonzero/nonempty value. + */ + and( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical not. Flips boolean value of a given parameter. For matrices, + * the function is evaluated element wise. + * @param x First value to not + * @returns Returns true when input is a zero or empty value. + */ + not( + x: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical or. Test if at least one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to or + * @param y Second value to or + * @returns Returns true when one of the inputs is defined with a + * nonzero/nonempty value. + */ + or( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical xor. Test whether one and only one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to xor + * @param y Second value to xor + * @returns Returns true when one and only one input is defined with a + * nonzero/nonempty value. + */ + xor( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /************************************************************************* + * Matrix functions + ************************************************************************/ + + /** + * Concatenate two or more matrices. dim: number is a zero-based + * dimension over which to concatenate the matrices. By default the last + * dimension of the matrices. + * @param args Two or more matrices + * @returns Concatenated matrix + */ + concat(...args: Array): MathArray | Matrix; + + /** + * Calculate the cross product for two vectors in three dimensional + * space. The cross product of A = [a1, a2, a3] and B =[b1, b2, b3] is + * defined as: cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 + * * b2 - a2 * b1 ] + * @param x First vector + * @param y Second vector + * @returns Returns the cross product of x and y + */ + cross(x: MathArray | Matrix, y: MathArray | Matrix): Matrix | MathArray; + + /** + * Calculate the determinant of a matrix. + * @param x A Matrix + * @returns the determinant of x + */ + det(x: MathArray | Matrix): number; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix. When x + * is a vector, a matrix with vector x on the diagonal will be returned. + * When x is a two dimensional matrix, the matrixes kth diagonal will be + * returned as vector. When k is positive, the values are placed on the + * super diagonal. When k is negative, the values are placed on the sub + * diagonal. + * @param X A two dimensional matrix or a vector + * @param k The diagonal where the vector will be filled in or + * retrieved. Default value: 0. + * @param format The matrix storage format. Default value: 'dense'. + * @returns Diagonal matrix from input vector, or diagonal from input + * matrix + */ + diag(X: MathArray | Matrix, format?: string): Matrix; + diag( + X: MathArray | Matrix, + k: number | BigNumber, + format?: string + ): Matrix | MathArray; + + /** + * Calculate the dot product of two vectors. The dot product of A = [a1, + * a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as: dot(A, + * B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * @param x First vector + * @param y Second vector + * @returns Returns the dot product of x and y + */ + dot(x: MathArray | Matrix, y: MathArray | Matrix): number; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be + * square. Not to be confused with exp(a), which performs element-wise + * exponentiation. The exponential is calculated using the Padé + * approximant with scaling and squaring; see “Nineteen Dubious Ways to + * Compute the Exponential of a Matrix,” by Moler and Van Loan. + * @param x A square matrix + * @returns The exponential of x + */ + expm(x: Matrix): Matrix; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. The + * matrix has ones on the diagonal and zeros elsewhere. + * @param size The size for the matrix + * @param format The Matrix storage format + * @returns A matrix with ones on the diagonal + */ + eye( + size: number | number[] | Matrix | MathArray, + format?: string + ): Matrix | MathArray | number; + /** + * @param m The x dimension for the matrix + * @param n The y dimension for the matrix + * @param format The Matrix storage format + * @returns A matrix with ones on the diagonal + */ + eye(m: number, n: number, format?: string): Matrix | MathArray | number; + + /** + * Filter the items in an array or one dimensional matrix. + * @param x A one dimensional matrix or array to filter + * @param test A function or regular expression to test items. All + * entries for which test returns true are returned. When test is a + * function, it is invoked with three parameters: the value of the + * element, the index of the element, and the matrix/array being + * traversed. The function must return a boolean. + */ + filter( + x: Matrix | MathArray, + test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray) | RegExp + ): Matrix | MathArray; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + * @param x Matrix to be flattened + * @returns Returns the flattened matrix + */ + flatten(x: MathArray | Matrix): MathArray | Matrix; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param x The matrix to iterate on. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + */ + forEach(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): void; + + /** + * Calculate the inverse of a square matrix. + * @param x Matrix to be inversed + * @returns The inverse of x + */ + inv( + x: number | Complex | MathArray | Matrix + ): number | Complex | MathArray | Matrix; /** * Calculate the kronecker product of two matrices or vectors - * @param x First Matrix - * @param y Second Matrix + * @param x First vector + * @param y Second vector + * @returns Returns the kronecker product of x and y */ - kron(x: Matrix|MathArray, y: Matrix|MathArray): Matrix; - - /** - * Calculate the least common multiple for two or more values or arrays. lcm is defined as: - * lcm(a, b) = abs(a * b) / gcd(a, b) - * For matrices, the function is evaluated element wise. - */ - lcm(a: number, b: number): number; - lcm(a: BigNumber , b: BigNumber): BigNumber ; - lcm(a: MathArray, b: MathArray): MathArray; - lcm(a: Matrix, b: Matrix): Matrix; - - /** - * Calculate the logarithm of a value. For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the logarithm. - * @param base Optional base for the logarithm. If not provided, the natural logarithm of x is calculated. Default value: e. - */ - log(x: number|BigNumber|Complex|MathArray|Matrix, base?: number|BigNumber|Complex): number|BigNumber|Complex|MathArray|Matrix; - - /** - * Calculate the 10-base of a value. This is the same as calculating log(x, 10). For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the logarithm. - */ - log10(x: number): number; - log10(x: BigNumber): BigNumber; - log10(x: Complex): Complex; - log10(x: MathArray): MathArray; - log10(x: Matrix): Matrix; - - /** - * Calculates the modulus, the remainder of an integer division. For matrices, the function is evaluated element wise. - * The modulus is defined as: - * x - y * floor(x / y) - * @see http://en.wikipedia.org/wiki/Modulo_operation. - * @param x Dividend - * @param y Divisor - */ - mod(x: number|BigNumber|Fraction|MathArray|Matrix, y: number|BigNumber|Fraction|MathArray|Matrix): number|BigNumber|Fraction|MathArray|Matrix; - - /** - * Multiply two values, x * y. The result is squeezed. For matrices, the matrix product is calculated. - */ - multiply(x: MathArray|Matrix, y: MathType): Matrix; - multiply(x: Unit, y: Unit): Unit; - multiply(x: number, y: number): number; - multiply(x: MathType, y: MathType): MathType; - - /** - * Calculate the norm of a number, vector or matrix. The second parameter p is optional. If not provided, it defaults to 2. - * @param x Value for which to calculate the norm - * @param p Vector space. Supported numbers include Infinity and -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) Default value: 2. - * @returns the p-norm - */ - norm(x: number|BigNumber|Complex|MathArray|Matrix, p?: number|BigNumber|string): number|BigNumber; - - /** - * Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation - * x^root = A - * For matrices, the function is evaluated element wise. - * @param a Value for which to calculate the nth root - * @param root The root. Default value: 2. - */ - nthRoot(a: number|BigNumber|MathArray|Matrix|Complex, root?: number|BigNumber): number|Complex|MathArray|Matrix; - - /** - * Calculates the power of x to y, x ^ y. Matrix exponentiation is supported for square matrices x, and positive integer exponents y. - * @param x The base - * @param y The exponent - */ - pow(x: MathType, y: number|BigNumber|Complex): MathType; - - /** - * Round a value towards the nearest integer. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @param n Number of decimals Default value: 0. - */ - round(x: number|BigNumber|Fraction|Complex|MathArray|Matrix, n?: number|BigNumber|MathArray): number|BigNumber|Fraction|Complex|MathArray|Matrix; - - /** - * Compute the sign of a value. The sign of a value x is: - * 1 when x > 1 - * -1 when x < 0 - * 0 when x == 0 - * For matrices, the function is evaluated element wise. - */ - sign(x: number): number; - sign(x: BigNumber): BigNumber; - sign(x: Fraction): Fraction ; - sign(x: Complex): Complex ; - sign(x: MathArray): MathArray; - sign(x: Matrix): Matrix; - sign(x: Unit): Unit; - - /** - * Calculate the square root of a value. For matrices, the function is evaluated element wise. - */ - sqrt(x: number): number; - sqrt(x: BigNumber): BigNumber; - sqrt(x: Complex): Complex ; - sqrt(x: MathArray): MathArray; - sqrt(x: Matrix): Matrix; - sqrt(x: Unit): Unit; - - /** - * Compute the square of a value, x * x. For matrices, the function is evaluated element wise. - */ - square(x: number): number; - square(x: BigNumber): BigNumber; - square(x: Fraction): Fraction ; - square(x: Complex): Complex ; - square(x: MathArray): MathArray; - square(x: Matrix): Matrix; - square(x: Unit): Unit; - - /** - * Subtract two values, x - y. For matrices, the function is evaluated element wise. - */ - subtract(x: MathType, y: MathType): MathType; - - /** - * Inverse the sign of a value, apply a unary minus operation. - * For matrices, the function is evaluated element wise. Boolean values and strings will be converted to a number. For complex numbers, both real and complex value are inverted. - */ - unaryMinus(x: number): number; - unaryMinus(x: BigNumber): BigNumber; - unaryMinus(x: Fraction): Fraction ; - unaryMinus(x: Complex): Complex ; - unaryMinus(x: MathArray): MathArray; - unaryMinus(x: Matrix): Matrix; - unaryMinus(x: Unit): Unit; - - /** - * Unary plus operation. Boolean values and strings will be converted to a number, numeric values will be returned as is. - * For matrices, the function is evaluated element wise. - */ - unaryPlus(x: number): number; - unaryPlus(x: BigNumber): BigNumber; - unaryPlus(x: Fraction): Fraction ; - unaryPlus(x: string): string; - unaryPlus(x: Complex): Complex ; - unaryPlus(x: MathArray): MathArray; - unaryPlus(x: Matrix): Matrix; - unaryPlus(x: Unit): Unit; - - /** - * Calculate the extended greatest common divisor for two values. See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. - */ - xgcd(a: number|BigNumber, b: number|BigNumber): MathArray; - - /** - * Bitwise AND two values, x & y. For matrices, the function is evaluated element wise. - */ - bitAnd(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise NOT value, ~x. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - */ - bitNot(x: number): number; - bitNot(x: BigNumber): BigNumber ; - bitNot(x: MathArray): MathArray; - bitNot(x: Matrix): Matrix; - - /** - * Bitwise OR two values, x | y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the lowest print base. - */ - bitOr(x: number): number; - bitOr(x: BigNumber): BigNumber ; - bitOr(x: MathArray): MathArray; - bitOr(x: Matrix): Matrix; - - /** - * Bitwise XOR two values, x ^ y. For matrices, the function is evaluated element wise. - */ - bitXor(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise left logical shift of a value x by y number of bits, x << y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - leftShift(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise right arithmetic shift of a value x by y number of bits, x >> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightArithShift(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise right logical shift of value x by y number of bits, x >>> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightLogShift(x: number|MathArray|Matrix, y: number): number|MathArray|Matrix; - - /** - * The Bell Numbers count the number of partitions of a set. - * A partition is a pairwise disjoint subset of S whose union is S. bellNumbers only takes integer arguments. - * The following condition must be enforced: n >= 0 - * @param n Total number of objects in the set - */ - bellNumbers(n: number): number; - bellNumbers(n: BigNumber): BigNumber; - - /** - * The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n nth Catalan number - */ - catalan(n: number): number; - catalan(n: BigNumber): BigNumber; - - /** - * The composition counts of n into k parts. Composition only takes integer arguments. The following condition must be enforced: k <= n. - * @param n Total number of objects in the set - * @param k Number of objects in the subset - * @returns Returns the composition counts of n into k parts. - */ - composition(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. - * stirlingS2 only takes integer arguments. The following condition must be enforced: k <= n. - * If n = k or k = 1, then s(n,k) = 1 - * @param n Total number of objects in the set - * @param k Number of objects in the subset - */ - stirlingS2(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * Compute the argument of a complex value. For a complex number a + bi, the argument is computed as atan2(b, a). For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - arg(x: number|Complex): number; - arg(x: MathArray): MathArray; - arg(x: Matrix): Matrix; - - /** - * Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate of x is a - bi. For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - conj(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|Complex|MathArray|Matrix; - - /** - * Get the imaginary part of a complex number. For a complex number a + bi, the function returns b. - * For matrices, the function is evaluated element wise. - */ - im(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Get the real part of a complex number. For a complex number a + bi, the function returns a. - * For matrices, the function is evaluated element wise. - */ - re(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Create a BigNumber, which can store numbers with arbitrary precision. When a matrix is provided, all elements will be converted to BigNumber. - */ - bignumber(x?: number|string|MathArray|Matrix|boolean): BigNumber; - - /** - * Create a boolean or convert a string or number to a boolean. - * In case of a number, true is returned for non-zero numbers, and false in case of zero. - * Strings can be 'true' or 'false', or can contain a number. When value is a matrix, all elements will be converted to boolean. - */ - boolean(x: string|number|boolean|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Wrap any value in a chain, allowing to perform chained operations on the value. - * All methods available in the math.js library can be called upon the chain, and then will be evaluated with the value itself as first argument. - * The chain can be closed by executing chain.done(), which returns the final value. - * The chain has a number of special functions: - * done() Finalize the chain and return the chain's value. - * valueOf() The same as done() - * toString() Executes math.format() onto the chain's value, returning a string representation of the value. - */ - chain(value?: any): MathJsChain; - - /** - * Create a complex value or convert a value to a complex value. - */ - complex(arg?: Complex|string|MathArray| PolarCoordinates): Complex; - complex(re: number, im: number): Complex; - - /** - * Create a fraction convert a value to a fraction. - */ - fraction(numerator: number|string|MathArray|Matrix, denominator?: number|string|MathArray|Matrix): Fraction|MathArray|Matrix; - - /** - * Create an index. An Index can store ranges having start, step, and end for multiple dimensions. Matrix.get, Matrix.set, and math.subset accept an Index as input. - */ - index(...ranges: any[]): Index; - - /** - * Create a Matrix. The function creates a new math.type.Matrix object from an Array. A Matrix has utility functions - * to manipulate the data in the matrix, like getting the size and getting or setting values in the matrix. Supported - * storage formats are 'dense' and 'sparse'. - */ - matrix(format?: 'sparse'|'dense'): Matrix; - matrix(data: MathArray|Matrix, format?: 'sparse'|'dense', dataType?: string): Matrix; - - /** - * Create a number or convert a string, boolean, or unit to a number. When value is a matrix, all elements will be converted to number. - */ - number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber): number|MathArray|Matrix; - number(unit: Unit, valuelessUnit: Unit|string): number|MathArray|Matrix; - - /** - * Create a Sparse Matrix. The function creates a new math.type.Matrix object from an Array. A Matrix has utility - * functions to manipulate the data in the matrix, like getting the size and getting or setting values in the matrix. - * @param data A two dimensional array - */ - sparse(data?: MathArray|Matrix, dataType?: string): Matrix; - - /** - * Create a string or convert any object into a string. Elements of Arrays and Matrices are processed element wise. - * @param value A value to convert to a string - */ - string(value: any): string|MathArray|Matrix; - - /** - * Create a unit. Depending on the passed arguments, the function will create and return a new math.type.Unit object. - * When a matrix is provided, all elements will be converted to units. - */ - unit(unit: string): Unit; - unit(value: number, unit: string): Unit; - - /** - * Create a user-defined unit and register it with the Unit type. - */ - createUnit(name: string, definition?: string|UnitDefinition, options?: CreateUnitOptions): Unit; - createUnit(units: Record, options?: CreateUnitOptions): Unit; - - /** - * Parse and compile an expression. Returns a an object with a function eval([scope]) to evaluate the compiled expression. - */ - compile(expr: MathExpression): EvalFunction; - compile(exprs: MathExpression[]): EvalFunction[]; - - /** - * Evaluate an expression. - */ - eval(expr: MathExpression|MathExpression[], scope?: any): any; - - /** - * Retrieve help on a function or data type. Help files are retrieved from the documentation in math.expression.docs. - */ - help(search: any): Help; - - /** - * Parse an expression. Returns a node tree, which can be evaluated by invoking node.eval(); - */ - parse(expr: MathExpression, options?: any): MathNode; - parse(exprs: MathExpression[], options?: any): MathNode[]; - - /** - * Create a parser. The function creates a new math.expression.Parser object. - */ - parser(): Parser; - - /** - * Calculates: The eucledian distance between two points in 2 and 3 dimensional spaces. Distance between point - * and a line in 2 and 3 dimensional spaces. Pairwise distance between a set of 2D or 3D points NOTE: When - * substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c For parametric - * equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) - */ - distance(x: MathType, y: MathType): number | BigNumber; - - /** - * Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in - * three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions - * return null if the lines do not meet. - * Note: Fill the plane coefficients as x + y + z = c and not as x + y + z + c = 0. - * @param w Co-ordinates of first end-point of first line - * @param x Co-ordinates of second end-point of first line - * @param y Co-ordinates of first end-point of second line OR Coefficients of the plane's equation - * @param z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane - * @returns Returns the point of intersection of lines/lines-planes - */ - intersect(w: MathArray|Matrix, x: MathArray|Matrix, y: MathArray|Matrix, z: MathArray|Matrix): MathArray; - - /** - * Logical and. Test whether two values are both defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - and(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical not. Flips boolean value of a given parameter. For matrices, the function is evaluated element wise. - */ - not(x: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical or. Test if at least one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - or(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical xor. Test whether one and only one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - xor(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Concatenate two or more matrices. - * dim: number is a zero-based dimension over which to concatenate the matrices. By default the last dimension of the matrices. - */ - concat(...args: Array): MathArray|Matrix; - - /** - * Calculate the cross product for two vectors in three dimensional space. The cross product of A = [a1, a2, a3] - * and B =[b1, b2, b3] is defined as: - * cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ] - */ - cross(x: MathArray|Matrix, y: MathArray|Matrix): Matrix; - - /** - * Calculate the determinant of a matrix. - */ - det(x: MathArray|Matrix): number; - - /** - * Create a diagonal matrix or retrieve the diagonal of a matrix. - * When x is a vector, a matrix with vector x on the diagonal will be returned. When x is a two dimensional matrix, - * the matrixes kth diagonal will be returned - * as vector. When k is positive, the values are placed on the super diagonal. When k is negative, the values are - * placed on the sub diagonal. - * @param X A two dimensional matrix or a vector - * @param k The diagonal where the vector will be filled in or retrieved. Default value: 0. - * @param format The matrix storage format. Default value: 'dense'. - */ - diag(X: MathArray|Matrix, format?: string): Matrix; - diag(X: MathArray|Matrix, k: number|BigNumber, format?: string): Matrix; - - /** - * Calculate the dot product of two vectors. - * The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] - * is defined as: - * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn - */ - dot(x: MathArray|Matrix, y: MathArray|Matrix): number; - - /** - * Create a 2-dimensional identity matrix with size m x n or n x n. The matrix has ones on the diagonal and zeros elsewhere. - */ - eye(n: number|number[], format?: string): Matrix; - eye(m: number, n: number, format?: string): Matrix; - - /** - * Flatten a multi dimensional matrix into a single dimensional matrix. - */ - flatten(x: MathArray|Matrix): MathArray|Matrix; - - /** - * Calculate the inverse of a square matrix. - */ - inv(x: number|Complex|MathArray|Matrix): number|Complex|MathArray|Matrix; - - /** - * Create a matrix filled with ones. The created matrix can have one or multiple dimensions. - */ - ones(n: number|number[], format?: string): MathArray|Matrix; - ones(m: number, n: number, format?: string): MathArray|Matrix; - - /** - * Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter includeEnd. - * @param str A string 'start:end' or 'start:step:end' - * @param start Start of the range - * @param end End of the range, excluded by default, included when parameter includeEnd=true - * @param step Step size. Default value is 1. - * @returns Parameters describing the ranges start, end, and optional step. - */ - range(str: string, includeEnd?: boolean): Matrix; - range(start: number|BigNumber, end: number|BigNumber, includeEnd?: boolean): Matrix; - range(start: number|BigNumber, end: number|BigNumber, step: number|BigNumber, includeEnd?: boolean): Matrix; - - /** - * Resize a matrix - * @param x Matrix to be resized - * @param size One dimensional array with numbers - * @param defaultValue Zero by default, except in case of a string, in that case defaultValue = ' ' Default value: 0. - */ - resize(x: MathArray|Matrix, size: MathArray|Matrix, defaultValue?: number|string): MathArray|Matrix; - - /** - * Calculate the size of a matrix or scalar. - */ - size(x: boolean|number|Complex|Unit|string|MathArray|Matrix): MathArray|Matrix; - - /** - * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. - */ - squeeze(x: MathArray|Matrix): Matrix|MathArray; - - /** - * Get or set a subset of a matrix or string. - * @param value An array, matrix, or string - * @param index An index containing ranges for each dimension - * @param replacement An array, matrix, or scalar. If provided, the subset is replaced with replacement. If not provided, the subset is returned - * @param defaultValue Default value, filled in on new entries when the matrix is resized. If not provided, math.matrix elements will be left undefined. Default value: undefined. - */ - subset(value: MathArray|Matrix|string, index: Index, replacement?: any, defaultValue?: any): MathArray|Matrix|string; - - /** - * Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. - */ - trace(x: MathArray|Matrix): number; - - /** - * Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only two dimensional matrices are supported. - */ - transpose(x: MathArray|Matrix): MathArray|Matrix; - - /** - * Create a matrix filled with zeros. The created matrix can have one or multiple dimensions. - */ - zeros(n: number|number[], format?: string): MathArray|Matrix; - zeros(m: number, n: number, format?: string): MathArray|Matrix; - - /** - * Compute the number of ways of picking k unordered outcomes from n possibilities. - * Combinations only takes integer arguments. The following condition must be enforced: k <= n. - */ - combinations(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * Create a distribution object with a set of random functions for given random distribution. - * @param name Name of a distribution. Choose from 'uniform', 'normal'. - */ - distribution(name: string): Distribution; - - /** - * Compute the factorial of a value - * Factorial only supports an integer value as argument. For matrices, the function is evaluated element wise. - */ - factorial(n: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Compute the gamma function of a value using Lanczos approximation for small values, and an extended - * Stirling approximation for large values. - * For matrices, the function is evaluated element wise. - */ - gamma(n: number|MathArray|Matrix): number|MathArray|Matrix; - - /** - * Calculate the Kullback-Leibler (KL) divergence between two distributions - */ - kldivergence(x: MathArray|Matrix, y: MathArray|Matrix): number; - - /** - * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from n possibilities. - * multinomial takes one array of integers as an argument. The following condition must be enforced: every ai <= 0 - */ - multinomial(a: number[]|BigNumber[]): number|BigNumber; - - /** - * Compute the number of ways of obtaining an ordered subset of k elements from a set of n elements. - * Permutations only takes integer arguments. The following condition must be enforced: k <= n. - * @param n The number of objects in total - * @param k The number of objects in the subset - */ - permutations(n: number|BigNumber, k?: number|BigNumber): number|BigNumber; - - /** - * Random pick a value from a one dimensional array. Array element is picked using a random function with uniform distribution. - */ - pickRandom(array: number[]): number; - - /** - * Return a random number larger or equal to min and smaller than max using a uniform distribution. - */ - random(min?: number, max?: number): number; - random(size: MathArray|Matrix, min?: number, max?: number): MathArray|Matrix; - - /** - * Return a random integer number larger or equal to min and smaller than max using a uniform distribution. - */ - randomInt(min: number, max?: number): number; - randomInt(size: MathArray|Matrix, min?: number, max?: number): MathArray|Matrix; - - /** - * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. - * x and y are considered equal when the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - compare(x: MathType, y: MathType): number|BigNumber|Fraction|MathArray|Matrix; - - /** - * Test element wise whether two matrices are equal. The function accepts both matrices and scalar values. - */ - deepEqual(x: MathType, y: MathType): number|BigNumber|Fraction|Complex|Unit|MathArray|Matrix; - - /** - * Test whether two values are equal. - * - * The function tests whether the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. - * Values null and undefined are compared strictly, thus null is only equal to null and nothing else, and undefined is only equal to undefined and nothing else. - */ - equal(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is larger than y. - * The function returns true when x is larger than y and the relative difference between x and y is larger than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - larger(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is larger or equal to y. - * The function returns true when x is larger than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - largerEq(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is smaller than y. - * The function returns true when x is smaller than y and the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - smaller(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is smaller or equal to y. - * The function returns true when x is smaller than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. For matrices, the function is evaluated element wise. - */ - smallerEq(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether two values are unequal. - * The function tests whether the relative difference between x and y is larger than the configured epsilon. The function cannot - * be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. - * Values null and undefined are compared strictly, thus null is unequal with everything except null, and undefined is unequal with - * everything except undefined. - */ - unequal(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Compute the maximum value of a matrix or a list with values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - max(...args: MathType[]): any; - max(A: MathArray|Matrix, dim?: number): any; - - /** - * Compute the mean value of matrix or a list with values. In case of a multi dimensional array, the mean of the flattened array will be - * calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - mean(...args: MathType[]): any; - mean(A: MathArray|Matrix, dim?: number): any; - - /** - * Compute the median of a matrix or a list with values. The values are sorted and the middle value is returned. In case of an - * even number of values, the average of the two middle values is returned. Supported types of values are: Number, BigNumber, Unit - * In case of a (multi dimensional) array or matrix, the median of all elements will be calculated. - */ - median(...args: MathType[]): any; - - /** - * Compute the maximum value of a matrix or a list of values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - min(...args: MathType[]): any; - min(A: MathArray|Matrix, dim?: number): any; - - /** - * Computes the mode of a set of numbers or a list with values(numbers or characters). If there are more than one modes, it returns a list of those values. - */ - mode(...args: MathType[]): any; - - /** - * Compute the product of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - prod(...args: MathType[]): any; - - /** - * Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. - * Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber - * In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated. - */ - quantileSeq(A: MathArray|Matrix, prob: number|BigNumber|MathArray, sorted?: boolean): number|BigNumber|Unit|MathArray; - - /** - * Compute the standard deviation of a matrix or a list with values. The standard deviations is defined as the square root of the - * variance: std(A) = sqrt(var(A)). In case of a (multi dimensional) array or matrix, the standard deviation over all elements will - * be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the following - * values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - */ - std(array: MathArray|Matrix, normalization?: string): number; - - /** - * Compute the sum of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - sum(...args: Array): any; - sum(array: MathArray|Matrix): any; - - /** - * Compute the variance of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the variance over all - * elements will be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the - * following values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - * Note that older browser may not like the variable name var. In that case, the function can be called as math['var'](...) - * instead of math.var(...). - */ - var(...args: Array): any; - var(array: MathArray|Matrix, normalization?: string): any; - - /** - * Calculate the inverse cosine of a value. For matrices, the function is evaluated element wise. - */ - acos(x: number): number; - acos(x: BigNumber): BigNumber; - acos(x: Complex): Complex; - acos(x: MathArray): MathArray; - acos(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccos of a value, defined as acosh(x) = ln(sqrt(x^2 - 1) + x). - * For matrices, the function is evaluated element wise. - */ - acosh(x: number): number; - acosh(x: BigNumber): BigNumber; - acosh(x: Complex): Complex; - acosh(x: MathArray): MathArray; - acosh(x: Matrix): Matrix; - - /** - * Calculate the inverse cotangent of a value. For matrices, the function is evaluated element wise. - */ - acot(x: number): number; - acot(x: BigNumber): BigNumber; - acot(x: MathArray): MathArray; - acot(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2. - * For matrices, the function is evaluated element wise. - */ - acoth(x: number): number; - acoth(x: BigNumber): BigNumber; - acoth(x: MathArray): MathArray; - acoth(x: Matrix): Matrix; - - /** - * Calculate the inverse cosecant of a value. For matrices, the function is evaluated element wise. - */ - acsc(x: number): number; - acsc(x: BigNumber): BigNumber; - acsc(x: MathArray): MathArray; - acsc(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) = ln(1/x + sqrt(1/x^2 + 1)). - * For matrices, the function is evaluated element wise. - */ - acsch(x: number): number; - acsch(x: BigNumber): BigNumber; - acsch(x: MathArray): MathArray; - acsch(x: Matrix): Matrix; - - /** - * Calculate the inverse secant of a value. For matrices, the function is evaluated element wise. - */ - asec(x: number): number; - asec(x: BigNumber): BigNumber; - asec(x: MathArray): MathArray; - asec(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated element wise. - */ - asech(x: number): number; - asech(x: BigNumber): BigNumber; - asech(x: MathArray): MathArray; - asech(x: Matrix): Matrix; - - /** - * Calculate the inverse sine of a value. For matrices, the function is evaluated element wise. - */ - asin(x: number): number; - asin(x: BigNumber): BigNumber; - asin(x: Complex): Complex; - asin(x: MathArray): MathArray; - asin(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated element wise. - */ - asinh(x: number): number; - asinh(x: BigNumber): BigNumber; - asinh(x: MathArray): MathArray; - asinh(x: Matrix): Matrix; - - /** - * Calculate the inverse tangent of a value. For matrices, the function is evaluated element wise. - */ - atan(x: number): number; - atan(x: BigNumber): BigNumber; - atan(x: MathArray): MathArray; - atan(x: Matrix): Matrix; - - /** - * Calculate the inverse tangent function with two arguments, y/x. By providing two arguments, the right quadrant of the - * computed angle can be determined. - * For matrices, the function is evaluated element wise. - */ - atan2(y: number, x: number): number; - atan2(y: MathArray|Matrix, x: MathArray|Matrix): MathArray|Matrix; - - /** - * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = ln((1 + x)/(1 - x)) / 2. - * For matrices, the function is evaluated element wise. - */ - atanh(x: number): number; - atanh(x: BigNumber): BigNumber; - atanh(x: MathArray): MathArray; - atanh(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 * (exp(x) + exp(-x)). For matrices, the function is evaluated element wise. - */ - cosh(x: number|Unit): number; - cosh(x: BigNumber): BigNumber; - cosh(x: Complex): Complex; - cosh(x: MathArray): MathArray; - cosh(x: Matrix): Matrix; - - /** - * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). For matrices, the function is evaluated element wise. - */ - cot(x: number|Unit): number; - cot(x: Complex): Complex; - cot(x: MathArray): MathArray; - cot(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 / tanh(x). For matrices, the function is evaluated element wise. - */ - coth(x: number|Unit): number; - coth(x: Complex): Complex; - coth(x: MathArray): MathArray; - coth(x: Matrix): Matrix; - - /** - * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For matrices, the function is evaluated element wise. - */ - csc(x: number|Unit): number; - csc(x: Complex): Complex; - csc(x: MathArray): MathArray; - csc(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 / sinh(x). For matrices, the function is evaluated element wise. - */ - csch(x: number|Unit): number; - csch(x: Complex): Complex; - csch(x: MathArray): MathArray; - csch(x: Matrix): Matrix; - - /** - * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For matrices, the function is evaluated element wise. - */ - sec(x: number|Unit): number; - sec(x: Complex): Complex; - sec(x: MathArray): MathArray; - sec(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / cosh(x). For matrices, the function is evaluated element wise. - */ - sech(x: number|Unit): number; - sech(x: Complex): Complex; - sech(x: MathArray): MathArray; - sech(x: Matrix): Matrix; - - /** - * Calculate the sine of a value. For matrices, the function is evaluated element wise. - */ - sin(x: number|Unit): number; - sin(x: BigNumber): BigNumber; - sin(x: Complex): Complex; - sin(x: MathArray): MathArray; - sin(x: Matrix): Matrix; - - /** - * Calculate the cosine of a value. For matrices, the function is evaluated element wise. - */ - cos(x: number|Unit): number; - cos(x: BigNumber): BigNumber; - cos(x: Complex): Complex; - cos(x: MathArray): MathArray; - cos(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * (exp(x) - exp(-x)). For matrices, the function is evaluated element wise. - */ - sinh(x: number|Unit): number; - sinh(x: BigNumber): BigNumber; - sinh(x: Complex): Complex; - sinh(x: MathArray): MathArray; - sinh(x: Matrix): Matrix; - - /** - * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). For matrices, the function is evaluated element wise. - */ - tan(x: number|Unit): number; - tan(x: BigNumber): BigNumber; - tan(x: Complex): Complex; - tan(x: MathArray): MathArray; - tan(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic tangent of a value, defined as tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is evaluated element wise. - */ - tanh(x: number|Unit): number; - tanh(x: BigNumber): BigNumber; - tanh(x: Complex): Complex; - tanh(x: MathArray): MathArray; - tanh(x: Matrix): Matrix; - - /** - * Change the unit of a value. For matrices, the function is evaluated element wise. - * @param x The unit to be converted. - * @param unit New unit. Can be a string like "cm" or a unit without value. - */ - to(x: Unit|MathArray|Matrix, unit: Unit|string): Unit|MathArray|Matrix; - - /** - * Clone an object. - */ - clone(x: any): any; - - /** - * Filter the items in an array or one dimensional matrix. - * @param x A one dimensional matrix or array to filter - * @param test - */ - filter(x: MathArray|Matrix, test: RegExp|((item: any) => boolean)): MathArray|Matrix; - - /** - * Iterate over all elements of a matrix/array, and executes the given callback function. - * @param x The matrix to iterate on. - * @param callback The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix/array being traversed. - */ - forEach: (x: MathArray|Matrix, callback: (item: any) => any) => void; - - /** - * Format a value of any type into a string. - * @param value The value to be formatted - */ - format(value: any, options?: FormatOptions|number|((item: any) => string)): string; - - /** - * Test whether a value is an integer number. The function supports number, BigNumber, and Fraction. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isInteger(x: any): boolean; - - /** - * Test whether a value is negative: smaller than zero. The function supports types number, BigNumber, Fraction, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isNegative(x: any): boolean; - - /** - * Test whether a value is an numeric value. The function is evaluated element-wise in case of Array or Matrix input. - */ - isNumeric(x: any): boolean; - - /** - * Test whether a value is positive: larger than zero. The function supports types number, BigNumber, Fraction, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isPositive(x: any): boolean; - - /** - * Test whether a value is zero. The function can check for zero for types number, BigNumber, Fraction, Complex, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isZero(x: any): boolean; - - /** - * Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array. - * @param x The matrix to iterate on. - * @param callback The callback method is invoked with three parameters: the value of the element, the index of the element, and the matrix being traversed. - */ - map(x: MathArray|Matrix, callback: (item: any) => any): MathArray|Matrix; - - /** - * Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. - * @param x A one dimensional matrix or array to sort - * @param k The kth smallest value to be retrieved; zero-based index - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - * @returns Returns the kth lowest value. - */ - partitionSelect(x: MathArray|Matrix, k: number, compare?: string|((a: any, b: any) => number)): any; - - /** - * Interpolate values into a string template. - * @param template A string containing variable placeholders. - * @param values An object containing variables which will be filled in in the template. - * @param precision Number of digits to format numbers. If not provided, the value will not be rounded. - */ - print: (template: string, values: any, precision?: number) => void; - - /** - * Sort the items in a matrix. - * @param x A one dimensional matrix or array to sort - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - */ - sort(x: MathArray|Matrix, compare?: string|((a: any, b: any) => number)): MathArray|Matrix; - - /** - * Determine the type of a variable. - */ - typeof(x: any): string; - } - - interface Matrix { - type: string; - storage(): string; - datatype(): string; - density(): number; - subset(index: Index, replacement?: any, defaultValue?: any): Matrix; - get(index: number[]): any; - set(index: number[], value: any, defaultValue?: number|string): Matrix; - resize(size: MathArray|Matrix, defaultValue?: number|string): Matrix; - clone(): Matrix; - size(): number[]; - map(callback: (a: any, b: number, c: Matrix) => any, skipZeros?: boolean): Matrix; - forEach: (callback: (a: any, b: number, c: Matrix) => void, skipZeros?: boolean) => void; - toJSON(): any; - diagonal(k?: number|BigNumber): any[]; - swapRows(i: number, j: number): Matrix; - } - - interface BigNumber extends Decimal {} // tslint:disable-line no-empty-interface - - interface Fraction { - s: number; - n: number; - d: number; - } - - interface Complex { - re: number; - im: number; - toPolar(): PolarCoordinates; - clone(): Complex; - } - - interface PolarCoordinates { - r: number; - phi: number; + kron(x: Matrix | MathArray, y: Matrix | MathArray): Matrix; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param x The matrix to iterate on. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + * @returns Transformed map of x + */ + map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): Matrix | MathArray; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * @param size The size of each dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with ones + */ + ones(size: number | number[], format?: string): MathArray | Matrix; + /** + * @param m The x dimension of the matrix + * @param n The y dimension of the amtrix + * @param format The matrix storage format + * @returns A matrix filled with ones + */ + ones(m: number, n: number, format?: string): MathArray | Matrix; + + /** + * Partition-based selection of an array or 1D matrix. Will find the kth + * smallest value, and mutates the input array. Uses Quickselect. + * @param x A one dimensional matrix or array to sort + * @param k The kth smallest value to be retrieved; zero-based index + * @param compare An optional comparator function. The function is + * called as compare(a, b), and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. Default value: 'asc'. + * @returns Returns the kth lowest value. + */ + partitionSelect( + x: MathArray | Matrix, + k: number, + compare?: "asc" | "desc" | ((a: any, b: any) => number) + ): any; + + /** + * Create an array from a range. By default, the range end is excluded. + * This can be customized by providing an extra parameter includeEnd. + * @param str A string 'start:end' or 'start:step:end' + * @param start Start of the range + * @param end End of the range, excluded by default, included when + * parameter includeEnd=true + * @param step Step size. Default value is 1. + * @param includeEnd: Option to specify whether to include the end or + * not. False by default + * @returns Parameters describing the ranges start, end, and optional + * step. + */ + range(str: string, includeEnd?: boolean): Matrix; + range( + start: number | BigNumber, + end: number | BigNumber, + includeEnd?: boolean + ): Matrix; + range( + start: number | BigNumber, + end: number | BigNumber, + step: number | BigNumber, + includeEnd?: boolean + ): Matrix; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * @param x Matrix to be reshaped + * @param sizes One dimensional array with integral sizes for each + * dimension + * @returns A reshaped clone of matrix x + */ + reshape( + x: MathArray | Matrix, + sizes: number[] + ): MathArray | Matrix; + + /** + * Resize a matrix + * @param x Matrix to be resized + * @param size One dimensional array with numbers + * @param defaultValue Zero by default, except in case of a string, in + * that case defaultValue = ' ' Default value: 0. + * @returns A resized clone of matrix x + */ + resize( + x: MathArray | Matrix, + size: MathArray | Matrix, + defaultValue?: number | string + ): MathArray | Matrix; + + /** + * Calculate the size of a matrix or scalar. + * @param A matrix + * @returns A vector with the size of x + */ + size( + x: boolean | number | Complex | Unit | string | MathArray | Matrix + ): MathArray | Matrix; + + /** + * Sort the items in a matrix + * @param x A one dimensional matrix or array to sort + * @param compare An optional _comparator function or name. The function + * is called as compare(a, b), and must return 1 when a > b, -1 when a < + * b, and 0 when a == b. Default value: ‘asc’ + * @returns Returns the sorted matrix + */ + sort( + x: Matrix | MathArray, + compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural" + ): Matrix | MathArray; + + /** + * Calculate the principal square root of a square matrix. The principal + * square root matrix X of another matrix A is such that X * X = A. + * @param A The square matrix A + * @returns The principal square root of matrix A + */ + sqrtm(A: MathArray | Matrix): MathArray | Matrix; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a + * matrix. + * @param x Matrix to be squeezed + * @returns Squeezed matrix + */ + squeeze(x: MathArray | Matrix): Matrix | MathArray; + + /** + * Get or set a subset of a matrix or string. + * @param value An array, matrix, or string + * @param index An index containing ranges for each dimension + * @param replacement An array, matrix, or scalar. If provided, the + * subset is replaced with replacement. If not provided, the subset is + * returned + * @param defaultValue Default value, filled in on new entries when the + * matrix is resized. If not provided, math.matrix elements will be left + * undefined. Default value: undefined. + * @returns Either the retrieved subset or the updated matrix + */ + subset( + value: MathArray | Matrix | string, + index: Index, + replacement?: any, + defaultValue?: any + ): MathArray | Matrix | string; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + * @param x A matrix + * @returns The trace of x + */ + trace(x: MathArray | Matrix): number; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only two dimensional matrices are supported. + * @param x Matrix to be transposed + * @returns The transposed matrix + */ + transpose(x: MathArray | Matrix): MathArray | Matrix; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * @param size The size of each dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(size: number | number[], format?: string): MathArray | Matrix; + /** + * @param m The x dimension of the matrix + * @param n The y dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(m: number, n: number, format?: string): MathArray | Matrix; + + /************************************************************************* + * Probability functions + ************************************************************************/ + + /** + * Compute the number of ways of picking k unordered outcomes from n + * possibilities. Combinations only takes integer arguments. The + * following condition must be enforced: k <= n. + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns Number of possible combinations + */ + combinations( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /** + * Compute the factorial of a value Factorial only supports an integer + * value as argument. For matrices, the function is evaluated element + * wise. + * @param n An integer number + * @returns The factorial of n + */ + factorial( + n: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large + * values. For matrices, the function is evaluated element wise. + * @param n A real or complex number + * @returns The gamma of n + */ + gamma(n: number | MathArray | Matrix): number | MathArray | Matrix; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two + * distributions + * @param q First vector + * @param p Second vector + * @returns Returns disance between q and p + */ + kldivergence(q: MathArray | Matrix, p: MathArray | Matrix): number; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, + * a2, ..., ai unordered outcomes from n possibilities. multinomial + * takes one array of integers as an argument. The following condition + * must be enforced: every ai <= 0 + * @param a Integer number of objects in the subset + * @returns multinomial coefficent + */ + multinomial(a: number[] | BigNumber[]): number | BigNumber; + + /** + * Compute the number of ways of obtaining an ordered subset of k + * elements from a set of n elements. Permutations only takes integer + * arguments. The following condition must be enforced: k <= n. + * @param n The number of objects in total + * @param k The number of objects in the subset + * @returns The number of permutations + */ + permutations( + n: number | BigNumber, + k?: number | BigNumber + ): number | BigNumber; + + /** + * Random pick a value from a one dimensional array. Array element is + * picked using a random function with uniform distribution. + * @param array A one dimensional array + * @param number An int or float + * @param weights An array of ints or floats + * @returns Returns a single random value from array when number is 1 or + * undefined. Returns an array with the configured number of elements + * when number is > 1. + */ + pickRandom( + array: number[], + number?: number, + weights?: number[] + ): number; + + /** + * Return a random number larger or equal to min and smaller than max + * using a uniform distribution. + * @param size If provided, an array or matrix with given size and + * filled with random values is returned + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + * @returns A random number + */ + random(min?: number, max?: number): number; + random( + size: MathArray | Matrix, + min?: number, + max?: number + ): MathArray | Matrix; + + /** + * Return a random integer number larger or equal to min and smaller + * than max using a uniform distribution. + * @param size If provided, an array or matrix with given size and + * filled with random values is returned + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + * @returns A random number + */ + randomInt(min: number, max?: number): number; + randomInt( + size: MathArray | Matrix, + min?: number, + max?: number + ): MathArray | Matrix; + + /************************************************************************* + * Relational functions + ************************************************************************/ + + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x + * == y. x and y are considered equal when the relative difference + * between x and y is smaller than the configured epsilon. The function + * cannot be used to compare values smaller than approximately 2.22e-16. + * For matrices, the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compare( + x: MathType | string, + y: MathType | string + ): number | BigNumber | Fraction | MathArray | Matrix; + + /** + * Compare two values of any type in a deterministic, natural way. For + * numeric values, the function works the same as math.compare. For + * types of values that can’t be compared mathematically, the function + * compares in a natural way. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compareNatural(x: any, y: any): number; + + /** + * Compare two strings lexically. Comparison is case sensitive. Returns + * 1 when x > y, -1 when x < y, and 0 when x == y. For matrices, the + * function is evaluated element wise. + * @param x First string to compare + * @param y Second string to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compareText( + x: string | MathArray | Matrix, + y: string | MathArray | Matrix + ): number | MathArray | Matrix; + + /** + * Test element wise whether two matrices are equal. The function + * accepts both matrices and scalar values. + * @param x First matrix to compare + * @param y Second amtrix to compare + * @returns Returns true when the input matrices have the same size and + * each of their elements is equal. + */ + deepEqual( + x: MathType, + y: MathType + ): number | BigNumber | Fraction | Complex | Unit | MathArray | Matrix; + + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. In case of complex numbers, x.re + * must equal y.re, and x.im must equal y.im. Values null and undefined + * are compared strictly, thus null is only equal to null and nothing + * else, and undefined is only equal to undefined and nothing else. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns true when the compared values are equal, else + * returns false + */ + equal( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Check equality of two strings. Comparison is case sensitive. For + * matrices, the function is evaluated element wise. + * @param x First string to compare + * @param y Second string to compare + * @returns Returns true if the values are equal, and false if not. + */ + equalText( + x: string | MathArray | Matrix, + y: string | MathArray | Matrix + ): number | MathArray | Matrix; + + /** + * Test whether value x is larger than y. The function returns true when + * x is larger than y and the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is larger than y, else returns false + */ + larger( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is larger or equal to y. The function returns + * true when x is larger than y or the relative difference between x and + * y is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is larger than or equal to y, else + * returns false + */ + largerEq( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is smaller than y. The function returns true + * when x is smaller than y and the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is smaller than y, else returns false + */ + smaller( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is smaller or equal to y. The function returns + * true when x is smaller than y or the relative difference between x + * and y is smaller than the configured epsilon. The function cannot be + * used to compare values smaller than approximately 2.22e-16. For + * matrices, the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is smaller than or equal to y, else + * returns false + */ + smallerEq( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether two values are unequal. The function tests whether the + * relative difference between x and y is larger than the configured + * epsilon. The function cannot be used to compare values smaller than + * approximately 2.22e-16. For matrices, the function is evaluated + * element wise. In case of complex numbers, x.re must unequal y.re, or + * x.im must unequal y.im. Values null and undefined are compared + * strictly, thus null is unequal with everything except null, and + * undefined is unequal with everything except undefined. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when the compared values are unequal, else + * returns false + */ + unequal( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /************************************************************************* + * Set functions + ************************************************************************/ + + /** + * Create the cartesian product of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The cartesian product of two (multi)sets + */ + setCartesian( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Create the difference of two (multi)sets: every element of set1, that + * is not the element of set2. Multi-dimension arrays will be converted + * to single-dimension arrays before the operation + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The difference of two (multi)sets + */ + setDifference( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Collect the distinct elements of a multiset. A multi-dimension array + * will be converted to a single-dimension array before the operation. + * @param a A multiset + * @returns A set containing the distinct elements of the multiset + */ + setDistinct(a: MathArray | Matrix): MathArray | Matrix; + + /** + * Create the intersection of two (multi)sets. Multi-dimension arrays + * will be converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The intersection of two (multi)sets + */ + setIntersect( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every + * element of set1 is the element of set2.) Multi-dimension arrays will + * be converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns True if a1 is subset of a2, else false + */ + setIsSubset(a1: MathArray | Matrix, a2: MathArray | Matrix): boolean; + + /** + * Count the multiplicity of an element in a multiset. A multi-dimension + * array will be converted to a single-dimension array before the + * operation. + * @param e An element in the multiset + * @param a A multiset + * @returns The number of how many times the multiset contains the + * element + */ + setMultiplicity( + e: number | BigNumber | Fraction | Complex, + a: MathArray | Matrix + ): number; + + /** + * Create the powerset of a (multi)set. (The powerset contains very + * possible subsets of a (multi)set.) A multi-dimension array will be + * converted to a single-dimension array before the operation. + * @param a A multiset + * @returns The powerset of the (multi)set + */ + setPowerset(a: MathArray | Matrix): MathArray | Matrix; + + /** + * Count the number of elements of a (multi)set. When a second parameter + * is ‘true’, count only the unique values. A multi-dimension array will + * be converted to a single-dimension array before the operation. + * @param a A multiset + * @returns The number of elements of the (multi)set + */ + setSize(a: MathArray | Matrix): number; + + /** + * Create the symmetric difference of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The symmetric difference of two (multi)sets + */ + setSymDifference( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Create the union of two (multi)sets. Multi-dimension arrays will be + * converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The union of two (multi)sets + */ + setUnion( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /************************************************************************* + * Special functions + ************************************************************************/ + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + * @param x A real number + * @returns The erf of x + */ + erf(x: number | MathArray | Matrix): number | MathArray | Matrix; + + /************************************************************************* + * Statistics functions + ************************************************************************/ + + /** + * Compute the median absolute deviation of a matrix or a list with + * values. The median absolute deviation is defined as the median of the + * absolute deviations from the median. + * @param array A single matrix or multiple scalar values. + * @returns The median absolute deviation + */ + mad(array: MathArray | Matrix): any; + + /** + * Compute the maximum value of a matrix or a list with values. In case + * of a multi dimensional array, the maximum of the flattened array will + * be calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or multiple scalar values + * @returns The maximum value + */ + max(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The maximum over the selected dimension + * @returns The maximum value + */ + max(A: MathArray | Matrix, dim?: number): any; + + /** + * Compute the mean value of matrix or a list with values. In case of a + * multi dimensional array, the mean of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or multiple scalar values + * @returns The mean of all values + */ + mean(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The mean over the selected dimension + * @returns The mean of all values + */ + mean(A: MathArray | Matrix, dim?: number): any; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. Supported + * types of values are: Number, BigNumber, Unit In case of a (multi + * dimensional) array or matrix, the median of all elements will be + * calculated. + * @param args A single matrix or or multiple scalar values + * @returns The median + */ + median(...args: MathType[]): any; + + /** + * Compute the maximum value of a matrix or a list of values. In case of + * a multi dimensional array, the maximum of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or or multiple scalar values + * @returns The minimum value + */ + min(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The minimum over the selected dimension + * @returns The minimum value + */ + min(A: MathArray | Matrix, dim?: number): any; + + /** + * Computes the mode of a set of numbers or a list with values(numbers + * or characters). If there are more than one modes, it returns a list + * of those values. + * @param args A single matrix + * @returns The mode of all values + */ + mode(...args: MathType[]): any; + + /** + * Compute the product of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + * @param args A single matrix or multiple scalar values + * @returns The product of all values + */ + prod(...args: MathType[]): any; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. Supported + * types of sequence values are: Number, BigNumber, Unit Supported types + * of probability are: Number, BigNumber In case of a (multi + * dimensional) array or matrix, the prob order quantile of all elements + * will be calculated. + * @param A A single matrix or array + * @param probOrN prob is the order of the quantile, while N is the + * amount of evenly distributed steps of probabilities; only one of + * these options can be provided + * @param sorted =false is data sorted in ascending order + * @returns Quantile(s) + */ + quantileSeq( + A: MathArray | Matrix, + prob: number | BigNumber | MathArray, + sorted?: boolean + ): number | BigNumber | Unit | MathArray; + + /** + * Compute the standard deviation of a matrix or a list with values. The + * standard deviations is defined as the square root of the variance: + * std(A) = sqrt(var(A)). In case of a (multi dimensional) array or + * matrix, the standard deviation over all elements will be calculated. + * Optionally, the type of normalization can be specified as second + * parameter. The parameter normalization can be one of the following + * values: 'unbiased' (default) The sum of squared errors is divided by + * (n - 1) 'uncorrected' The sum of squared errors is divided by n + * 'biased' The sum of squared errors is divided by (n + 1) + * @param array A single matrix or multiple scalar values + * @param normalization Determines how to normalize the variance. Choose + * ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. Default value: + * ‘unbiased’. + * @returns The standard deviation + */ + std( + array: MathArray | Matrix, + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): number; + + /** + * Compute the sum of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + * @param args A single matrix or multiple scalar values + * @returns The sum of all values + */ + sum(...args: Array): any; + /** + * @param array A single matrix + * @returns The sum of all values + */ + sum(array: MathArray | Matrix): any; + + /** + * Compute the variance of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the variance over all elements + * will be calculated. Optionally, the type of normalization can be + * specified as second parameter. The parameter normalization can be one + * of the following values: 'unbiased' (default) The sum of squared + * errors is divided by (n - 1) 'uncorrected' The sum of squared errors + * is divided by n 'biased' The sum of squared errors is divided by (n + + * 1) Note that older browser may not like the variable name var. In + * that case, the function can be called as math['var'](...) instead of + * math.var(...). + * @param args A single matrix or multiple scalar values + * @returns The variance + */ + var(...args: Array): any; + /** + * @param array A single matrix + * @param normalization normalization Determines how to normalize the + * variance. Choose ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. + * Default value: ‘unbiased’. + * @returns The variance + */ + var( + array: MathArray | Matrix, + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): any; + + /************************************************************************* + * String functions + ************************************************************************/ + + /** + * Format a value of any type into a string. + * @param value The value to be formatted + * @param options An object with formatting options. + * @param callback A custom formatting function, invoked for all numeric + * elements in value, for example all elements of a matrix, or the real + * and imaginary parts of a complex number. This callback can be used to + * override the built-in numeric notation with any type of formatting. + * Function callback is called with value as parameter and must return a + * string. + * @see http://mathjs.org/docs/reference/functions/format.html + * @returns The formatted value + */ + format( + value: any, + options?: FormatOptions | number | ((item: any) => string), + callback?: ((value: any) => string) + ): string; + + /** + * Interpolate values into a string template. + * @param template A string containing variable placeholders. + * @param values An object containing variables which will be filled in + * in the template. + * @param precision Number of digits to format numbers. If not provided, + * the value will not be rounded. + * @param options Formatting options, or the number of digits to format + * numbers. See function math.format for a description of all options. + * @returns Interpolated string + */ + print( + template: string, + values: any, + precision?: number, + options?: number | object + ): void; + + /************************************************************************* + * Trigonometry functions + ************************************************************************/ + + /** + * Calculate the inverse cosine of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc cosine of x + */ + acos(x: number): number; + acos(x: BigNumber): BigNumber; + acos(x: Complex): Complex; + acos(x: MathArray): MathArray; + acos(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccos of a value, defined as acosh(x) = + * ln(sqrt(x^2 - 1) + x). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arccosine of x + */ + acosh(x: number): number; + acosh(x: BigNumber): BigNumber; + acosh(x: Complex): Complex; + acosh(x: MathArray): MathArray; + acosh(x: Matrix): Matrix; + + /** + * Calculate the inverse cotangent of a value. For matrices, the + * function is evaluated element wise. + * @param x Function input + * @returns The arc cotangent of x + */ + acot(x: number): number; + acot(x: BigNumber): BigNumber; + acot(x: MathArray): MathArray; + acot(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) + * = (ln((x+1)/x) + ln(x/(x-1))) / 2. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The hyperbolic arccotangent of x + */ + acoth(x: number): number; + acoth(x: BigNumber): BigNumber; + acoth(x: MathArray): MathArray; + acoth(x: Matrix): Matrix; + + /** + * Calculate the inverse cosecant of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc cosecant of x + */ + acsc(x: number): number; + acsc(x: BigNumber): BigNumber; + acsc(x: MathArray): MathArray; + acsc(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) + * = ln(1/x + sqrt(1/x^2 + 1)). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arccosecant of x + */ + acsch(x: number): number; + acsch(x: BigNumber): BigNumber; + acsch(x: MathArray): MathArray; + acsch(x: Matrix): Matrix; + + /** + * Calculate the inverse secant of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc secant of x + */ + asec(x: number): number; + asec(x: BigNumber): BigNumber; + asec(x: MathArray): MathArray; + asec(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = + * ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arcsecant of x + */ + asech(x: number): number; + asech(x: BigNumber): BigNumber; + asech(x: MathArray): MathArray; + asech(x: Matrix): Matrix; + + /** + * Calculate the inverse sine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The arc sine of x + */ + asin(x: number): number; + asin(x: BigNumber): BigNumber; + asin(x: Complex): Complex; + asin(x: MathArray): MathArray; + asin(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = + * ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arcsine of x + */ + asinh(x: number): number; + asinh(x: BigNumber): BigNumber; + asinh(x: MathArray): MathArray; + asinh(x: Matrix): Matrix; + + /** + * Calculate the inverse tangent of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc tangent of x + */ + atan(x: number): number; + atan(x: BigNumber): BigNumber; + atan(x: MathArray): MathArray; + atan(x: Matrix): Matrix; + + /** + * Calculate the inverse tangent function with two arguments, y/x. By + * providing two arguments, the right quadrant of the computed angle can + * be determined. For matrices, the function is evaluated element wise. + * @param x Function input + * @returns Four quadrant inverse tangent + */ + atan2(y: number, x: number): number; + atan2(y: MathArray | Matrix, x: MathArray | Matrix): MathArray | Matrix; + + /** + * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = + * ln((1 + x)/(1 - x)) / 2. For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arctangent of x + */ + atanh(x: number): number; + atanh(x: BigNumber): BigNumber; + atanh(x: MathArray): MathArray; + atanh(x: Matrix): Matrix; + + /** + * Calculate the cosine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The cosine of x + */ + cos(x: number | Unit): number; + cos(x: BigNumber): BigNumber; + cos(x: Complex): Complex; + cos(x: MathArray): MathArray; + cos(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 + * * (exp(x) + exp(-x)). For matrices, the function is evaluated element + * wise. + * @param x Function input + * @returns The hyperbolic cosine of x + */ + cosh(x: number | Unit): number; + cosh(x: BigNumber): BigNumber; + cosh(x: Complex): Complex; + cosh(x: MathArray): MathArray; + cosh(x: Matrix): Matrix; + + /** + * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). + * For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The cotangent of x + */ + cot(x: number | Unit): number; + cot(x: Complex): Complex; + cot(x: MathArray): MathArray; + cot(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 + * / tanh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic cotangent of x + */ + coth(x: number | Unit): number; + coth(x: Complex): Complex; + coth(x: MathArray): MathArray; + coth(x: Matrix): Matrix; + + /** + * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For + * matrices, the function is evaluated element wise. + * @param x Function input + * @returns The cosecant hof x + */ + csc(x: number | Unit): number; + csc(x: Complex): Complex; + csc(x: MathArray): MathArray; + csc(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 + * / sinh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic cosecant of x + */ + csch(x: number | Unit): number; + csch(x: Complex): Complex; + csch(x: MathArray): MathArray; + csch(x: Matrix): Matrix; + + /** + * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For + * matrices, the function is evaluated element wise. + * @param x Function input + * @returns The secant of x + */ + sec(x: number | Unit): number; + sec(x: Complex): Complex; + sec(x: MathArray): MathArray; + sec(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / + * cosh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic secant of x + */ + sech(x: number | Unit): number; + sech(x: Complex): Complex; + sech(x: MathArray): MathArray; + sech(x: Matrix): Matrix; + + /** + * Calculate the sine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The sine of x + */ + sin(x: number | Unit): number; + sin(x: BigNumber): BigNumber; + sin(x: Complex): Complex; + sin(x: MathArray): MathArray; + sin(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * + * (exp(x) - exp(-x)). For matrices, the function is evaluated element + * wise. + * @param x Function input + * @returns The hyperbolic sine of x + */ + sinh(x: number | Unit): number; + sinh(x: BigNumber): BigNumber; + sinh(x: Complex): Complex; + sinh(x: MathArray): MathArray; + sinh(x: Matrix): Matrix; + + /** + * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). + * For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The tangent of x + */ + tan(x: number | Unit): number; + tan(x: BigNumber): BigNumber; + tan(x: Complex): Complex; + tan(x: MathArray): MathArray; + tan(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic tangent of a value, defined as tanh(x) = + * (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The hyperbolic tangent of x + */ + tanh(x: number | Unit): number; + tanh(x: BigNumber): BigNumber; + tanh(x: Complex): Complex; + tanh(x: MathArray): MathArray; + tanh(x: Matrix): Matrix; + + /************************************************************************* + * Unit functions + ************************************************************************/ + + /** + * Change the unit of a value. For matrices, the function is evaluated + * element wise. + * @param x The unit to be converted. + * @param unit New unit. Can be a string like "cm" or a unit without + * value. + * @returns Value with changed, fixed unit + */ + to( + x: Unit | MathArray | Matrix, + unit: Unit | string + ): Unit | MathArray | Matrix; + + /************************************************************************* + * Utils functions + ************************************************************************/ + + /** + * Clone an object. + * @param x Object to be cloned + * @returns A clone of object x + */ + clone(x: any): any; + + /** + * Test whether a value is an integer number. The function supports + * number, BigNumber, and Fraction. The function is evaluated + * element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x contains a numeric, integer value. + * Throws an error in case of an unknown data type. + */ + isInteger( + x: number | BigNumber | Fraction | MathArray | Matrix + ): boolean; + + /** + * Test whether a value is NaN (not a number). The function supports + * types number, BigNumber, Fraction, Unit and Complex. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is NaN. Throws an error in case of an + * unknown data type. + */ + isNaN( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is negative: smaller than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isNegative( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is an numeric value. The function is evaluated + * element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is a number, BigNumber, Fraction, or + * boolean. Returns false for other types. Throws an error in case of + * unknown types. + */ + isNumeric(x: any): x is number | BigNumber | Fraction | boolean; + + /** + * Test whether a value is positive: larger than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isPositive( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is prime: has no divisors other than itself and + * one. The function supports type number, bignumber. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isPrime(x: number | BigNumber | MathArray | Matrix): boolean; + + /** + * Test whether a value is zero. The function can check for zero for + * types number, BigNumber, Fraction, Complex, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is zero. Throws an error in case of an + * unknown data type. + */ + isZero( + x: + | number + | BigNumber + | Fraction + | MathArray + | Matrix + | Unit + | Complex + ): boolean; + + /** + * Determine the type of a variable. + * @param x The variable for which to test the type + * @returns Returns the name of the type. Primitive types are lower + * case, non-primitive types are upper-camel-case. For example ‘number’, + * ‘string’, ‘Array’, ‘Date’. + */ + typeof(x: any): string; } - interface MathJSON { - mathjs?: string; - value: number; - unit: string; - fixPrefix?: boolean; - } + interface Matrix { + type: string; + storage(): string; + datatype(): string; + create(data: MathArray, datatype?: string): void; + density(): number; + subset(index: Index, replacement?: any, defaultValue?: any): Matrix; + get(index: number[]): any; + set( + index: number[], + value: any, + defaultValue?: number | string + ): Matrix; + resize( + size: MathArray | Matrix, + defaultValue?: number | string + ): Matrix; + clone(): Matrix; + size(): number[]; + map( + callback: (a: any, b: number, c: Matrix) => any, + skipZeros?: boolean + ): Matrix; + forEach( + callback: (a: any, b: number, c: Matrix) => void, + skipZeros?: boolean + ): void; + toArray(): MathArray | Matrix; + valueOff(): MathArray | Matrix; + format(options?: FormatOptions | number | ((value: any) => string)): string; + toString(): string; + toJSON(): any; + diagonal(k?: number | BigNumber): any[]; + swapRows(i: number, j: number): Matrix; + } - interface Unit { - to(unit: string): Unit; - toNumber(unit: string): number; - clone(): Unit; - equalBase(unit: Unit): boolean; - equals(unit: Unit): boolean; - format(options: FormatOptions): string; - fromJSON(json: MathJSON): Unit; - toJSON(): MathJSON; - splitUnit(parts: ReadonlyArray): Unit[]; - toNumeric(unit: string): number | Fraction | BigNumber; - toSI(): Unit; - toString(): string; - } + interface BigNumber extends Decimal {} // tslint:disable-line no-empty-interface - interface CreateUnitOptions { - override?: boolean; - } + interface Fraction { + s: number; + n: number; + d: number; + } - interface UnitDefinition { - definition?: string|Unit; - prefixes?: string; - offset?: number; - aliases?: string[]; - } + interface Complex { + re: number; + im: number; + clone(): Complex; + equals(other: Complex): boolean; + format(precision?: number): string; + fromJSON(json: object): Complex; + fromPolar(polar: object): Complex; + fromPolar(r: number, phi: number): Complex; + toJSON(): object; + toPolar(): PolarCoordinates; + toString(): string; + compare(a: Complex, b: Complex): number; + } - interface Index {} // tslint:disable-line no-empty-interface + interface PolarCoordinates { + r: number; + phi: number; + } - interface EvalFunction { - eval(scope?: any): any; - } + interface MathJSON { + mathjs?: string; + value: number; + unit: string; + fixPrefix?: boolean; + } - interface MathNode { - isNode: boolean; - isSymbolNode?: boolean; - isConstantNode?: boolean; - isOperatorNode?: boolean; - op?: string; - fn?: string; - args?: MathNode[]; - type: string; - name?: string; - value?: any; + interface Unit { + valueOf(): string; + clone(): Unit; + isDerived(): boolean; + hasBase(base: any): boolean; + equalBase(unit: Unit): boolean; + equals(unit: Unit): boolean; + multiply(unit: Unit): Unit; + divide(unit: Unit): Unit; + pow(unit: Unit): Unit; + abs(unit: Unit): Unit; + to(unit: string): Unit; + toNumber(unit: string): number; + toNumeric(unit: string): number | Fraction | BigNumber; + toString(): string; + toJSON(): MathJSON; + formatUnits(): string; + format(options: FormatOptions): string; + parse(str: DOMStringList): Unit; + isValuelessUnit(name: string): boolean; + fromJSON(json: MathJSON): Unit; + } - compile(): EvalFunction; - eval(expr?: string): any; - /** - * - * Filter nodes in an expression tree. The callback function is called as callback(node: Node, path: string, parent: Node) : boolean for every node in the tree, - * and must return a boolean. The function filter returns an array with nodes for which the test returned true. - * Parameter path is a string containing a relative JSON Path. - * - * Example: - * - * ``` - * var node = math.parse('x^2 + x/4 + 3*y'); - * var filtered = node.filter(function (node) { - * return node.isSymbolNode && node.name == 'x'; - * }); - * // returns an array with two entries: two SymbolNodes 'x' - * ``` - * - * The callback function is called as callback(node: Node, path: string, parent: Node) : boolean for every node in the tree, and must return a boolean. - * The function filter returns an array with nodes for which the test returned true. Parameter path is a string containing a relative JSON Path. - * @return Returns an array with nodes for which test returned true - */ - filter(callback: (node: MathNode, path: string, parent: MathNode) => any): MathNode[]; + interface CreateUnitOptions { + prefixes?: "none" | "short" | "long" | "binary_short" | "binary_long"; + aliases?: string[]; + offset?: number; + override?: boolean; + } - /** - * [forEach description] - */ - forEach(callback: (node: MathNode, path: string, parent: MathNode) => any): MathNode[]; + interface UnitDefinition { + definition?: string | Unit; + prefixes?: string; + offset?: number; + aliases?: string[]; + } - /** - * `traverse(callback)` - * - * Recursively traverse all nodes in a node tree. - * Executes given callback for this node and each of its child nodes. - * Similar to Array.forEach, except recursive. - * The callback function is a mapping function accepting a node, and returning a replacement for the node or the original node. - * Function callback is called as callback(node: Node, path: string, parent: Node) for every node in the tree. - * Parameter path is a string containing a relative JSON Path. Example: - * - * ``` - * var node = math.parse('3 * x + 2'); - * node.traverse(function (node, path, parent) { - * switch (node.type) { - * case 'OperatorNode': console.log(node.type, node.op); break; - * case 'ConstantNode': console.log(node.type, node.value); break; - * case 'SymbolNode': console.log(node.type, node.name); break; - * default: console.log(node.type); - * } - * }); - * // outputs: - * // OperatorNode + - * // OperatorNode * - * // ConstantNode 3 - * // SymbolNode x - * // ConstantNode 2 - * ``` - */ - traverse(callback: (node: MathNode, path: string, parent: MathNode) => void): any; - /** - * Recursively transform an expression tree via a transform function. Similar to Array.map, - * but recursively executed on all nodes in the expression tree. The callback function is a - * mapping function accepting a node, and returning a replacement for the node or the original node. - * Function callback is called as callback(node: Node, path: string, parent: Node) for every node in - * the tree, and must return a Node. Parameter path is a string containing a relative JSON Path. - * - * For example, to replace all nodes of type SymbolNode having name ‘x’ with a ConstantNode with value 3: - * ```js - * var node = math.parse('x^2 + 5*x'); - * var transformed = node.transform(function (node, path, parent) { - * if (node.SymbolNode && node.name == 'x') { - * return new math.expression.node.ConstantNode(3); - * } - * else { - * return node; - * } - * }); - * transformed.toString(); // returns '(3 ^ 2) + (5 * 3)' - * ``` - */ - transform(callback: (node: MathNode, path: string, parent: MathNode) => MathNode): MathNode; + interface Index {} // tslint:disable-line no-empty-interface - /** - * Transform a node. Creates a new Node having it’s child's be the results of calling the provided - * callback function for each of the child's of the original node. The callback function is called - * as `callback(child: Node, path: string, parent: Node)` and must return a Node. - * Parameter path is a string containing a relative JSON Path. - * - * - * See also transform, which is a recursive version of map. - */ - map(callback: (node: MathNode, path: string, parent: MathNode) => MathNode): MathNode; - } + interface EvalFunction { + eval(scope?: any): any; + } - interface Parser { - eval(expr: string): any; - get(variable: string): any; - set: (variable: string, value: any) => void; - clear: () => void; - } + interface MathNode { + isNode: boolean; + isAccessorNode?: boolean; + isArrayNode?: boolean; + isAssignmentNode?: boolean; + isBlockNode?: boolean; + isConditionalnode?: boolean; + isConstantNode?: boolean; + isFunctionAssignmentNode?: boolean; + isFunctionNode?: boolean; + isIndexNode?: boolean; + isObjectNode?: boolean; + isOperatorNode?: boolean; + isParenthesisNode?: boolean; + isRangeNode?: boolean; + isSymbolNode?: boolean; + isUpdateNode?: boolean; + comment?: string; + op?: string; + fn?: string; + args?: MathNode[]; + type: string; + name?: string; + value?: any; - interface Distribution { - random(size: any, min?: any, max?: any): any; - randomInt(min: any, max?: any): any; - pickRandom(array: any): any; - } + /** + * Create a shallow clone of the node. The node itself is cloned, its + * childs are not cloned. + */ + clone(): MathNode; + /** + * Create a deep clone of the node. Both the node as well as all its + * childs are cloned recursively. + */ + cloneDeep(): MathNode; + /** + * Compile an expression into optimized JavaScript code. compile returns + * an object with a function eval([scope]) to evaluate. Example: + */ + compile(): EvalFunction; + /** + * Compile and eval an expression, this is the equivalent of doing + * node.compile().eval(scope). Example: + */ + eval(expr?: any): any; + /** + * Test whether this node equals an other node. Does a deep comparison + * of the values of both nodes. + */ + equals(other: MathNode): boolean; + /** + * + * Filter nodes in an expression tree. The callback function is called + * as callback(node: MathNode, path: string, parent: MathNode) : boolean + * for every node in the tree, and must return a boolean. The function + * filter returns an array with nodes for which the test returned true. + * Parameter path is a string containing a relative JSON Path. + * + * Example: + * + * ``` + * var node = math.parse('x^2 + x/4 + 3*y'); + * var filtered = node.filter(function (node) { + * return node.isSymbolMathNode && node.name == 'x'; + * }); + * // returns an array with two entries: two SymbolMathNodes 'x' + * ``` + * + * The callback function is called as callback(node: MathNode, path: + * string, parent: MathNode) : boolean for every node in the tree, and + * must return a boolean. The function filter returns an array with + * nodes for which the test returned true. Parameter path is a string + * containing a relative JSON Path. + * @return Returns an array with nodes for which test returned true + */ + filter( + callback: (node: MathNode, path: string, parent: MathNode) => any + ): MathNode[]; - interface FormatOptions { - /** - * Number notation. Choose from: - * 'fixed' Always use regular number notation. For example '123.40' and '14000000' - * 'exponential' Always use exponential notation. For example '1.234e+2' and '1.4e+7' - * 'auto' (default) Regular number notation for numbers having an absolute value between lower and upper bounds, and - * uses exponential notation elsewhere. Lower bound is included, upper bound is excluded. For example '123.4' and '1.4e7'. - */ - notation?: string; + /** + * [forEach description] + */ + forEach( + callback: (node: MathNode, path: string, parent: MathNode) => any + ): MathNode[]; - /** - * A number between 0 and 16 to round the digits of the number. In case of notations 'exponential' and 'auto', - * precision defines the total number of significant digits returned and is undefined by default. In case of notation 'fixed', - * precision defines the number of significant digits after the decimal point, and is 0 by default. - */ - precision?: number; + /** + * Transform a node. Creates a new MathNode having it’s child's be the + * results of calling the provided callback function for each of the + * child's of the original node. The callback function is called as + * `callback(child: MathNode, path: string, parent: MathNode)` and must + * return a MathNode. Parameter path is a string containing a relative + * JSON Path. + * + * + * See also transform, which is a recursive version of map. + */ + map( + callback: ( + node: MathNode, + path: string, + parent: MathNode + ) => MathNode + ): MathNode; - /** - * An object containing two parameters, {number} lower and {number} upper, used by notation 'auto' to determine - * when to return exponential notation. Default values are lower=1e-3 and upper=1e5. Only applicable for notation auto. - */ - exponential?: {lower: number; upper: number}; + /** + * Get a HTML representation of the parsed expression. + */ + toHtml(options?: object): string; - /** - * Available values: 'ratio' (default) or 'decimal'. For example format(fraction(1, 3)) will output '1/3' when 'ratio' - * is configured, and will output 0.(3) when 'decimal' is configured. - */ - fraction?: string; + /** + * Get a string representation of the parsed expression. This is not + * exactly the same as the original input. + */ + toString(options?: object): string; - /** - * A custom formatting function. Can be used to override the built-in notations. Function fn is called with - * value as parameter and must return a string. Is useful for example to format all values inside a matrix in a particular way. - */ - fn?: (item: any) => string; - } + /** + * Get a LaTeX representation of the expression. + */ + toTex(options?: object): string; - interface Help { - toString(): string; - toJSON(): string; + /** + * Recursively transform an expression tree via a transform function. + * Similar to Array.map, but recursively executed on all nodes in the + * expression tree. The callback function is a mapping function + * accepting a node, and returning a replacement for the node or the + * original node. Function callback is called as callback(node: + * MathNode, path: string, parent: MathNode) for every node in the tree, + * and must return a MathNode. Parameter path is a string containing a + * relative JSON Path. + * + * For example, to replace all nodes of type SymbolMathNode having name + * ‘x’ with a ConstantMathNode with value 3: + * ```js + * var node = math.parse('x^2 + 5*x'); + * var transformed = node.transform(function (node, path, parent) { + * if (node.SymbolMathNode && node.name == 'x') { + * return new math.expression.node.ConstantMathNode(3); + * } + * else { + * return node; + * } + * }); + * transformed.toString(); // returns '(3 ^ 2) + (5 * 3)' + * ``` + */ + transform( + callback: ( + node: MathNode, + path: string, + parent: MathNode + ) => MathNode + ): MathNode; + + /** + * `traverse(callback)` + * + * Recursively traverse all nodes in a node tree. Executes given + * callback for this node and each of its child nodes. Similar to + * Array.forEach, except recursive. The callback function is a mapping + * function accepting a node, and returning a replacement for the node + * or the original node. Function callback is called as callback(node: + * MathNode, path: string, parent: MathNode) for every node in the tree. + * Parameter path is a string containing a relative JSON Path. Example: + * + * ``` + * var node = math.parse('3 * x + 2'); + * node.traverse(function (node, path, parent) { + * switch (node.type) { + * case 'OperatorMathNode': console.log(node.type, node.op); break; + * case 'ConstantMathNode': console.log(node.type, node.value); break; + * case 'SymbolMathNode': console.log(node.type, node.name); break; + * default: console.log(node.type); + * } + * }); + * // outputs: + * // OperatorMathNode + + * // OperatorMathNode * + * // ConstantMathNode 3 + * // SymbolMathNode x + * // ConstantMathNode 2 + * ``` + */ + traverse( + callback: (node: MathNode, path: string, parent: MathNode) => void + ): any; + } + + interface Parser { + eval(expr: string): any; + get(variable: string): any; + set: (variable: string, value: any) => void; + clear: () => void; + } + + interface Distribution { + random(size: any, min?: any, max?: any): any; + randomInt(min: any, max?: any): any; + pickRandom(array: any): any; + } + + interface FormatOptions { + /** + * Number notation. Choose from: 'fixed' Always use regular number + * notation. For example '123.40' and '14000000' 'exponential' Always + * use exponential notation. For example '1.234e+2' and '1.4e+7' 'auto' + * (default) Regular number notation for numbers having an absolute + * value between lower and upper bounds, and uses exponential notation + * elsewhere. Lower bound is included, upper bound is excluded. For + * example '123.4' and '1.4e7'. + */ + notation?: "fixed" | "exponential" | "engineering" | "auto"; + + /** + * A number between 0 and 16 to round the digits of the number. In case + * of notations 'exponential' and 'auto', precision defines the total + * number of significant digits returned and is undefined by default. In + * case of notation 'fixed', precision defines the number of significant + * digits after the decimal point, and is 0 by default. + */ + precision?: number; + + /** + * Exponent determining the lower boundary for formatting a value with + * an exponent when notation='auto. Default value is -3. + */ + lowerExp?: number; + + /** + * Exponent determining the upper boundary for formatting a value with + * an exponent when notation='auto. Default value is 5. + */ + upperExp?: number; + + /** + * Available values: 'ratio' (default) or 'decimal'. For example + * format(fraction(1, 3)) will output '1/3' when 'ratio' is configured, + * and will output 0.(3) when 'decimal' is configured. + */ + fraction?: string; + } + + interface Help { + toString(): string; + toJSON(): string; + } + + interface ConfigOptions { + epsilon?: number; + matrix?: string; + number?: string; + precision?: number; + parenthesis?: string; + randomSeed?: string; + } + + interface MathJsJson { + /** + * Returns reviver function that can be used as reviver in JSON.parse function. + */ + reviver(): (key: any, value: any) => any; } interface MathJsChain { - /** - * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. - * @param b A column vector with the b values - */ - lsolve(b: Matrix|MathArray): MathJsChain; + done(): any; - /** - * Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in two matrices (L, U) - * and a row permutation vector p where A[p,:] = L * U - */ - lup(): MathJsChain; + /************************************************************************* + * Construction functions + ************************************************************************/ - /** - * Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector. - * @param b Column Vector - */ - lusolve(b: Matrix|MathArray): MathJsChain; + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to + * BigNumber. + */ + bignumber(): MathJsChain; - /** - * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix A is decomposed in - * two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U - * @param order The Symbolic Ordering and Analysis order: 0 - Natural ordering, no permutation vector q is - * returned 1 - Matrix must be square, symbolic ordering and analysis is performed on M = A + A' 2 - Symbolic - * ordering and analysis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. - * This is appropriate for LU factorization of non-symmetric matrices. 3 - Symbolic ordering and analysis is performed - * on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. A dense row is a row with - * more than 10*sqr(columns) entries. - * @param threshold Partial pivoting threshold (1 for partial pivoting) - * @returns The lower triangular matrix, the upper triangular matrix and the permutation vectors. - */ - slu(order: number, threshold: number): MathJsChain; + /** + * Create a boolean or convert a string or number to a boolean. In case + * of a number, true is returned for non-zero numbers, and false in case + * of zero. Strings can be 'true' or 'false', or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + */ + boolean(): MathJsChain; - /** - * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. U * x = b - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - usolve(b: Matrix|MathArray): MathJsChain; + /** + * Create a complex value or convert a value to a complex value. + * @param im Argument specifying the imaginary part of the complex + * number + */ + complex(im?: number): MathJsChain; - /** - * Calculate the absolute value of a number. For matrices, the function is evaluated element wise. - */ - abs(): MathJsChain; + /** + * Create a user-defined unit and register it with the Unit type. + * @param definition Definition of the unit in terms of existing units. + * For example, ‘0.514444444 m / s’. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + */ + createUnit( + definition?: string | UnitDefinition, + options?: CreateUnitOptions + ): MathJsChain; + /** + * Create a user-defined unit and register it with the Unit type. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + */ + createUnit(options?: CreateUnitOptions): MathJsChain; - /** - * Add two values, x + y. For matrices, the function is evaluated element wise. - * @param y Second value to add - */ - add(y: MathType): MathJsChain; + /** + * Create a fraction convert a value to a fraction. + * @param denominator Argument specifying the denominator of the + * fraction + */ + fraction( + denominator?: number | string | MathArray | Matrix + ): MathJsChain; - /** - * Calculate the cubic root of a value. For matrices, the function is evaluated element wise. - * @param allRoots Optional, false by default. Only applicable when x is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned. - */ - cbrt(allRoots?: boolean): MathJsChain; + /** + * Create an index. An Index can store ranges having start, step, and + * end for multiple dimensions. Matrix.get, Matrix.set, and math.subset + * accept an Index as input. + */ + index(): MathJsChain; - /** - * Round a value towards plus infinity If x is complex, both real and imaginary part are rounded towards plus infinity. For matrices, the function is evaluated element wise. - */ - ceil(): MathJsChain; + /** + * Create a Matrix. The function creates a new math.type.Matrix object + * from an Array. A Matrix has utility functions to manipulate the data + * in the matrix, like getting the size and getting or setting values in + * the matrix. Supported storage formats are 'dense' and 'sparse'. + */ + matrix(format?: "sparse" | "dense", dataType?: string): MathJsChain; - /** - * Compute the cube of a value, x * x * x. For matrices, the function is evaluated element wise. - */ - cube(): MathJsChain; + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * @param valuelessUnit A valueless unit, used to convert a unit to a + * number + */ + number(valuelessUnit?: Unit | string): MathJsChain; - /** - * Divide two values, x / y. To divide matrices, x is multiplied with the inverse of y: x * inv(y). - * @param y Denominator - */ - divide(y: MathType): MathJsChain; + /** + * Create a Sparse Matrix. The function creates a new math.type.Matrix + * object from an Array. A Matrix has utility functions to manipulate + * the data in the matrix, like getting the size and getting or setting + * values in the matrix. + * @param dataType Sparse Matrix data type + */ + sparse(dataType?: string): MathJsChain; - /** - * Divide two matrices element wise. The function accepts both matrices and scalar values. - * @param y Denominator - */ - dotDivide(y: MathType): MathJsChain; + /** + * Split a unit in an array of units whose sum is equal to the original + * unit. + * @param parts An array of strings or valueless units + */ + splitUnit(parts: Unit[]): MathJsChain; - /** - * Multiply two matrices element wise. The function accepts both matrices and scalar values. - * @param y Right hand value - */ - dotMultiply(y: MathType): MathJsChain; + /** + * Create a string or convert any object into a string. Elements of + * Arrays and Matrices are processed element wise. + */ + string(): MathJsChain; - /** - * Calculates the power of x to y element wise. - * @param y The exponent - */ - dotPow(y: MathType): MathJsChain; + /** + * Create a unit. Depending on the passed arguments, the function will + * create and return a new math.type.Unit object. When a matrix is + * provided, all elements will be converted to units. + * @param unit The unit to be created + */ + unit(unit?: string): MathJsChain; - /** - * Calculate the exponent of a value. For matrices, the function is evaluated element wise. - */ - exp(): MathJsChain; + /************************************************************************* + * Expression functions + ************************************************************************/ - /** - * Round a value towards zero. For matrices, the function is evaluated element wise. - */ - fix(): MathJsChain; + /** + * Parse and compile an expression. Returns a an object with a function + * eval([scope]) to evaluate the compiled expression. + */ + compile(): MathJsChain; - /** - * Round a value towards minus infinity. For matrices, the function is evaluated element wise. - */ - floor(): MathJsChain; + /** + * Evaluate an expression. + * @param scope Scope to read/write variables + */ + eval(scope?: object): MathJsChain; - /** - * Calculate the greatest common divisor for two or more values or arrays. For matrices, the function is evaluated element wise. - */ - gcd(...args: number[]): MathJsChain; - gcd(...args: BigNumber[]): MathJsChain ; - gcd(...args: Fraction[]): MathJsChain ; - gcd(...args: MathArray[]): MathJsChain ; - gcd(...args: Matrix[]): MathJsChain; + /** + * Retrieve help on a function or data type. Help files are retrieved + * from the documentation in math.expression.docs. + */ + help(): MathJsChain; - /** - * Calculate the hypotenuse of a list with values. The hypotenuse is defined as: - * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) - * For matrix input, the hypotenuse is calculated for all values in the matrix. - */ - hypot(...args: number[]): MathJsChain; - hypot(...args: BigNumber[]): MathJsChain; + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.eval(); + * @param options Available options: nodes - a set of custome nodes + */ + parse(options?: any): MathJsChain; + /** + * @param options Available options: nodes - a set of custome nodes + */ + parse(options?: any): MathJsChain; + + /** + * Create a parser. The function creates a new math.expression.Parser + * object. + */ + parser(): MathJsChain; + + /************************************************************************* + * Algebra functions + ************************************************************************/ + /** + * @param variable The variable over which to differentiate + * @param options There is one option available, simplify, which is true + * by default. When false, output will not be simplified. + */ + derivative(variable: MathNode | string, options?: {simplify: boolean}): MathJsChain; + + /** + * Solves the linear equation system by forwards substitution. Matrix + * must be a lower triangular matrix. + * @param b A column vector with the b values + */ + lsolve(b: Matrix | MathArray): MathJsChain; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix A + * is decomposed in two matrices (L, U) and a row permutation vector p + * where A[p,:] = L * U + */ + lup(): MathJsChain; + + /** + * Solves the linear system A * x = b where A is an [n x n] matrix and b + * is a [n] column vector. + * @param b Column Vector + * @param order The Symbolic Ordering and Analysis order, see slu for + * details. Matrix must be a SparseMatrix + * @param threshold Partial pivoting threshold (1 for partial pivoting), + * see slu for details. Matrix must be a SparseMatrix. + */ + lusolve( + b: Matrix | MathArray, + order?: number, + threshold?: number + ): MathJsChain; + + /** + * Calculate the Matrix QR decomposition. Matrix A is decomposed in two + * matrices (Q, R) where Q is an orthogonal matrix and R is an upper + * triangular matrix. + */ + qr(): MathJsChain; + + /** + * Transform a rationalizable expression in a rational fraction. If + * rational fraction is one variable polynomial then converts the + * numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * @param optional scope of expression or true for already evaluated + * rational expression at input + * @param detailed optional True if return an object, false if return + * expression node (default) + */ + rationalize(optional?: object | boolean, detailed?: boolean): MathJsChain; + + /** + * Simplify an expression tree. + * @param rules A list of rules are applied to an expression, repeating + * over the list until no further changes are made. It’s possible to + * pass a custom set of rules to the function as second argument. A rule + * can be specified as an object, string, or function. + * @param scope Scope to variables + */ + simplify( + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, + scope?: object + ): MathJsChain; + + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. + * Sparse Matrix A is decomposed in two matrices (L, U) and two + * permutation vectors (pinv, q) where P * A * Q = L * U + * @param order The Symbolic Ordering and Analysis order: 0 - Natural + * ordering, no permutation vector q is returned 1 - Matrix must be + * square, symbolic ordering and analisis is performed on M = A + A' 2 - + * Symbolic ordering and analysis is performed on M = A' * A. Dense + * columns from A' are dropped, A recreated from A'. This is appropriate + * for LU factorization of non-symmetric matrices. 3 - Symbolic ordering + * and analysis is performed on M = A' * A. This is best used for LU + * factorization is matrix M has no dense rows. A dense row is a row + * with more than 10*sqr(columns) entries. + * @param threshold Partial pivoting threshold (1 for partial pivoting) + */ + slu(order: number, threshold: number): MathJsChain; + + /** + * Solves the linear equation system by backward substitution. Matrix + * must be an upper triangular matrix. U * x = b + * @param b A column vector with the b values + */ + usolve(b: Matrix | MathArray): MathJsChain; + + /************************************************************************* + * Arithmetic functions + ************************************************************************/ + + /** + * Calculate the absolute value of a number. For matrices, the function + * is evaluated element wise. + */ + abs(): MathJsChain; + + /** + * Add two values, x + y. For matrices, the function is evaluated + * element wise. + * @param y Second value to add + */ + add(y: MathType): MathJsChain; + + /** + * Calculate the cubic root of a value. For matrices, the function is + * evaluated element wise. + * @param allRoots Optional, false by default. Only applicable when x is + * a number or complex number. If true, all complex roots are returned, + * if false (default) the principal root is returned. + */ + cbrt(allRoots?: boolean): MathJsChain; + + /** + * Round a value towards plus infinity If x is complex, both real and + * imaginary part are rounded towards plus infinity. For matrices, the + * function is evaluated element wise. + */ + ceil(): MathJsChain; + + /** + * Compute the cube of a value, x * x * x. For matrices, the function is + * evaluated element wise. + */ + cube(): MathJsChain; + + /** + * Divide two values, x / y. To divide matrices, x is multiplied with + * the inverse of y: x * inv(y). + * @param y Denominator + */ + divide(y: MathType): MathJsChain; + + /** + * Divide two matrices element wise. The function accepts both matrices + * and scalar values. + * @param y Denominator + */ + dotDivide(y: MathType): MathJsChain; + + /** + * Multiply two matrices element wise. The function accepts both + * matrices and scalar values. + * @param y Right hand value + */ + dotMultiply(y: MathType): MathJsChain; + + /** + * Calculates the power of x to y element wise. + * @param y The exponent + */ + dotPow(y: MathType): MathJsChain; + + /** + * Calculate the exponent of a value. For matrices, the function is + * evaluated element wise. + */ + exp(): MathJsChain; + + /** + * Calculate the value of subtracting 1 from the exponential value. For + * matrices, the function is evaluated element wise. + */ + expm1(): MathJsChain; + + /** + * Round a value towards zero. For matrices, the function is evaluated + * element wise. + */ + fix(): MathJsChain; + + /** + * Round a value towards minus infinity. For matrices, the function is + * evaluated element wise. + */ + floor(): MathJsChain; + + /** + * Calculate the greatest common divisor for two or more values or + * arrays. For matrices, the function is evaluated element wise. + */ + gcd(): MathJsChain; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is + * defined as: hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) For + * matrix input, the hypotenusa is calculated for all values in the + * matrix. + */ + hypot(): MathJsChain; + + /** + * Calculate the least common multiple for two or more values or arrays. + * lcm is defined as: lcm(a, b) = abs(a * b) / gcd(a, b) For matrices, + * the function is evaluated element wise. + * @param b An integer number + */ + lcm(b: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Calculate the logarithm of a value. For matrices, the function is + * evaluated element wise. + * @param base Optional base for the logarithm. If not provided, the + * natural logarithm of x is calculated. Default value: e. + */ + log(base?: number | BigNumber | Complex): MathJsChain; + + /** + * Calculate the 10-base of a value. This is the same as calculating + * log(x, 10). For matrices, the function is evaluated element wise. + */ + log10(): MathJsChain; + + /** + * Calculate the logarithm of a value+1. For matrices, the function is + * evaluated element wise. + */ + log1p(base?: number | BigNumber | Complex): MathJsChain; + /** + * Calculate the 2-base of a value. This is the same as calculating + * log(x, 2). For matrices, the function is evaluated element wise. + */ + log2(): MathJsChain; + /** + * Calculates the modulus, the remainder of an integer division. For + * matrices, the function is evaluated element wise. The modulus is + * defined as: x - y * floor(x / y) + * @see http://en.wikipedia.org/wiki/Modulo_operation. + * @param y Divisor + */ + mod(y: number | BigNumber | Fraction | MathArray | Matrix): MathJsChain; + + /** + * Multiply two values, x * y. The result is squeezed. For matrices, the + * matrix product is calculated. + * @param y The second value to multiply + */ + multiply(y: MathType): MathJsChain; + + /** + * Calculate the norm of a number, vector or matrix. The second + * parameter p is optional. If not provided, it defaults to 2. + * @param p Vector space. Supported numbers include Infinity and + * -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The + * Frobenius norm) Default value: 2. + */ + norm(p?: number | BigNumber | string): MathJsChain; + + /** + * Calculate the nth root of a value. The principal nth root of a + * positive real number A, is the positive real solution of the equation + * x^root = A For matrices, the function is evaluated element wise. + * @param root The root. Default value: 2. + */ + nthRoot(root?: number | BigNumber): MathJsChain; + + /** + * Calculates the power of x to y, x ^ y. Matrix exponentiation is + * supported for square matrices x, and positive integer exponents y. + * @param y The exponent + */ + pow(): MathJsChain; + + /** + * Round a value towards the nearest integer. For matrices, the function + * is evaluated element wise. + * @param n Number of decimals Default value: 0. + */ + round(n?: number | BigNumber | MathArray): MathJsChain; + + /** + * Compute the sign of a value. The sign of a value x is: 1 when x > 1 + * -1 when x < 0 0 when x == 0 For matrices, the function is evaluated + * element wise. + * @param x The number for which to determine the sign + * @returns The sign of x + */ + sign(): MathJsChain; + + /** + * Calculate the square root of a value. For matrices, the function is + * evaluated element wise. + */ + sqrt(): MathJsChain; + + /** + * Compute the square of a value, x * x. For matrices, the function is + * evaluated element wise. + */ + square(): MathJsChain; + + /** + * Subtract two values, x - y. For matrices, the function is evaluated + * element wise. + * @param y Value to subtract from x + */ + subtract(y: MathType): MathJsChain; + + /** + * Inverse the sign of a value, apply a unary minus operation. For + * matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real + * and complex value are inverted. + */ + unaryMinus(): MathJsChain; + + /** + * Unary plus operation. Boolean values and strings will be converted to + * a number, numeric values will be returned as is. For matrices, the + * function is evaluated element wise. + */ + unaryPlus(): MathJsChain; + + /** + * Calculate the extended greatest common divisor for two values. See + * http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * @param b An integer number + */ + xgcd(b: number | BigNumber): MathJsChain; + + /************************************************************************* + * Bitwise functions + ************************************************************************/ + + /** + * Bitwise AND two values, x & y. For matrices, the function is + * evaluated element wise. + * @param y Second value to and + */ + bitAnd(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise NOT value, ~x. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the best prefix + * base. + */ + bitNot(): MathJsChain; + + /** + * Bitwise OR two values, x | y. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the lowest + * print base. + * @param y Second value to or + */ + bitOr(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise XOR two values, x ^ y. For matrices, the function is + * evaluated element wise. + * @param y Second value to xor + */ + bitXor(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise left logical shift of a value x by y number of bits, x << y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + leftShift(y: number | BigNumber): MathJsChain; + + /** + * Bitwise right arithmetic shift of a value x by y number of bits, x >> + * y. For matrices, the function is evaluated element wise. For units, + * the function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + rightArithShift(y: number | BigNumber): MathJsChain; + + /** + * Bitwise right logical shift of value x by y number of bits, x >>> y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + rightLogShift(y: number): MathJsChain; + + /************************************************************************* + * Combinatorics functions + ************************************************************************/ + + /** + * The Bell Numbers count the number of partitions of a set. A partition + * is a pairwise disjoint subset of S whose union is S. bellNumbers only + * takes integer arguments. The following condition must be enforced: n + * >= 0 + */ + bellNumbers(): MathJsChain; + + /** + * The Catalan Numbers enumerate combinatorial structures of many + * different types. catalan only takes integer arguments. The following + * condition must be enforced: n >= 0 + */ + catalan(): MathJsChain; + + /** + * The composition counts of n into k parts. Composition only takes + * integer arguments. The following condition must be enforced: k <= n. + * @param k Number of objects in the subset + */ + composition(k: number | BigNumber): MathJsChain; + + /** + * The Stirling numbers of the second kind, counts the number of ways to + * partition a set of n labelled objects into k nonempty unlabelled + * subsets. stirlingS2 only takes integer arguments. The following + * condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = + * 1 + * @param k Number of objects in the subset + */ + stirlingS2(k: number | BigNumber): MathJsChain; + + /************************************************************************* + * Complex functions + ************************************************************************/ + + /** + * Compute the argument of a complex value. For a complex number a + bi, + * the argument is computed as atan2(b, a). For matrices, the function + * is evaluated element wise. + */ + arg(): MathJsChain; + + /** + * Compute the complex conjugate of a complex value. If x = a+bi, the + * complex conjugate of x is a - bi. For matrices, the function is + * evaluated element wise. + */ + conj(): MathJsChain; + + /** + * Get the imaginary part of a complex number. For a complex number a + + * bi, the function returns b. For matrices, the function is evaluated + * element wise. + */ + im(): MathJsChain; + + /** + * Get the real part of a complex number. For a complex number a + bi, + * the function returns a. For matrices, the function is evaluated + * element wise. + */ + re(): MathJsChain; + + /************************************************************************* + * Geometry functions + ************************************************************************/ + + /** + * Calculates: The eucledian distance between two points in 2 and 3 + * dimensional spaces. Distance between point and a line in 2 and 3 + * dimensional spaces. Pairwise distance between a set of 2D or 3D + * points NOTE: When substituting coefficients of a line(a, b and c), + * use ax + by + c = 0 instead of ax + by = c For parametric equation of + * a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, + * c) + * @param y Coordinates of the second point + */ + distance(y: MathArray | Matrix | object): MathJsChain; + + /** + * Calculates the point of intersection of two lines in two or three + * dimensions and of a line and a plane in three dimensions. The inputs + * are in the form of arrays or 1 dimensional matrices. The line + * intersection functions return null if the lines do not meet. Note: + * Fill the plane coefficients as x + y + z = c and not as x + y + z + c + * = 0. + * @param x Co-ordinates of second end-point of first line + * @param y Co-ordinates of first end-point of second line OR + * Coefficients of the plane's equation + * @param z Co-ordinates of second end-point of second line OR null if + * the calculation is for line and plane + */ + intersect( + x: MathArray | Matrix, + y: MathArray | Matrix, + z: MathArray | Matrix + ): MathJsChain; + + /************************************************************************* + * Logical functions + ************************************************************************/ + + /** + * Logical and. Test whether two values are both defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to and + */ + and( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /** + * Logical not. Flips boolean value of a given parameter. For matrices, + * the function is evaluated element wise. + */ + not(): MathJsChain; + + /** + * Logical or. Test if at least one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to or + */ + or( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /** + * Logical xor. Test whether one and only one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to xor + */ + xor( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /************************************************************************* + * Matrix functions + ************************************************************************/ + + /** + * Concatenate two or more matrices. dim: number is a zero-based + * dimension over which to concatenate the matrices. By default the last + * dimension of the matrices. + */ + concat(): MathJsChain; + + /** + * Calculate the cross product for two vectors in three dimensional + * space. The cross product of A = [a1, a2, a3] and B =[b1, b2, b3] is + * defined as: cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 + * * b2 - a2 * b1 ] + * @param y Second vector + */ + cross(y: MathArray | Matrix): MathJsChain; + + /** + * Calculate the determinant of a matrix. + */ + det(): MathJsChain; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix. When x + * is a vector, a matrix with vector x on the diagonal will be returned. + * When x is a two dimensional matrix, the matrixes kth diagonal will be + * returned as vector. When k is positive, the values are placed on the + * super diagonal. When k is negative, the values are placed on the sub + * diagonal. + * @param k The diagonal where the vector will be filled in or + * retrieved. Default value: 0. + * @param format The matrix storage format. Default value: 'dense'. + */ + diag(format?: string): MathJsChain; + diag(k: number | BigNumber, format?: string): MathJsChain; + + /** + * Calculate the dot product of two vectors. The dot product of A = [a1, + * a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as: dot(A, + * B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * @param y Second vector + */ + dot(y: MathArray | Matrix): MathJsChain; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be + * square. Not to be confused with exp(a), which performs element-wise + * exponentiation. The exponential is calculated using the Padé + * approximant with scaling and squaring; see “Nineteen Dubious Ways to + * Compute the Exponential of a Matrix,” by Moler and Van Loan. + */ + expm(): MathJsChain; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. The + * matrix has ones on the diagonal and zeros elsewhere. + * @param format The Matrix storage format + */ + eye(format?: string): MathJsChain; + /** + * @param n The y dimension for the matrix + * @param format The Matrix storage format + */ + eye(n: number, format?: string): MathJsChain; + + /** + * Filter the items in an array or one dimensional matrix. + */ + filter(test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)| RegExp): MathJsChain; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + */ + flatten(): MathJsChain; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + */ + forEach(callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): MathJsChain; + + /** + * Calculate the inverse of a square matrix. + */ + inv(): MathJsChain; /** * Calculate the kronecker product of two matrices or vectors - * @param x First Matrix - * @param y Second Matrix + * @param y Second vector */ - kron(x: Matrix|MathArray, y: Matrix|MathArray): MathJsChain; - - /** - * Calculate the least common multiple for two or more values or arrays. lcm is defined as: - * lcm(a, b) = abs(a * b) / gcd(a, b) - * For matrices, the function is evaluated element wise. - */ - lcm(b: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Calculate the logarithm of a value. For matrices, the function is evaluated element wise. - * @param base Optional base for the logarithm. If not provided, the natural logarithm of x is calculated. Default value: e. - */ - log(base?: number|BigNumber|Complex): MathJsChain; - - /** - * Calculate the 10-base of a value. This is the same as calculating log(x, 10). For matrices, the function is evaluated element wise. - */ - log10(): MathJsChain; - - /** - * Calculates the modulus, the remainder of an integer division. For matrices, the function is evaluated element wise. - * The modulus is defined as: - * x - y * floor(x / y) - * @see http://en.wikipedia.org/wiki/Modulo_operation. - * @param y Divisor - */ - mod(y: number|BigNumber|Fraction|MathArray|Matrix): MathJsChain; - - /** - * Multiply two values, x * y. The result is squeezed. For matrices, the matrix product is calculated. - */ - multiply(y: MathType): MathJsChain; - - /** - * Calculate the norm of a number, vector or matrix. The second parameter p is optional. If not provided, it defaults to 2. - * @param p Vector space. Supported numbers include Infinity and -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) Default value: 2. - */ - norm(p?: number|BigNumber|string): MathJsChain; - - /** - * Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation - * x^root = A - * For matrices, the function is evaluated element wise. - * @param root The root. Default value: 2. - */ - nthRoot(root?: number|BigNumber): MathJsChain; - - /** - * Calculates the power of x to y, x ^ y. Matrix exponentiation is supported for square matrices x, and positive integer exponents y. - * @param y The exponent - */ - pow(y: number|BigNumber|Complex): MathJsChain; - - /** - * Round a value towards the nearest integer. For matrices, the function is evaluated element wise. - * @param n Number of decimals Default value: 0. - */ - round(n?: number|BigNumber|MathArray): MathJsChain; - - /** - * Compute the sign of a value. The sign of a value x is: - * 1 when x > 1 - * -1 when x < 0 - * 0 when x == 0 - * For matrices, the function is evaluated element wise. - */ - sign(): MathJsChain; - - /** - * Calculate the square root of a value. For matrices, the function is evaluated element wise. - */ - sqrt(): MathJsChain; - - /** - * Compute the square of a value, x * x. For matrices, the function is evaluated element wise. - */ - square(): MathJsChain; - - /** - * Subtract two values, x - y. For matrices, the function is evaluated element wise. - */ - subtract(y: MathType): MathJsChain; - - /** - * Inverse the sign of a value, apply a unary minus operation. - * For matrices, the function is evaluated element wise. Boolean values and strings will be converted to a number. For complex numbers, both real and complex value are inverted. - */ - unaryMinus(): MathJsChain; - - /** - * Unary plus operation. Boolean values and strings will be converted to a number, numeric values will be returned as is. - * For matrices, the function is evaluated element wise. - */ - unaryPlus(): MathJsChain; - - /** - * Calculate the extended greatest common divisor for two values. See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. - */ - xgcd(b: number|BigNumber): MathJsChain; - - /** - * Bitwise AND two values, x & y. For matrices, the function is evaluated element wise. - */ - bitAnd(y: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Bitwise NOT value, ~x. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - */ - bitNot(): MathJsChain; - - /** - * Bitwise OR two values, x | y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the lowest print base. - */ - bitOr(): MathJsChain; - - /** - * Bitwise XOR two values, x ^ y. For matrices, the function is evaluated element wise. - */ - bitXor(y: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Bitwise left logical shift of a value x by y number of bits, x << y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - leftShift(y: number|BigNumber): MathJsChain; - - /** - * Bitwise right arithmetic shift of a value x by y number of bits, x >> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightArithShift(y: number|BigNumber): MathJsChain; - - /** - * Bitwise right logical shift of value x by y number of bits, x >>> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightLogShift(y: number): MathJsChain; - - /** - * The Bell Numbers count the number of partitions of a set. - * A partition is a pairwise disjoint subset of S whose union is S. - * bellNumbers only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n Total number of objects in the set - */ - bellNumbers(): MathJsChain; - - /** - * The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n nth Catalan number - */ - catalan(): MathJsChain; - - /** - * The composition counts of n into k parts. Composition only takes integer arguments. The following condition must be enforced: k <= n. - * @param n Total number of objects in the set - * @param k Number of objects in the subset - * @returns Returns the composition counts of n into k parts. - */ - composition(k: number|BigNumber): MathJsChain; - - /** - * The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. - * stirlingS2 only takes integer arguments. The following condition must be enforced: k <= n. - * If n = k or k = 1, then s(n,k) = 1 - * @param n Total number of objects in the set - * @param k Number of objects in the subset - */ - stirlingS2(k: number|BigNumber): MathJsChain; - - /** - * Compute the argument of a complex value. For a complex number a + bi, the argument is computed as atan2(b, a). For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - arg(): MathJsChain; - - /** - * Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate of x is a - bi. For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - conj(): MathJsChain; - - /** - * Get the imaginary part of a complex number. For a complex number a + bi, the function returns b. - * For matrices, the function is evaluated element wise. - */ - im(): MathJsChain; - - /** - * Get the real part of a complex number. For a complex number a + bi, the function returns a. - * For matrices, the function is evaluated element wise. - */ - re(): MathJsChain; - - /** - * Calculates: The eucledian distance between two points in 2 and 3 dimensional spaces. Distance between point - * and a line in 2 and 3 dimensional spaces. Pairwise distance between a set of 2D or 3D points NOTE: When - * substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c For parametric - * equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) - */ - distance(y: MathType): MathJsChain; - - /** - * Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in - * three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions - * return null if the lines do not meet. - * Note: Fill the plane coefficients as x + y + z = c and not as x + y + z + c = 0. - * @param w Co-ordinates of first end-point of first line - * @param x Co-ordinates of second end-point of first line - * @param y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation - * @param z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane - * @returns Returns the point of intersection of lines/lines-planes - */ - intersect(x: MathArray|Matrix, y: MathArray|Matrix, z: MathArray|Matrix): MathJsChain; - - /** - * Logical and. Test whether two values are both defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - and(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Logical not. Flips boolean value of a given parameter. For matrices, the function is evaluated element wise. - */ - not(): MathJsChain; - - /** - * Logical or. Test if at least one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - or(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Logical xor. Test whether one and only one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - xor(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Calculate the cross product for two vectors in three dimensional space. The cross product of A = [a1, a2, a3] - * and B =[b1, b2, b3] is defined as: - * cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ] - */ - cross(y: MathArray|Matrix): MathJsChain; - - /** - * Calculate the determinant of a matrix. - */ - det(): MathJsChain; - - /** - * Resize a matrix - * @param x Matrix to be resized - * @param size One dimensional array with numbers - * @param defaultValue Zero by default, except in case of a string, in that case defaultValue = ' ' Default value: 0. - */ - resize(size: MathArray|Matrix, defaultValue?: number|string): MathJsChain; - - /** - * Calculate the size of a matrix or scalar. - */ - size(): MathJsChain; - - /** - * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. - */ - squeeze(): MathJsChain; - - /** - * Get or set a subset of a matrix or string. - * @param value An array, matrix, or string - * @param index An index containing ranges for each dimension - * @param replacement An array, matrix, or scalar. If provided, the subset is replaced with replacement. If not provided, the subset is returned - * @param defaultValue Default value, filled in on new entries when the matrix is resized. If not provided, math.matrix elements will be left undefined. Default value: undefined. - */ - subset(index: Index, replacement?: any, defaultValue?: any): MathJsChain; - - /** - * Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. - */ - trace(): MathJsChain; - - /** - * Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only two dimensional matrices are supported. - */ - transpose(): MathJsChain; - - /** - * Random pick a value from a one dimensional array. Array element is picked using a random function with uniform distribution. - */ - pickRandom(): MathJsChain; - - /** - * Return a random number larger or equal to min and smaller than max using a uniform distribution. - */ - random(min?: number, max?: number): MathJsChain; - - /** - * Return a random integer number larger or equal to min and smaller than max using a uniform distribution. - */ - randomInt(min?: number, max?: number): MathJsChain; - - /** - * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. - * x and y are considered equal when the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - compare(y: MathType): MathJsChain; - - /** - * Test element wise whether two matrices are equal. The function accepts both matrices and scalar values. - */ - deepEqual(y: MathType): MathJsChain; - - /** - * Test whether two values are equal. - * The function tests whether the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. - * Values null and undefined are compared strictly, thus null is only equal to null and nothing else, and undefined is only equal to undefined and nothing else. - */ - equal(y: MathType): MathJsChain; - - /** - * Test whether value x is larger than y. - * The function returns true when x is larger than y and the relative difference between x and y is larger than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - larger(y: MathType): MathJsChain; - - /** - * Test whether value x is larger or equal to y. - * The function returns true when x is larger than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - largerEq(y: MathType): MathJsChain; - - /** - * Test whether value x is smaller than y. - * The function returns true when x is smaller than y and the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - smaller(MathJsChainy: MathType): MathJsChain; - - /** - * Test whether value x is smaller or equal to y. - * The function returns true when x is smaller than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. For matrices, the function is evaluated element wise. - */ - smallerEq(MathJsChainy: MathType): MathJsChain; - - /** - * Test whether two values are unequal. - * The function tests whether the relative difference between x and y is larger than the configured epsilon. The function cannot - * be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. - * Values null and undefined are compared strictly, thus null is unequal with everything except null, and undefined is unequal with - * everything except undefined. - */ - unequal(MathJsChainy: MathType): MathJsChain; - - /** - * Compute the maximum value of a matrix or a list with values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - max(dim?: number): MathJsChain; - - /** - * Compute the mean value of matrix or a list with values. In case of a multi dimensional array, the mean of the flattened array will be - * calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - mean(dim?: number): MathJsChain; - - /** - * Compute the median of a matrix or a list with values. The values are sorted and the middle value is returned. In case of an - * even number of values, the average of the two middle values is returned. Supported types of values are: Number, BigNumber, Unit - * In case of a (multi dimensional) array or matrix, the median of all elements will be calculated. - */ - median(): MathJsChain; - - /** - * Compute the maximum value of a matrix or a list of values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - min(dim?: number): MathJsChain; - - /** - * Computes the mode of a set of numbers or a list with values(numbers or characters). If there are more than one modes, it returns a list of those values. - */ - mode(): MathJsChain; - - /** - * Compute the product of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - prod(): MathJsChain; - - /** - * Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. - * Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber - * In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated. - */ - quantileSeq(prob: number|BigNumber|MathArray, sorted?: boolean): MathJsChain; - - /** - * Compute the standard deviation of a matrix or a list with values. The standard deviations is defined as the square root of the - * variance: std(A) = sqrt(var(A)). In case of a (multi dimensional) array or matrix, the standard deviation over all elements will - * be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the following - * values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - */ - std(normalization?: string): MathJsChain; - - /** - * Compute the sum of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - sum(): MathJsChain; - - /** - * Compute the variance of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the variance over all - * elements will be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the - * following values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - * Note that older browser may not like the variable name var. In that case, the function can be called as math['var'](...) - * instead of math.var(...). - */ - var(normalization?: string): MathJsChain; - - /** - * Calculate the inverse cosine of a value. For matrices, the function is evaluated element wise. - */ - acos(): MathJsChain; - - /** - * Calculate the hyperbolic arccos of a value, defined as acosh(x) = ln(sqrt(x^2 - 1) + x). - * For matrices, the function is evaluated element wise. - */ - acosh(): MathJsChain; - - /** - * Calculate the inverse cotangent of a value. For matrices, the function is evaluated element wise. - */ - acot(): MathJsChain; - - /** - * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2. - * For matrices, the function is evaluated element wise. - */ - acoth(): MathJsChain; - - /** - * Calculate the inverse cosecant of a value. For matrices, the function is evaluated element wise. - */ - acsc(): MathJsChain; - - /** - * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) = ln(1/x + sqrt(1/x^2 + 1)). - * For matrices, the function is evaluated element wise. - */ - acsch(): MathJsChain; - - /** - * Calculate the inverse secant of a value. For matrices, the function is evaluated element wise. - */ - asec(): MathJsChain; - - /** - * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated element wise. - */ - asech(): MathJsChain; - - /** - * Calculate the inverse sine of a value. For matrices, the function is evaluated element wise. - */ - asin(): MathJsChain; - - /** - * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated element wise. - */ - asinh(): MathJsChain; - - /** - * Calculate the inverse tangent of a value. For matrices, the function is evaluated element wise. - */ - atan(): MathJsChain; - - /** - * Calculate the inverse tangent function with two arguments, y/x. By providing two arguments, the right quadrant of the - * computed angle can be determined. - * For matrices, the function is evaluated element wise. - */ - atan2(x: number|MathArray|Matrix): MathJsChain; - - /** - * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = ln((1 + x)/(1 - x)) / 2. - * For matrices, the function is evaluated element wise. - */ - atanh(): MathJsChain; - - /** - * Calculate the cosine of a value. For matrices, the function is evaluated element wise. - */ - asin(): MathJsChain; // tslint:disable-line adjacent-overload-signatures - - /** - * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 * (exp(x) + exp(-x)). For matrices, the function is evaluated element wise. - */ - cosh(): MathJsChain; - - /** - * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). For matrices, the function is evaluated element wise. - */ - cot(): MathJsChain; - - /** - * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 / tanh(x). For matrices, the function is evaluated element wise. - */ - coth(): MathJsChain; - - /** - * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For matrices, the function is evaluated element wise. - */ - csc(): MathJsChain; - - /** - * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 / sinh(x). For matrices, the function is evaluated element wise. - */ - csch(): MathJsChain; - - /** - * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For matrices, the function is evaluated element wise. - */ - sec(): MathJsChain; - - /** - * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / cosh(x). For matrices, the function is evaluated element wise. - */ - sech(): MathJsChain; - - /** - * Calculate the sine of a value. For matrices, the function is evaluated element wise. - */ - sin(): MathJsChain; - - /** - * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * (exp(x) - exp(-x)). For matrices, the function is evaluated element wise. - */ - sinh(): MathJsChain; - - /** - * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). For matrices, the function is evaluated element wise. - */ - tan(): MathJsChain; - - /** - * Calculate the hyperbolic tangent of a value, defined as tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is evaluated element wise. - */ - tanh(): MathJsChain; - - /** - * Change the unit of a value. For matrices, the function is evaluated element wise. - * @param x The unit to be converted. - * @param unit New unit. Can be a string like "cm" or a unit without value. - */ - to(unit: Unit|string): MathJsChain; - - /** - * Clone an object. - */ - clone(): MathJsChain; - - /** - * Filter the items in an array or one dimensional matrix. - * @param x A one dimensional matrix or array to filter - * @param test - */ - filter(test: RegExp|((item: any) => boolean)): MathJsChain; - - /** - * Format a value of any type into a string. - */ - format(options?: FormatOptions|number|((item: any) => string)): MathJsChain; - - /** - * Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array. - * @param callback The callback method is invoked with three parameters: the value of the element, the index of the element, and the matrix being traversed. - */ - map(callback: (item: any) => any): MathJsChain; - - /** - * Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. - * @param k The kth smallest value to be retrieved; zero-based index - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - * @returns Returns the kth lowest value. - */ - partitionSelect(k: number, compare?: string|((a: any, b: any) => number)): MathJsChain; - - /** - * Sort the items in a matrix. - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - */ - sort(compare?: string|((a: any, b: any) => number)): MathJsChain; - - done(): any; - valueOf(): any; - toString(): string; - } + kron(y: Matrix | MathArray): MathJsChain; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + */ + map(callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): MathJsChain; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * @param format The matrix storage format + */ + ones(format?: string): MathJsChain; + /** + * @param format The matrix storage format + */ + ones(n: number, format?: string): MathJsChain; + /** + * Partition-based selection of an array or 1D matrix. Will find the kth + * smallest value, and mutates the input array. Uses Quickselect. + * @param k The kth smallest value to be retrieved; zero-based index + * @param compare An optional comparator function. The function is + * called as compare(a, b), and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. Default value: 'asc'. + */ + partitionSelect( + k: number, + compare?: "asc" | "desc" | ((a: any, b: any) => number) + ): MathJsChain; + + /** + * Create an array from a range. By default, the range end is excluded. + * This can be customized by providing an extra parameter includeEnd. + * @param end End of the range, excluded by default, included when + * parameter includeEnd=true + * @param step Step size. Default value is 1. + * @param includeEnd: Option to specify whether to include the end or + * not. False by default + */ + range(includeEnd?: boolean): Matrix; + range(end: number | BigNumber, includeEnd?: boolean): MathJsChain; + range( + end: number | BigNumber, + step: number | BigNumber, + includeEnd?: boolean + ): MathJsChain; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * @param sizes One dimensional array with integral sizes for each + * dimension + */ + reshape(sizes: number[]): MathJsChain; + + /** + * Resize a matrix + * @param size One dimensional array with numbers + * @param defaultValue Zero by default, except in case of a string, in + * that case defaultValue = ' ' Default value: 0. + */ + resize( + size: MathArray | Matrix, + defaultValue?: number | string + ): MathJsChain; + + /** + * Calculate the size of a matrix or scalar. + */ + size(): MathJsChain; + + /** + * Sort the items in a matrix + * @param compare An optional _comparator function or name. The function + * is called as compare(a, b), and must return 1 when a > b, -1 when a < + * b, and 0 when a == b. Default value: ‘asc’ + */ + sort(compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural"): MathJsChain; + + /** + * Calculate the principal square root of a square matrix. The principal + * square root matrix X of another matrix A is such that X * X = A. + */ + sqrtm(): MathJsChain; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a + * matrix. + */ + squeeze(): MathJsChain; + + /** + * Get or set a subset of a matrix or string. + * @param index An index containing ranges for each dimension + * @param replacement An array, matrix, or scalar. If provided, the + * subset is replaced with replacement. If not provided, the subset is + * returned + * @param defaultValue Default value, filled in on new entries when the + * matrix is resized. If not provided, math.matrix elements will be left + * undefined. Default value: undefined. + */ + subset( + index: Index, + replacement?: any, + defaultValue?: any + ): MathJsChain; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + */ + trace(): MathJsChain; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only two dimensional matrices are supported. + */ + transpose(): MathJsChain; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(format?: string): MathJsChain; + /** + * @param n The y dimension of the matrix + * @param format The matrix storage format + */ + zeros(n: number, format?: string): MathJsChain; + + /************************************************************************* + * Probability functions + ************************************************************************/ + + /** + * Compute the number of ways of picking k unordered outcomes from n + * possibilities. Combinations only takes integer arguments. The + * following condition must be enforced: k <= n. + * @param k Number of objects in the subset + */ + combinations(k: number | BigNumber): MathJsChain; + + /** + * Compute the factorial of a value Factorial only supports an integer + * value as argument. For matrices, the function is evaluated element + * wise. + */ + factorial(): MathJsChain; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large + * values. For matrices, the function is evaluated element wise. + */ + gamma(): MathJsChain; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two + * distributions + * @param p Second vector + */ + kldivergence(p: MathArray | Matrix): MathJsChain; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, + * a2, ..., ai unordered outcomes from n possibilities. multinomial + * takes one array of integers as an argument. The following condition + * must be enforced: every ai <= 0 + */ + multinomial(): MathJsChain; + + /** + * Compute the number of ways of obtaining an ordered subset of k + * elements from a set of n elements. Permutations only takes integer + * arguments. The following condition must be enforced: k <= n. + * @param k The number of objects in the subset + */ + permutations(k?: number | BigNumber): MathJsChain; + + /** + * Random pick a value from a one dimensional array. Array element is + * picked using a random function with uniform distribution. + * @param number An int or float + * @param weights An array of ints or floats + */ + pickRandom(number?: number, weights?: number[]): MathJsChain; + + /** + * Return a random number larger or equal to min and smaller than max + * using a uniform distribution. + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + */ + // tslint:disable-next-line unified-signatures + random(max?: number): MathJsChain; + // tslint:disable-next-line unified-signatures + random(min: number, max: number): MathJsChain; + + /** + * Return a random integer number larger or equal to min and smaller + * than max using a uniform distribution. + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + */ + // tslint:disable-next-line unified-signatures + randomInt(max?: number): MathJsChain; + // tslint:disable-next-line unified-signatures + randomInt(min: number, max: number): MathJsChain; + + /************************************************************************* + * Relational functions + ************************************************************************/ + + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x + * == y. x and y are considered equal when the relative difference + * between x and y is smaller than the configured epsilon. The function + * cannot be used to compare values smaller than approximately 2.22e-16. + * For matrices, the function is evaluated element wise. + * @param y Second value to compare + */ + compare(y: MathType | string): MathJsChain; + + /** + * Compare two values of any type in a deterministic, natural way. For + * numeric values, the function works the same as math.compare. For + * types of values that can’t be compared mathematically, the function + * compares in a natural way. + * @param y Second value to compare + */ + compareNatural(y: any): MathJsChain; + + /** + * Compare two strings lexically. Comparison is case sensitive. Returns + * 1 when x > y, -1 when x < y, and 0 when x == y. For matrices, the + * function is evaluated element wise. + * @param y Second string to compare + */ + compareText(y: string | MathArray | Matrix): MathJsChain; + + /** + * Test element wise whether two matrices are equal. The function + * accepts both matrices and scalar values. + * @param y Second amtrix to compare + */ + deepEqual(y: MathType): MathJsChain; + + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. In case of complex numbers, x.re + * must equal y.re, and x.im must equal y.im. Values null and undefined + * are compared strictly, thus null is only equal to null and nothing + * else, and undefined is only equal to undefined and nothing else. + * @param y Second value to compare + */ + equal(y: MathType | string): MathJsChain; + + /** + * Check equality of two strings. Comparison is case sensitive. For + * matrices, the function is evaluated element wise. + * @param y Second string to compare + */ + equalText(y: string | MathArray | Matrix): MathJsChain; + + /** + * Test whether value x is larger than y. The function returns true when + * x is larger than y and the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. + * @param y Second value to compare + */ + larger(y: MathType | string): MathJsChain; + + /** + * Test whether value x is larger or equal to y. The function returns + * true when x is larger than y or the relative difference between x and + * y is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param y Second value to vcompare + */ + largerEq(y: MathType | string): MathJsChain; + + /** + * Test whether value x is smaller than y. The function returns true + * when x is smaller than y and the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param y Second value to vcompare + */ + smaller(y: MathType | string): MathJsChain; + + /** + * Test whether value x is smaller or equal to y. The function returns + * true when x is smaller than y or the relative difference between x + * and y is smaller than the configured epsilon. The function cannot be + * used to compare values smaller than approximately 2.22e-16. For + * matrices, the function is evaluated element wise. + * @param y Second value to compare + */ + smallerEq(y: MathType | string): MathJsChain; + + /** + * Test whether two values are unequal. The function tests whether the + * relative difference between x and y is larger than the configured + * epsilon. The function cannot be used to compare values smaller than + * approximately 2.22e-16. For matrices, the function is evaluated + * element wise. In case of complex numbers, x.re must unequal y.re, or + * x.im must unequal y.im. Values null and undefined are compared + * strictly, thus null is unequal with everything except null, and + * undefined is unequal with everything except undefined. + * @param y Second value to vcompare + */ + unequal(y: MathType | string): MathJsChain; + + /************************************************************************* + * Set functions + ************************************************************************/ + + /** + * Create the cartesian product of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a2 A (multi)set + */ + setCartesian(a2: MathArray | Matrix): MathJsChain; + + /** + * Create the difference of two (multi)sets: every element of set1, that + * is not the element of set2. Multi-dimension arrays will be converted + * to single-dimension arrays before the operation + * @param a2 A (multi)set + */ + setDifference(a2: MathArray | Matrix): MathJsChain; + + /** + * Collect the distinct elements of a multiset. A multi-dimension array + * will be converted to a single-dimension array before the operation. + */ + setDistinct(): MathJsChain; + + /** + * Create the intersection of two (multi)sets. Multi-dimension arrays + * will be converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setIntersect(a2: MathArray | Matrix): MathJsChain; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every + * element of set1 is the element of set2.) Multi-dimension arrays will + * be converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setIsSubset(a2: MathArray | Matrix): MathJsChain; + + /** + * Count the multiplicity of an element in a multiset. A multi-dimension + * array will be converted to a single-dimension array before the + * operation. + * @param a A multiset + */ + setMultiplicity(a: MathArray | Matrix): MathJsChain; + + /** + * Create the powerset of a (multi)set. (The powerset contains very + * possible subsets of a (multi)set.) A multi-dimension array will be + * converted to a single-dimension array before the operation. + */ + setPowerset(): MathJsChain; + + /** + * Count the number of elements of a (multi)set. When a second parameter + * is ‘true’, count only the unique values. A multi-dimension array will + * be converted to a single-dimension array before the operation. + */ + setSize(): MathJsChain; + + /** + * Create the symmetric difference of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a2 A (multi)set + */ + setSymDifference(a2: MathArray | Matrix): MathJsChain; + + /** + * Create the union of two (multi)sets. Multi-dimension arrays will be + * converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setUnion(a2: MathArray | Matrix): MathJsChain; + + /************************************************************************* + * Special functions + ************************************************************************/ + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + */ + erf(): MathJsChain; + + /************************************************************************* + * Statistics functions + ************************************************************************/ + + /** + * Compute the median absolute deviation of a matrix or a list with + * values. The median absolute deviation is defined as the median of the + * absolute deviations from the median. + */ + mad(): MathJsChain; + + /** + * Compute the maximum value of a matrix or a list with values. In case + * of a multi dimensional array, the maximum of the flattened array will + * be calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The maximum over the selected dimension + */ + max(dim?: number): MathJsChain; + + /** + * Compute the mean value of matrix or a list with values. In case of a + * multi dimensional array, the mean of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The mean over the selected dimension + */ + mean(dim?: number): MathJsChain; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. Supported + * types of values are: Number, BigNumber, Unit In case of a (multi + * dimensional) array or matrix, the median of all elements will be + * calculated. + */ + median(): MathJsChain; + + /** + * Compute the maximum value of a matrix or a list of values. In case of + * a multi dimensional array, the maximum of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The minimum over the selected dimension + */ + min(dim?: number): MathJsChain; + + /** + * Computes the mode of a set of numbers or a list with values(numbers + * or characters). If there are more than one modes, it returns a list + * of those values. + */ + mode(): MathJsChain; + + /** + * Compute the product of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + */ + prod(): MathJsChain; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. Supported + * types of sequence values are: Number, BigNumber, Unit Supported types + * of probability are: Number, BigNumber In case of a (multi + * dimensional) array or matrix, the prob order quantile of all elements + * will be calculated. + * @param probOrN prob is the order of the quantile, while N is the + * amount of evenly distributed steps of probabilities; only one of + * these options can be provided + * @param sorted =false is data sorted in ascending order + */ + quantileSeq( + prob: number | BigNumber | MathArray, + sorted?: boolean + ): MathJsChain; + + /** + * Compute the standard deviation of a matrix or a list with values. The + * standard deviations is defined as the square root of the variance: + * std(A) = sqrt(var(A)). In case of a (multi dimensional) array or + * matrix, the standard deviation over all elements will be calculated. + * Optionally, the type of normalization can be specified as second + * parameter. The parameter normalization can be one of the following + * values: 'unbiased' (default) The sum of squared errors is divided by + * (n - 1) 'uncorrected' The sum of squared errors is divided by n + * 'biased' The sum of squared errors is divided by (n + 1) + * @param array A single matrix or multiple scalar values + * @param normalization Determines how to normalize the variance. Choose + * ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. Default value: + * ‘unbiased’. + * @returns The standard deviation + */ + std( + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): MathJsChain; + + /** + * Compute the sum of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + */ + sum(): MathJsChain; + + /** + * Compute the variance of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the variance over all elements + * will be calculated. Optionally, the type of normalization can be + * specified as second parameter. The parameter normalization can be one + * of the following values: 'unbiased' (default) The sum of squared + * errors is divided by (n - 1) 'uncorrected' The sum of squared errors + * is divided by n 'biased' The sum of squared errors is divided by (n + + * 1) Note that older browser may not like the variable name var. In + * that case, the function can be called as math['var'](...) instead of + * math.var(...). + * @param normalization normalization Determines how to normalize the + * variance. Choose ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. + * Default value: ‘unbiased’. + * @returns The variance + */ + var( + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): MathJsChain; + + /************************************************************************* + * String functions + ************************************************************************/ + + /** + * Format a value of any type into a string. + * @param options An object with formatting options. + * @param callback A custom formatting function, invoked for all numeric + * elements in value, for example all elements of a matrix, or the real + * and imaginary parts of a complex number. This callback can be used to + * override the built-in numeric notation with any type of formatting. + * Function callback is called with value as parameter and must return a + * string. + * @see http://mathjs.org/docs/reference/functions/format.html + */ + format( + value: any, + options?: FormatOptions | number | ((item: any) => string), + callback?: ((value: any) => string) + ): MathJsChain; + + /** + * Interpolate values into a string template. + * @param values An object containing variables which will be filled in + * in the template. + * @param precision Number of digits to format numbers. If not provided, + * the value will not be rounded. + * @param options Formatting options, or the number of digits to format + * numbers. See function math.format for a description of all options. + */ + print( + values: any, + precision?: number, + options?: number | object + ): MathJsChain; + + /************************************************************************* + * Trigonometry functions + ************************************************************************/ + + /** + * Calculate the inverse cosine of a value. For matrices, the function + * is evaluated element wise. + */ + acos(): MathJsChain; + + /** + * Calculate the hyperbolic arccos of a value, defined as acosh(x) = + * ln(sqrt(x^2 - 1) + x). For matrices, the function is evaluated + * element wise. + */ + acosh(): MathJsChain; + + /** + * Calculate the inverse cotangent of a value. For matrices, the + * function is evaluated element wise. + */ + acot(): MathJsChain; + + /** + * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) + * = (ln((x+1)/x) + ln(x/(x-1))) / 2. For matrices, the function is + * evaluated element wise. + */ + acoth(): MathJsChain; + + /** + * Calculate the inverse cosecant of a value. For matrices, the function + * is evaluated element wise. + */ + acsc(): MathJsChain; + + /** + * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) + * = ln(1/x + sqrt(1/x^2 + 1)). For matrices, the function is evaluated + * element wise. + */ + acsch(): MathJsChain; + + /** + * Calculate the inverse secant of a value. For matrices, the function + * is evaluated element wise. + */ + asec(): MathJsChain; + + /** + * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = + * ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated + * element wise. + */ + asech(): MathJsChain; + + /** + * Calculate the inverse sine of a value. For matrices, the function is + * evaluated element wise. + */ + asin(): MathJsChain; + + /** + * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = + * ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated + * element wise. + */ + asinh(): MathJsChain; + + /** + * Calculate the inverse tangent of a value. For matrices, the function + * is evaluated element wise. + */ + atan(): MathJsChain; + + /** + * Calculate the inverse tangent function with two arguments, y/x. By + * providing two arguments, the right quadrant of the computed angle can + * be determined. For matrices, the function is evaluated element wise. + */ + atan2(): MathJsChain; + + /** + * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = + * ln((1 + x)/(1 - x)) / 2. For matrices, the function is evaluated + * element wise. + */ + atanh(): MathJsChain; + + /** + * Calculate the cosine of a value. For matrices, the function is + * evaluated element wise. + */ + cos(): MathJsChain; + + /** + * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 + * * (exp(x) + exp(-x)). For matrices, the function is evaluated element + * wise. + */ + cosh(): MathJsChain; + + /** + * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). + * For matrices, the function is evaluated element wise. + */ + cot(): MathJsChain; + + /** + * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 + * / tanh(x). For matrices, the function is evaluated element wise. + */ + coth(): MathJsChain; + + /** + * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For + * matrices, the function is evaluated element wise. + */ + csc(): MathJsChain; + + /** + * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 + * / sinh(x). For matrices, the function is evaluated element wise. + */ + csch(): MathJsChain; + + /** + * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For + * matrices, the function is evaluated element wise. + */ + sec(): MathJsChain; + + /** + * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / + * cosh(x). For matrices, the function is evaluated element wise. + */ + sech(): MathJsChain; + + /** + * Calculate the sine of a value. For matrices, the function is + * evaluated element wise. + */ + sin(): MathJsChain; + + /** + * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * + * (exp(x) - exp(-x)). For matrices, the function is evaluated element + * wise. + */ + sinh(): MathJsChain; + + /** + * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). + * For matrices, the function is evaluated element wise. + */ + tan(): MathJsChain; + + /** + * Calculate the hyperbolic tangent of a value, defined as tanh(x) = + * (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is + * evaluated element wise. + */ + tanh(): MathJsChain; + + /************************************************************************* + * Unit functions + ************************************************************************/ + + /** + * Change the unit of a value. For matrices, the function is evaluated + * element wise. + * @param unit New unit. Can be a string like "cm" or a unit without + * value. + */ + to(unit: Unit | string): MathJsChain; + + /************************************************************************* + * Utils functions + ************************************************************************/ + + /** + * Clone an object. + */ + clone(): MathJsChain; + + /** + * Test whether a value is an integer number. The function supports + * number, BigNumber, and Fraction. The function is evaluated + * element-wise in case of Array or Matrix input. + */ + isInteger(): MathJsChain; + + /** + * Test whether a value is NaN (not a number). The function supports + * types number, BigNumber, Fraction, Unit and Complex. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isNaN(): MathJsChain; + + /** + * Test whether a value is negative: smaller than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isNegative(): MathJsChain; + + /** + * Test whether a value is an numeric value. The function is evaluated + * element-wise in case of Array or Matrix input. + */ + isNumeric(): MathJsChain; + + /** + * Test whether a value is positive: larger than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isPositive(): MathJsChain; + + /** + * Test whether a value is prime: has no divisors other than itself and + * one. The function supports type number, bignumber. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isPrime(): MathJsChain; + + /** + * Test whether a value is zero. The function can check for zero for + * types number, BigNumber, Fraction, Complex, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isZero(): MathJsChain; + + /** + * Determine the type of a variable. + */ + typeof(): MathJsChain; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 6cf43dc698..c1e32a7d9a 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -33,7 +33,7 @@ Bignumbers examples { // configure the default type of numbers as BigNumbers math.config({ - number: 'bignumber', + number: 'BigNumber', precision: 20, }); @@ -108,16 +108,13 @@ Complex numbers examples // create a complex number from polar coordinates { - const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 }; - const c: math.Complex = math - .complex(p); + const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 }; + const c: math.Complex = math.complex(p); } // get polar coordinates of a complex number { - const p: math.PolarCoordinates = math - .complex(3, 4) - .toPolar(); + const p: math.PolarCoordinates = math.complex(3, 4).toPolar(); } } @@ -175,6 +172,11 @@ Expressions examples // get and set variables and functions { + parser.eval('x = 7 / 2'); // 3.5 + parser.eval('x + 3'); // 6.5 + parser.eval('f(x, y) = x^y'); // f(x, y) + parser.eval('f(2, 3)'); // 8 + const x = parser.get('x'); const f = parser.get('f'); const g = f(3, 3); @@ -193,7 +195,7 @@ Fractions examples { // configure the default type of numbers as Fractions math.config({ - number: 'fraction', + number: 'Fraction', }); const x = math.fraction(0.125); @@ -205,9 +207,6 @@ Fractions examples // output formatting const a = math.fraction('2/3'); - console.log(math.format(a)); - console.log(math.format(a, {fraction: 'ratio'})); - console.log(math.format(a, {fraction: 'decimal'})); } /* @@ -237,7 +236,8 @@ Matrices examples b.subset(math.index(1, [0, 1]), [[7, 8]]); const c = math.multiply(a, b); - const d: math.Matrix = c.subset(math.index(1, 0)); + const f: math.Matrix = math.matrix([1, 0]); + const d: math.Matrix = f.subset(math.index(1, 0)); } // get a sub matrix @@ -282,8 +282,9 @@ Sparse matrices examples // do operations with a sparse matrix const b = math.multiply(a, a); const c = math.multiply(b, math.complex(2, 2)); - const d = math.transpose(c); - const e = math.multiply(d, a); + const d = math.matrix([0, 1]); + const e = math.transpose(d); + const f = math.multiply(e, a); } /* @@ -299,8 +300,8 @@ Units examples math.createUnit('foo'); math.createUnit('furlong', '220 yards'); math.createUnit('furlong', '220 yards', {override: true}); - math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67}); - math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67}, {override: true}); + math.createUnit('testunit', {definition: '0.555556 kelvin', offset: 459.67}); + math.createUnit('testunit', {definition: '0.555556 kelvin', offset: 459.67}, {override: true}); math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']}); math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']}, {override: true}); math.createUnit('knot', { @@ -309,7 +310,7 @@ Units examples prefixes: 'long' }, {override: true}); math.createUnit({ - foo: { + foo_2: { prefixes: 'long' }, bar: '40 foo', @@ -365,3 +366,15 @@ Expression tree examples } }); } + +/* +JSON serialization/deserialization +*/ +{ + const data = { + bigNumber: math.bignumber('1.5') + }; + const stringified = JSON.stringify(data); + const parsed = JSON.parse(stringified, math.json.reviver); + parsed.bigNumber === math.bignumber('1.5'); // true +} diff --git a/types/maxmind/index.d.ts b/types/maxmind/index.d.ts index da45eb907b..c93c59a72a 100644 --- a/types/maxmind/index.d.ts +++ b/types/maxmind/index.d.ts @@ -68,6 +68,11 @@ export declare interface Response { readonly names: Translations; }; readonly postal?: { code: string }; + readonly isp?: { + readonly isp: string; + readonly autonomous_system_number: number; + }; + readonly connection?: { connection_type: string }; } export declare interface Translations { diff --git a/types/memoize-one/index.d.ts b/types/memoize-one/index.d.ts index caac3a4429..71f785e73c 100644 --- a/types/memoize-one/index.d.ts +++ b/types/memoize-one/index.d.ts @@ -1,12 +1,9 @@ // Type definitions for memoize-one 3.1 // Project: https://github.com/alexreardon/memoize-one#readme -// Definitions by: Karol Majewski +// Definitions by: Karol Majewski , Frank Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = memoizeOne; +declare function memoizeOne any>(resultFn: T, isEqual?: EqualityFn): T; +export type EqualityFn = (a: any, b: any) => boolean; -declare function memoizeOne any>(resultFn: T, isEqual?: memoizeOne.EqualityFn): T; - -declare namespace memoizeOne { - type EqualityFn = (a: any, b: any) => boolean; -} +export default memoizeOne; diff --git a/types/memoize-one/memoize-one-tests.ts b/types/memoize-one/memoize-one-tests.ts index 7ab20ac891..4feddf6e57 100644 --- a/types/memoize-one/memoize-one-tests.ts +++ b/types/memoize-one/memoize-one-tests.ts @@ -1,4 +1,4 @@ -import memoizeOne = require('memoize-one'); +import memoizeOne, { EqualityFn } from 'memoize-one'; declare function add(a: number, b: number): number ; declare function lousyEqualityFn(a: any, b: any): boolean; @@ -30,4 +30,4 @@ memoizeOne(add, (a: string, b: string) => 0); // $ExpectError /** * The `EqualityFn` type is publicly accessible. */ -const simpleIsEqual: memoizeOne.EqualityFn = (x: number, y: number): boolean => (x === y); +const simpleIsEqual: EqualityFn = (x: number, y: number): boolean => (x === y); diff --git a/types/meteor/meteor-tests.ts b/types/meteor/meteor-tests.ts index f9cf039c84..a321e4a409 100644 --- a/types/meteor/meteor-tests.ts +++ b/types/meteor/meteor-tests.ts @@ -781,3 +781,8 @@ DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); DDPRateLimiter.addRule({ userId: userId => userId == 'foo' }, 5, 1000); Template.instance().autorun(() => { }).stop(); + +// Mongo Collection without connection (local collection) +const collectionWithoutConnection = new Mongo.Collection("monkey", { + connection: null +}); diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 248f5a22af..771d24edc1 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -124,7 +124,7 @@ declare module Mongo { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; @@ -348,7 +348,7 @@ declare module "meteor/mongo" { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; diff --git a/types/microrouter/index.d.ts b/types/microrouter/index.d.ts index 934affd630..c4927ecf9b 100644 --- a/types/microrouter/index.d.ts +++ b/types/microrouter/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for microrouter 2.2 +// Type definitions for microrouter 3.1 // Project: https://github.com/pedronauck/micro-router#readme // Definitions by: Mathieu Dutour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,6 +21,7 @@ export type AugmentedRequestHandler = ( export type RouteHandler = (path: string, handler: AugmentedRequestHandler) => RequestHandler; export function router(...routes: RequestHandler[]): RequestHandler; +export function withNamespace(namespace: string): (...routes: RequestHandler[]) => RequestHandler; export const get: RouteHandler; export const post: RouteHandler; diff --git a/types/mocha/UNUSED_FILES.txt b/types/mocha/UNUSED_FILES.txt deleted file mode 100644 index 2c70329a00..0000000000 --- a/types/mocha/UNUSED_FILES.txt +++ /dev/null @@ -1,2 +0,0 @@ -mocha-node.d.ts -mocha-node-tests.ts \ No newline at end of file diff --git a/types/mocha/index.d.ts b/types/mocha/index.d.ts index 2dd6bb2c21..1ada77c0a4 100644 --- a/types/mocha/index.d.ts +++ b/types/mocha/index.d.ts @@ -9,261 +9,2146 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 +export = Mocha; +export as namespace Mocha; + /** - * Mocha is using node.js EventEmitter for its internal classes - * But when it's executed in the browser environment it bundles a 3rd party EventEmitter in its code - * Also node.js EventEmitter brings its globals which cannot be used in the browser environment. - * So it's unsafe to reference node EventEmitter here, that's why we have a generic interface for EventEmitter. + * Mocha API * - * @see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/25117#issuecomment-383404187 + * @see https://mochajs.org/api/mocha */ -declare class GenericEventEmitter { - addListener(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - on(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - once(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - removeListener(event: string, listener: (...args: any[]) => void): GenericEventEmitter; - removeAllListeners(event?: string): GenericEventEmitter; - emit(event: string, ...args: any[]): boolean; - } +declare class Mocha { + private _growl; + private _reporter; + private _ui; - interface MochaSetupOptions { - // milliseconds to wait before considering a test slow - slow?: number; + constructor(options?: Mocha.MochaOptions); - // timeout in milliseconds - timeout?: number; - - // ui name "bdd", "tdd", "exports" etc - ui?: Mocha.Interface; - - // array of accepted globals - globals?: any[]; - - // reporter instance (function or string), defaults to `mocha.reporters.Spec` - reporter?: string | ReporterConstructor; - - // bail on the first test failure - bail?: boolean; - - // ignore global leaks - ignoreLeaks?: boolean; - - // grep string or regexp to filter tests with - grep?: any; - - // require modules before running tests - require?: string[]; - - asyncOnly?: boolean; - delay?: boolean; - files?: string[]; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; - } - - declare const mocha: Mocha; - declare const describe: Mocha.IContextDefinition; - declare const xdescribe: Mocha.IContextDefinition; - // alias for `describe` - declare const context: Mocha.IContextDefinition; - // alias for `describe` - declare const suite: Mocha.IContextDefinition; - declare const it: Mocha.ITestDefinition; - declare const xit: Mocha.ITestDefinition; - // alias for `it` - declare const test: Mocha.ITestDefinition; - declare const specify: Mocha.ITestDefinition; - - // Used with the --delay flag; see https://mochajs.org/#hooks - declare function run(): void; - - type MochaDone = (error?: any) => void; - - declare function setup(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function teardown(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function suiteSetup(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function suiteTeardown(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function before(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function before(description: string, callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function after(callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function after(description: string, callback: (this: Mocha.IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - declare function beforeEach(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function beforeEach(description: string, callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function afterEach(callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - declare function afterEach(description: string, callback: (this: Mocha.IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - - interface ReporterConstructor { - new(runner: Mocha.IRunner, options: any): any; - } - - declare class Mocha { - currentTest: Mocha.ITestDefinition; - suite: Mocha.ISuite; + suite: Mocha.Suite; files: string[]; - options: MochaSetupOptions; + options: Mocha.MochaInstanceOptions; - constructor(options?: MochaSetupOptions); - - asyncOnly(): Mocha; - asyncOnly(value: boolean): Mocha; - delay(): Mocha; - forbidOnly(): Mocha; - forbidPending(): Mocha; - fullTrace(): Mocha; - /** Setup mocha with the given interface. */ - setup(interface: Mocha.Interface): Mocha; - bail(value?: boolean): Mocha; - addFile(file: string): Mocha; - /** Sets reporter by name, defaults to "spec". */ - reporter(name: string, reporterOptions?: any): Mocha; - /** Sets reporter constructor, defaults to mocha.reporters.Spec. */ - reporter(reporter: ReporterConstructor, reporterOptions?: any): Mocha; - ui(value: string): Mocha; - grep(value: string): Mocha; - grep(value: RegExp): Mocha; - invert(): Mocha; - ignoreLeaks(value: boolean): Mocha; - checkLeaks(): Mocha; /** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. + * Enable or disable bailing on the first failure. + * + * @see https://mochajs.org/api/mocha#bail */ - throwError(error: Error): void; - /** Enables growl support. */ - growl(): Mocha; - globals(value: string): Mocha; - globals(values: string[]): Mocha; - useColors(value: boolean): Mocha; - useInlineDiffs(value: boolean): Mocha; - timeout(value: number): Mocha; - slow(value: number): Mocha; - enableTimeouts(value: boolean): Mocha; - noHighlighting(value: boolean): Mocha; - /** Runs tests and invokes `onComplete()` when finished. */ - run(onComplete?: (failures: number) => void): Mocha.IRunner; - loadFiles(cb?: () => any): void; + bail(bail?: boolean): this; - // internals exposed via exports.* - Runnable: Mocha.Runnable; - Context: Mocha.Context; - Runner: Mocha.Runner; - Suite: Mocha.Suite; - Hook: Mocha.Hook; - Test: Mocha.Test; - } + /** + * Add test `file`. + * + * @see https://mochajs.org/api/mocha#addFile + */ + addFile(file: string): this; - // merge the Mocha class declaration with a module - declare namespace Mocha { - /** Third-party declarations that want to add new interfaces can contribute names here */ - interface InterfaceContributions { - bdd: any; - tdd: any; - qunit: any; - exports: any; + /** + * Set reporter to one of the built-in reporters. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter: Mocha.Reporter, reporterOptions?: any): this; + + /** + * Set reporter to the provided constructor, one of the built-in reporters, or loads a reporter + * from a module path. Defaults to `"spec"`. + * + * @see https://mochajs.org/api/mocha#reporter + */ + reporter(reporter?: string | Mocha.ReporterConstructor, reporterOptions?: any): this; + + /** + * Set test UI to one of the built-in test interfaces. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name: Mocha.Interface): this; + + /** + * Set test UI to one of the built-in test interfaces or loads a test interface from a module + * path. Defaults to `"bdd"`. + * + * @see https://mochajs.org/api/mocha#ui + */ + ui(name?: string): this; + + /** + * Escape string and add it to grep as a RegExp. + * + * @see https://mochajs.org/api/mocha#fgrep + */ + fgrep(str: string): this; + + /** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @see https://mochajs.org/api/mocha#grep + */ + grep(re: string | RegExp): this; + + /** + * Invert `.grep()` matches. + * + * @see https://mochajs.org/api/mocha#invert + */ + invert(): this; + + /** + * Ignore global leaks. + * + * @see https://mochajs.org/api/mocha#ignoreLeaks + */ + ignoreLeaks(ignore: boolean): this; + + /** + * Enable global leak checking. + * + * @see https://mochajs.org/api/mocha#checkLeaks + */ + checkLeaks(): this; + + /** + * Display long stack-trace on failing + * + * @see https://mochajs.org/api/mocha#fullTrace + */ + fullTrace(): this; + + /** + * Enable growl support. + * + * @see https://mochajs.org/api/mocha#growl + */ + growl(): this; + + /** + * Ignore `globals` array or string. + * + * @see https://mochajs.org/api/mocha#globals + */ + globals(globals: string | ReadonlyArray): this; + + /** + * Emit color output. + * + * @see https://mochajs.org/api/mocha#useColors + */ + useColors(colors: boolean): this; + + /** + * Use inline diffs rather than +/-. + * + * @see https://mochajs.org/api/mocha#useInlineDiffs + */ + useInlineDiffs(inlineDiffs: boolean): this; + + /** + * Do not show diffs at all. + * + * @see https://mochajs.org/api/mocha#hideDiff + */ + hideDiff(hideDiff: boolean): this; + + /** + * Set the timeout in milliseconds. + * + * @see https://mochajs.org/api/mocha#timeout + */ + timeout(timeout: string | number): this; + + /** + * Set the number of times to retry failed tests. + * + * @see https://mochajs.org/api/mocha#retries + */ + retries(n: number): this; + + /** + * Set slowness threshold in milliseconds. + * + * @see https://mochajs.org/api/mocha#slow + */ + slow(slow: string | number): this; + + /** + * Enable timeouts. + * + * @see https://mochajs.org/api/mocha#enableTimeouts + */ + enableTimeouts(enabled?: boolean): this; + + /** + * Makes all tests async (accepting a callback) + * + * @see https://mochajs.org/api/mocha#asyncOnly. + */ + asyncOnly(): this; + + /** + * Disable syntax highlighting (in browser). + * + * @see https://mochajs.org/api/mocha#noHighlighting + */ + noHighlighting(): this; + + /** + * Enable uncaught errors to propagate (in browser). + * + * @see https://mochajs.org/api/mocha#allowUncaught + */ + allowUncaught(): boolean; + + /** + * Delay root suite execution. + * + * @see https://mochajs.org/api/mocha#delay + */ + delay(): boolean; + + /** + * Tests marked only fail the suite + * + * @see https://mochajs.org/api/mocha#forbidOnly + */ + forbidOnly(): boolean; + + /** + * Pending tests and tests marked skip fail the suite + * + * @see https://mochajs.org/api/mocha#forbidPending + */ + forbidPending(): boolean; + + /** + * Run tests and invoke `fn()` when complete. + * + * Note that `run` relies on Node's `require` to execute + * the test interface functions and will be subject to the + * cache - if the files are already in the `require` cache, + * they will effectively be skipped. Therefore, to run tests + * multiple times or to run tests in files that are already + * in the `require` cache, make sure to clear them from the + * cache first in whichever manner best suits your needs. + * + * @see https://mochajs.org/api/mocha#run + */ + run(fn?: (failures: number) => void): Mocha.Runner; + + /** + * Load registered files. + * + * @see https://mochajs.org/api/mocha#loadFiles + */ + protected loadFiles(fn?: () => void): void; +} + +declare namespace Mocha { + namespace utils { + /** + * Compute a slug from the given `str`. + * + * @see https://mochajs.org/api/module-utils.html#.slug + */ + function slug(str: string): string; + + /** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @see https://mochajs.org/api/module-utils.html#.clean + */ + function clean(str: string): string; + + /** + * Highlight the given string of `js`. + */ + function highlight(js: string): string; + + /** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it is. + */ + function type(value: any): string; + + /** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, returns `'{}'`, `'[Function]'`, or `'[]'` respectively. + * - If `value` has properties, call canonicalize} on it, then return result of `JSON.stringify()` + * + * @see https://mochajs.org/api/module-utils.html#.stringify + */ + function stringify(value: any): string; + + /** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, returns `'[]'`, `'{}'`, or `'[Function]'` respectively. + * + * @see https://mochajs.org/api/module-utils.html#.canonicalize + */ + function canonicalize(value: any, stack: any[], typeHint: string): any; + + /** + * Lookup file names at the given `path`. + * + * @see https://mochajs.org/api/Mocha.utils.html#.exports.lookupFiles + */ + function lookupFiles(filepath: string, extensions?: string[], recursive?: boolean): string[]; + + /** + * Generate an undefined error with a message warning the user. + * + * @see https://mochajs.org/api/module-utils.html#.undefinedError + */ + function undefinedError(): Error; + + /** + * Generate an undefined error if `err` is not defined. + * + * @see https://mochajs.org/api/module-utils.html#.getError + */ + function getError(err: Error | undefined): Error; + + /** + * When invoking this function you get a filter function that get the Error.stack as an + * input, and return a prettify output. (i.e: strip Mocha and internal node functions from + * stack trace). + * + * @see https://mochajs.org/api/module-utils.html#.stackTraceFilter + */ + function stackTraceFilter(): (stack: string) => string; } - type Interface = keyof InterfaceContributions; - - interface IContext { - _runnable?: IRunnable; - test?: IRunnable; - - runnable(): IRunnable | undefined; - runnable(runnable: IRunnable): IContext; - timeout(): number; - timeout(timeout: number): IContext; - enableTimeouts(enableTimeouts: boolean): IContext; - slow(slow: number): IContext; - skip(): IContext; - retries(): number; - retries(retries: number): IContext; - inspect(): string; + namespace interfaces { + function bdd(suite: Suite): void; + function tdd(suite: Suite): void; + function qunit(suite: Suite): void; + function exports(suite: Suite): void; } - interface ISuiteCallbackContext { - timeout(ms: number | string): this; - retries(n: number): this; - slow(ms: number): this; + // #region Test interface augmentations + + interface HookFunction { + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given callback `fn`. The name of the + * function is used as the name of the hook. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: Func): void; + + /** + * [bdd, qunit, tdd] Describe a "hook" to execute the given `title` and callback `fn`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (name: string, fn?: AsyncFunc): void; } - interface IHookCallbackContext { - skip(): this; - timeout(ms: number | string): this; - [index: string]: any; + interface SuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; + + /** + * [bdd, tdd, qunit] Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveSuiteFunction; + + /** + * [bdd, tdd] Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingSuiteFunction; } - interface ITestCallbackContext { - skip(): this; - timeout(ms: number | string): this; - retries(n: number): this; - slow(ms: number): this; - [index: string]: any; + interface ExclusiveSuiteFunction { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn: (this: Suite) => void): Suite; + + /** + * [qunit] Describe a "suite" with the given `title`. Indicates this suite should be executed + * exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string): Suite; } - /** Partial interface for Mocha's `Runnable` class. */ - interface IRunnable extends GenericEventEmitter { + /** + * [bdd, tdd] Describe a "suite" with the given `title` and callback `fn` containing + * nested suites. Indicates this suite should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + * + * @returns [bdd] `Suite` + * @returns [tdd] `void` + */ + type PendingSuiteFunction = (title: string, fn: (this: Suite) => void) => Suite | void; + + interface TestFunction { + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * Describe a specification or test-case with the given callback `fn` acting as a thunk. + * The name of the function is used as the name of the test. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * Describe a specification or test-case with the given `title` and callback `fn` acting + * as a thunk. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + + /** + * Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + only: ExclusiveTestFunction; + + /** + * Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + skip: PendingTestFunction; + + /** + * Number of attempts to retry. + * + * - _Only available when invoked via the mocha CLI._ + */ + retries(n: number): void; + } + + interface ExclusiveTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should be executed exclusively. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + interface PendingTestFunction { + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given callback `fn` + * acting as a thunk. The name of the function is used as the name of the test. Indicates + * this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (fn: AsyncFunc): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: Func): Test; + + /** + * [bdd, tdd, qunit] Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. Indicates this test should not be executed. + * + * - _Only available when invoked via the mocha CLI._ + */ + (title: string, fn?: AsyncFunc): Test; + } + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let afterEach: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let beforeEach: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let before: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let describe: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let it: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let xit: PendingTestFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + let setup: HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + let suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + let suiteTeardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + let suite: SuiteFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + let teardown: HookFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + let test: TestFunction; + + /** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ + function run(): void; + + // #endregion Test interface augmentations + + namespace reporters { + /** + * Initialize a new `Base` reporter. + * + * All other reporters generally inherit from this reporter, providing stats such as test duration, + * number of tests passed / failed, etc. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html + */ + class Base { + constructor(runner: Runner, options?: MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: MochaOptions); + + /** + * Test run statistics + */ + stats: Stats; + + /** + * Test failures + */ + failures: Test[]; + + /** + * The configured runner + */ + runner: Runner; + + /** + * Output common epilogue used by many of the bundled reporters. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.Base#epilogue + */ + epilogue(): void; + + done?(failures: number, fn?: (failures: number) => void): void; + } + + namespace Base { + /** + * Enables coloring by default + * + * @see https://mochajs.org/api/module-base#.useColors + */ + let useColors: boolean; + + /** + * Inline diffs instead of +/- + * + * @see https://mochajs.org/api/module-base#.inlineDiffs + */ + let inlineDiffs: boolean; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + const colors: ColorMap; + + /** + * Default color map + * + * @see https://mochajs.org/api/module-base#.colors + */ + interface ColorMap { + // added by Base + pass: number; + fail: number; + "bright pass": number; + "bright fail": number; + "bright yellow": number; + pending: number; + suite: number; + "error title": number; + "error message": number; + "error stack": number; + checkmark: number; + fast: number; + medium: number; + slow: number; + green: number; + light: number; + "diff gutter": number; + "diff added": number; + "diff removed": number; + + // added by Progress + progress: number; + + // added by Landing + plane: number; + "plane crash": number; + runway: number; + + [key: string]: number; + } + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + const symbols: SymbolMap; + + /** + * Default symbol map + * + * @see https://mochajs.org/api/module-base#.symbols + */ + interface SymbolMap { + ok: string; + err: string; + dot: string; + comma: string; + bang: string; + [key: string]: string; + } + + /** + * Color `str` with the given `type` (from `colors`) + * + * @see https://mochajs.org/api/module-base#.color + */ + function color(type: string, str: string): string; + + /** + * Expose terminal window size + * + * @see https://mochajs.org/api/module-base#.window + */ + const window: { + width: number; + }; + + /** + * ANSI TTY control sequences common among reporters. + * + * @see https://mochajs.org/api/module-base#.cursor + */ + namespace cursor { + /** + * Hides the cursor + */ + function hide(): void; + + /** + * Shows the cursor + */ + function show(): void; + + /** + * Deletes the current line + */ + function deleteLine(): void; + + /** + * Moves to the beginning of the line + */ + function beginningOfLine(): void; + + /** + * Clears the line and moves to the beginning of the line. + */ + function CR(): void; + } + + /** + * Returns a diff between two strings with colored ANSI output. + * + * @see https://mochajs.org/api/module-base#.generateDiff + */ + function generateDiff(actual: string, expected: string): string; + + /** + * Output the given `failures` as a list. + * + * @see https://mochajs.org/api/Mocha.reporters.Base.html#.exports.list1 + */ + function list(failures: Test[]): void; + } + + /** + * Initialize a new `Dot` matrix test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Dot.html + */ + class Dot extends Base { + } + + /** + * Initialize a new `Doc` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Doc.html + */ + class Doc extends Base { + } + + /** + * Initialize a new `TAP` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.TAP.html + */ + class TAP extends Base { + } + + /** + * Initialize a new `JSON` reporter + * + * @see https://mochajs.org/api/Mocha.reporters.JSON.html + */ + class JSON extends Base { + } + + /** + * Initialize a new `HTML` reporter. + * + * - _This reporter cannot be used on the console._ + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html + */ + class HTML extends Base { + /** + * Provide suite URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#suiteURL + */ + suiteURL(suite: Suite): string; + + /** + * Provide test URL. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#testURL + */ + testURL(test: Test): string; + + /** + * Adds code toggle functionality for the provided test's list element. + * + * @see https://mochajs.org/api/Mocha.reporters.HTML.html#addCodeToggle + */ + addCodeToggle(el: HTMLLIElement, contents: string): void; + } + + /** + * Initialize a new `List` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.List.html + */ + class List extends Base { + } + + /** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @see https://mochajs.org/api/Mocha.reporters.Min.html + */ + class Min extends Base { + } + + /** + * Initialize a new `Spec` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Spec.html + */ + class Spec extends Base { + } + + /** + * Initialize a new `NyanCat` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Nyan.html + */ + class Nyan extends Base { + private colorIndex; + private numberOfLines; + private rainbowColors; + private scoreboardWidth; + private tick; + private trajectories; + private trajectoryWidthMax; + private draw; + private drawScoreboard; + private appendRainbow; + private drawRainbow; + private drawNyanCat; + private face; + private cursorUp; + private cursorDown; + private generateColors; + private rainbowify; + } + + /** + * Initialize a new `XUnit` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html + */ + class XUnit extends Base { + constructor(runner: Runner, options?: XUnit.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: XUnit.MochaOptions); + + /** + * Override done to close the stream (if it's a file). + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#done + */ + done(failures: number, fn: (failures: number) => void): void; + + /** + * Write out the given line. + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#write + */ + write(line: string): void; + + /** + * Output tag for the given `test.` + * + * @see https://mochajs.org/api/Mocha.reporters.XUnit.html#test + */ + test(test: Test): void; + } + + namespace XUnit { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + output?: string; + suiteName?: string; + } + } + + /** + * Initialize a new `Markdown` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Markdown.html + */ + class Markdown extends Base { + } + + /** + * Initialize a new `Progress` bar test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Progress.html + */ + class Progress extends Base { + constructor(runner: Runner, options?: Progress.MochaOptions); + /** @deprecated Use the overload that accepts `Mocha.Runner` instead. */ + constructor(runner: IRunner, options?: Progress.MochaOptions); + } + + namespace Progress { + interface MochaOptions extends Mocha.MochaOptions { + reporterOptions?: ReporterOptions; + } + + interface ReporterOptions { + open?: string; + complete?: string; + incomplete?: string; + close?: string; + verbose?: boolean; + } + } + + /** + * Initialize a new `Landing` reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.Landing.html + */ + class Landing extends Base { + } + + /** + * Initialize a new `JSONStream` test reporter. + * + * @see https://mochajs.org/api/Mocha.reporters.JSONStream.html + */ + class JSONStream extends Base { + } + + // value-only aliases + const base: typeof Base; + const dot: typeof Dot; + const doc: typeof Doc; + const tap: typeof TAP; + const json: typeof JSON; + const html: typeof HTML; + const list: typeof List; + const spec: typeof Spec; + const nyan: typeof Nyan; + const xunit: typeof XUnit; + const markdown: typeof Markdown; + const progress: typeof Progress; + const landing: typeof Landing; + // NOTE: not possible to type this correctly: + // const "json-stream": typeof JSONStream; + } + + /** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Runnable.html + */ + class Runnable { + private _slow; + private _enableTimeouts; + private _retries; + private _currentRetry; + private _timeout; + private _timeoutError; + + constructor(title: string, fn?: Func | AsyncFunc); + title: string; - fn: Function; + fn: Func | AsyncFunc | undefined; + body: string; async: boolean; sync: boolean; timedOut: boolean; - timeout(n: number | string): this; - duration?: number; - } - - /** Partial interface for Mocha's `Suite` class. */ - interface ISuite { - ctx: IContext; - parent: ISuite; - root: boolean; - title: string; - suites: ISuite[]; - tests: ITest[]; - - _beforeEach: IHook[]; - _beforeAll: IHook[]; - _afterEach: IHook[]; - _afterAll: IHook[]; - - bail(): boolean; - bail(bail: boolean): ISuite; - fullTitle(): string; - retries(): number; - retries(retries: number): ISuite; - slow(): number; - slow(slow: number): ISuite; - timeout(): number; - timeout(timeout: number): ISuite; - } - - /** Partial interface for Mocha's `Test` class. */ - interface ITest extends IRunnable { - body?: string; - file?: string; - parent: ISuite; pending: boolean; - state: 'failed' | 'passed' | undefined; - type: 'test'; + duration?: number; + parent?: Suite; + state?: "failed" | "passed"; + timer?: any; + ctx?: Context; + callback?: Done; + allowUncaught?: boolean; + file?: string; + /** + * Get test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(): number; + + /** + * Set test timeout. + * + * @see https://mochajs.org/api/Runnable.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(): number; + + /** + * Set test slowness threshold. + * + * @see https://mochajs.org/api/Runnable.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + * + * @see https://mochajs.org/api/Runnable.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Halt and mark as pending. + */ + skip(): never; + + /** + * Check if this runnable or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Runnable.html#isPending + */ + isPending(): boolean; + + /** + * Return `true` if this Runnable has failed. + */ + isFailed(): boolean; + + /** + * Return `true` if this Runnable has passed. + */ + isPassed(): boolean; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(): number; + + /** + * Set or get number of retries. + * + * @see https://mochajs.org/api/Runnable.html#retries + */ + retries(n: number): void; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(): number; + + /** + * Set or get current retry + * + * @see https://mochajs.org/api/Runnable.html#currentRetry + */ + protected currentRetry(n: number): void; + + /** + * Return the full title generated by recursively concatenating the parent's full title. + */ fullTitle(): string; + + /** + * Return the title path generated by concatenating the parent's title path with the title. + */ + titlePath(): string[]; + + /** + * Clear the timeout. + * + * @see https://mochajs.org/api/Runnable.html#clearTimeout + */ + clearTimeout(): void; + + /** + * Inspect the runnable void of private properties. + * + * @see https://mochajs.org/api/Runnable.html#inspect + */ + inspect(): string; + + /** + * Reset the timeout. + * + * @see https://mochajs.org/api/Runnable.html#resetTimeout + */ + resetTimeout(): void; + + /** + * Get a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(): string[]; + + /** + * Set a list of whitelisted globals for this test run. + * + * @see https://mochajs.org/api/Runnable.html#globals + */ + globals(globals: ReadonlyArray): void; + + /** + * Run the test and invoke `fn(err)`. + * + * @see https://mochajs.org/api/Runnable.html#run + */ + run(fn: Done): void; } - interface IHook extends IRunnable { - ctx?: IContext; - parent?: ISuite; - type: 'hook'; + // #region Runnable "error" event + interface Runnable extends NodeJS.EventEmitter { + on(event: "error", listener: (error: any) => void): this; + once(event: "error", listener: (error: any) => void): this; + addListener(event: "error", listener: (error: any) => void): this; + removeListener(event: "error", listener: (error: any) => void): this; + prependListener(event: "error", listener: (error: any) => void): this; + prependOnceListener(event: "error", listener: (error: any) => void): this; + emit(name: "error", error: any): boolean; + } + // #endregion Runnable "error" event + // #region Runnable untyped events + interface Runnable extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runnable untyped events - error(err: Error): void; + /** + * Test context + * + * @see https://mochajs.org/api/module-Context.html#~Context + */ + class Context { + private _runnable; + + test?: Runnable; + currentTest?: Test; + + /** + * Get the context `Runnable`. + */ + runnable(): Runnable; + + /** + * Set the context `Runnable`. + */ + runnable(runnable: Runnable): this; + /** @deprecated Use the overload that accepts `Mocha.Runnable` instead. */ + runnable(runnable: IRunnable): this; + + /** + * Get test timeout. + */ + timeout(): number; + + /** + * Set test timeout. + */ + timeout(ms: string | number): this; + + /** + * Get whether timeouts are enabled. + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are enabled. + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get test slowness threshold. + */ + slow(): number; + + /** + * Set test slowness threshold. + */ + slow(ms: string | number): this; + + /** + * Mark a test as skipped. + */ + skip(): never; + + /** + * Get the number of allowed retries on failed tests. + */ + retries(): number; + + /** + * Set the number of allowed retries on failed tests. + */ + retries(n: number): this; + + [key: string]: any; } - interface IBeforeAndAfterContext extends IHookCallbackContext { - currentTest: ITest; + /** + * Initialize a `Runner` for the given `suite`. + * + * @see https://mochajs.org/api/Mocha.Runner.html + */ + class Runner { + private _globals; + private _abort; + private _delay; + private _defaultGrep; + private next; + private hookErr; + private prevGlobalsLength; + private nextSuite; + + constructor(suite: Suite, delay: boolean); + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + constructor(suite: ISuite, delay: boolean); + + suite: Suite; + started: boolean; + total: number; + failures: number; + asyncOnly?: boolean; + allowUncaught?: boolean; + fullStackTrace?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + ignoreLeaks?: boolean; + test?: Test; + currentRunnable?: Runnable; + stats?: Stats; // added by reporters + + /** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grep + */ + grep(re: RegExp, invert: boolean): this; + + /** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#grepTotal + */ + grepTotal(suite: Suite): number; + + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + grepTotal(suite: ISuite): number; + + /** + * Gets the allowed globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(): string[]; + + /** + * Allow the given `arr` of globals. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#globals + */ + globals(arr: ReadonlyArray): this; + + /** + * Run the root suite and invoke `fn(failures)` on completion. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#run + */ + run(fn?: (failures: number) => void): this; + + /** + * Cleanly abort execution. + * + * @see https://mochajs.org/api/Mocha.Runner.html#.Runner#abort + */ + abort(): this; + + /** + * Handle uncaught exceptions. + * + * @see https://mochajs.org/api/Mocha.Runner.html#uncaught + */ + uncaught(err: any): void; + + /** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + */ + protected static immediately(callback: Function): void; + + /** + * Return a list of global properties. + * + * @see https://mochajs.org/api/Mocha.Runner.html#globalProps + */ + protected globalProps(): string[]; + + /** + * Check for global variable leaks. + * + * @see https://mochajs.org/api/Mocha.Runner.html#checkGlobals + */ + protected checkGlobals(test: Test): void; + + /** + * Fail the given `test`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#fail + */ + protected fail(test: Test, err: any): void; + + /** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @see https://mochajs.org/api/Mocha.Runner.html#failHook + */ + protected failHook(hook: Hook, err: any): void; + + /** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hook + */ + protected hook(name: string, fn: () => void): void; + + /** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hooks + */ + protected hooks(name: string, suites: Suite[], fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the top level down. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookUp + */ + protected hookUp(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Run hooks from the bottom up. + * + * @see https://mochajs.org/api/Mocha.Runner.html#hookDown + */ + protected hookDown(name: string, fn: (err?: any, errSuite?: Suite) => void): void; + + /** + * Return an array of parent Suites from closest to furthest. + * + * @see https://mochajs.org/api/Mocha.Runner.html#parents + */ + protected parents(): Suite[]; + + /** + * Run the current test and callback `fn(err)`. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTest + */ + protected runTest(fn: Done): any; + + /** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runTests + */ + protected runTests(suite: Suite, fn: (errSuite?: Suite) => void): void; + + /** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @see https://mochajs.org/api/Mocha.Runner.html#runSuite + */ + protected runSuite(suite: Suite, fn: (errSuite?: Suite) => void): void; } - interface IStats { + // #region Runner "waiting" event + interface Runner { + on(event: "waiting", listener: (rootSuite: Suite) => void): this; + once(event: "waiting", listener: (rootSuite: Suite) => void): this; + addListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + removeListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + prependOnceListener(event: "waiting", listener: (rootSuite: Suite) => void): this; + emit(name: "waiting", rootSuite: Suite): boolean; + } + // #endregion Runner "waiting" event + // #region Runner "start" event + interface Runner extends NodeJS.EventEmitter { + on(event: "start", listener: () => void): this; + once(event: "start", listener: () => void): this; + addListener(event: "start", listener: () => void): this; + removeListener(event: "start", listener: () => void): this; + prependListener(event: "start", listener: () => void): this; + prependOnceListener(event: "start", listener: () => void): this; + emit(name: "start"): boolean; + } + // #endregion Runner "start" event + // #region Runner "end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "end", listener: () => void): this; + once(event: "end", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + emit(name: "end"): boolean; + } + // #endregion Runner "end" event + // #region Runner "suite" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Runner "suite" event + // #region Runner "suite end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "suite end", listener: (suite: Suite) => void): this; + once(event: "suite end", listener: (suite: Suite) => void): this; + addListener(event: "suite end", listener: (suite: Suite) => void): this; + removeListener(event: "suite end", listener: (suite: Suite) => void): this; + prependListener(event: "suite end", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite end", listener: (suite: Suite) => void): this; + emit(name: "suite end", suite: Suite): boolean; + } + // #endregion Runner "suite end" event + // #region Runner "test" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Runner "test" event + // #region Runner "test end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "test end", listener: (test: Test) => void): this; + once(event: "test end", listener: (test: Test) => void): this; + addListener(event: "test end", listener: (test: Test) => void): this; + removeListener(event: "test end", listener: (test: Test) => void): this; + prependListener(event: "test end", listener: (test: Test) => void): this; + prependOnceListener(event: "test end", listener: (test: Test) => void): this; + emit(name: "test end", test: Test): boolean; + } + // #endregion Runner "test end" event + // #region Runner "hook" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook", listener: (hook: Hook) => void): this; + once(event: "hook", listener: (hook: Hook) => void): this; + addListener(event: "hook", listener: (hook: Hook) => void): this; + removeListener(event: "hook", listener: (hook: Hook) => void): this; + prependListener(event: "hook", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook", listener: (hook: Hook) => void): this; + emit(name: "hook", hook: Hook): boolean; + } + // #endregion Runner "hook" event + // #region Runner "hook end" event + interface Runner extends NodeJS.EventEmitter { + on(event: "hook end", listener: (hook: Hook) => void): this; + once(event: "hook end", listener: (hook: Hook) => void): this; + addListener(event: "hook end", listener: (hook: Hook) => void): this; + removeListener(event: "hook end", listener: (hook: Hook) => void): this; + prependListener(event: "hook end", listener: (hook: Hook) => void): this; + prependOnceListener(event: "hook end", listener: (hook: Hook) => void): this; + emit(name: "hook end", hook: Hook): boolean; + } + // #endregion Runner "hook end" event + // #region Runner "pass" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pass", listener: (test: Test) => void): this; + once(event: "pass", listener: (test: Test) => void): this; + addListener(event: "pass", listener: (test: Test) => void): this; + removeListener(event: "pass", listener: (test: Test) => void): this; + prependListener(event: "pass", listener: (test: Test) => void): this; + prependOnceListener(event: "pass", listener: (test: Test) => void): this; + emit(name: "pass", test: Test): boolean; + } + // #endregion Runner "pass" event + // #region Runner "fail" event + interface Runner extends NodeJS.EventEmitter { + on(event: "fail", listener: (test: Test, err: any) => void): this; + once(event: "fail", listener: (test: Test, err: any) => void): this; + addListener(event: "fail", listener: (test: Test, err: any) => void): this; + removeListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependListener(event: "fail", listener: (test: Test, err: any) => void): this; + prependOnceListener(event: "fail", listener: (test: Test, err: any) => void): this; + emit(name: "fail", test: Test, err: any): boolean; + } + // #endregion Runner "fail" event + // #region Runner "pending" event + interface Runner extends NodeJS.EventEmitter { + on(event: "pending", listener: (test: Test) => void): this; + once(event: "pending", listener: (test: Test) => void): this; + addListener(event: "pending", listener: (test: Test) => void): this; + removeListener(event: "pending", listener: (test: Test) => void): this; + prependListener(event: "pending", listener: (test: Test) => void): this; + prependOnceListener(event: "pending", listener: (test: Test) => void): this; + emit(name: "pending", test: Test): boolean; + } + // #endregion Runner "pending" event + // #region Runner untyped events + interface Runner extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Suite` with the given `title` and `ctx`. + * + * @see https://mochajs.org/api/Mocha.Suite.html + */ + class Suite { + private _beforeEach; + private _beforeAll; + private _afterEach; + private _afterAll; + private _timeout; + private _enableTimeouts; + private _slow; + private _bail; + private _retries; + private _onlyTests; + private _onlySuites; + + constructor(title: string, parentContext?: Context); + /** @deprecated Use the overload that accepts `Mocha.Context` instead. */ + constructor(title: string, parentContext?: IContext); + + ctx: Context; + suites: Suite[]; + tests: Test[]; + pending: boolean; + file?: string; + root: boolean; + delayed: boolean; + parent: Suite | undefined; + title: string; + + /** + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. + * + * @see https://mochajs.org/api/mocha#.exports.create + */ + static create(parent: Suite, title: string): Suite; + /** @deprecated Use the overload that accepts `Mocha.Suite` instead. */ + static create(parent: ISuite, title: string): Suite; + + /** + * Return a clone of this `Suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#clone + */ + clone(): Suite; + + /** + * Get timeout `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(): number; + + /** + * Set timeout `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#timeout + */ + timeout(ms: string | number): this; + + /** + * Get number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(): number; + + /** + * Set number of times to retry a failed test. + * + * @see https://mochajs.org/api/Mocha.Suite.html#retries + */ + retries(n: string | number): this; + + /** + * Get whether timeouts are enabled. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(): boolean; + + /** + * Set whether timeouts are `enabled`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts + */ + enableTimeouts(enabled: boolean): this; + + /** + * Get slow `ms`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(): number; + + /** + * Set slow `ms` or short-hand such as "2s". + * + * @see https://mochajs.org/api/Mocha.Suite.html#slow + */ + slow(ms: string | number): this; + + /** + * Get whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(): boolean; + + /** + * Set whether to bail after first error. + * + * @see https://mochajs.org/api/Mocha.Suite.html#bail + */ + bail(bail: boolean): this; + + /** + * Check if this suite or its parent suite is marked as pending. + * + * @see https://mochajs.org/api/Mocha.Suite.html#isPending + */ + isPending(): boolean; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll + */ + beforeAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after running tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterAll + */ + afterAll(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` before each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach + */ + beforeEach(title: string, fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(fn?: AsyncFunc): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: Func): this; + + /** + * Run `fn(test[, done])` after each test case. + * + * @see https://mochajs.org/api/Mocha.Suite.html#afterEach + */ + afterEach(title: string, fn?: AsyncFunc): this; + + /** + * Add a test `suite`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addSuite + */ + addSuite(suite: Suite): this; + /** @deprecated Use the overload that accepts `Mocha.ISuite` instead. */ + addSuite(suite: ISuite): this; + + /** + * Add a `test` to this suite. + * + * @see https://mochajs.org/api/Mocha.Suite.html#addTest + */ + addTest(test: Test): this; + /** @deprecated Use the overload that accepts `Mocha.ITest` instead. */ + addTest(test: ITest): this; + + /** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#fullTitle + */ + fullTitle(): string; + + /** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#titlePath + */ + titlePath(): string[]; + + /** + * Return the total number of tests. + * + * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#total + */ + total(): number; + + /** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @see https://mochajs.org/api/Mocha.Suite.html#eachTest + */ + eachTest(fn: (test: Test) => void): this; + + /** + * This will run the root suite if we happen to be running in delayed mode. + * + * @see https://mochajs.org/api/Mocha.Suite.html#run + */ + run(): void; + + /** + * Generic hook-creator. + */ + protected _createHook(title: string, fn?: Func | AsyncFunc): Hook; + } + + // #region Suite "beforeAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeAll", listener: (hook: Hook) => void): this; + once(event: "beforeAll", listener: (hook: Hook) => void): this; + addListener(event: "beforeAll", listener: (hook: Hook) => void): this; + removeListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependListener(event: "beforeAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeAll", listener: (hook: Hook) => void): this; + emit(name: "beforeAll", hook: Hook): boolean; + } + // #endregion Suite "beforeAll" event + // #region Suite "afterAll" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterAll", listener: (hook: Hook) => void): this; + once(event: "afterAll", listener: (hook: Hook) => void): this; + addListener(event: "afterAll", listener: (hook: Hook) => void): this; + removeListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependListener(event: "afterAll", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterAll", listener: (hook: Hook) => void): this; + emit(name: "afterAll", hook: Hook): boolean; + } + // #endregion Suite "afterAll" event + // #region Suite "beforeEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "beforeEach", listener: (hook: Hook) => void): this; + once(event: "beforeEach", listener: (hook: Hook) => void): this; + addListener(event: "beforeEach", listener: (hook: Hook) => void): this; + removeListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependListener(event: "beforeEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "beforeEach", listener: (hook: Hook) => void): this; + emit(name: "beforeEach", hook: Hook): boolean; + } + // #endregion Suite "beforeEach" event + // #region Suite "afterEach" event + interface Suite extends NodeJS.EventEmitter { + on(event: "afterEach", listener: (hook: Hook) => void): this; + once(event: "afterEach", listener: (hook: Hook) => void): this; + addListener(event: "afterEach", listener: (hook: Hook) => void): this; + removeListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependListener(event: "afterEach", listener: (hook: Hook) => void): this; + prependOnceListener(event: "afterEach", listener: (hook: Hook) => void): this; + emit(name: "afterEach", hook: Hook): boolean; + } + // #endregion Suite "afterEach" event + // #region Suite "suite" event + interface Suite extends NodeJS.EventEmitter { + on(event: "suite", listener: (suite: Suite) => void): this; + once(event: "suite", listener: (suite: Suite) => void): this; + addListener(event: "suite", listener: (suite: Suite) => void): this; + removeListener(event: "suite", listener: (suite: Suite) => void): this; + prependListener(event: "suite", listener: (suite: Suite) => void): this; + prependOnceListener(event: "suite", listener: (suite: Suite) => void): this; + emit(name: "suite", suite: Suite): boolean; + } + // #endregion Suite "suite" event + // #region Suite "test" event + interface Suite { + on(event: "test", listener: (test: Test) => void): this; + once(event: "test", listener: (test: Test) => void): this; + addListener(event: "test", listener: (test: Test) => void): this; + removeListener(event: "test", listener: (test: Test) => void): this; + prependListener(event: "test", listener: (test: Test) => void): this; + prependOnceListener(event: "test", listener: (test: Test) => void): this; + emit(name: "test", test: Test): boolean; + } + // #endregion Suite "test" event + // #region Suite "run" event + interface Suite extends NodeJS.EventEmitter { + on(event: "run", listener: () => void): this; + once(event: "run", listener: () => void): this; + addListener(event: "run", listener: () => void): this; + removeListener(event: "run", listener: () => void): this; + prependListener(event: "run", listener: () => void): this; + prependOnceListener(event: "run", listener: () => void): this; + emit(name: "run"): boolean; + } + // #endregion Suite "run" event + // #region Suite "pre-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "pre-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "pre-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "pre-require" event + // #region Suite "require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + once(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + addListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + removeListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "require", listener: (module: any, file: string, mocha: Mocha) => void): this; + emit(name: "require", module: any, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "require" event + // #region Suite "post-require" event + interface Suite extends NodeJS.EventEmitter { + on(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + once(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + addListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + removeListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + prependOnceListener(event: "post-require", listener: (context: MochaGlobals, file: string, mocha: Mocha) => void): this; + emit(name: "post-require", context: MochaGlobals, file: string, mocha: Mocha): boolean; + } + // #endregion Suite "post-require" event + // #region Suite untyped events + interface Suite extends NodeJS.EventEmitter { + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + emit(name: string, ...args: any[]): boolean; + } + // #endregion Runner untyped events + + /** + * Initialize a new `Hook` with the given `title` and callback `fn` + * + * @see https://mochajs.org/api/Hook.html + */ + class Hook extends Runnable { + private _error; + + type: "hook"; + originalTitle?: string; // added by Runner + + /** + * Get the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(): any; + + /** + * Set the test `err`. + * + * @see https://mochajs.org/api/Hook.html#error + */ + error(err: any): void; + } + + /** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @see https://mochajs.org/api/Test.html + */ + class Test extends Runnable { + type: "test"; + speed?: "slow" | "medium" | "fast"; // added by reporters + err?: Error; // added by reporters + clone(): Test; + } + + /** + * Test statistics + */ + interface Stats { suites: number; tests: number; passes: number; @@ -271,252 +2156,701 @@ declare class GenericEventEmitter { failures: number; start?: Date; end?: Date; - duration?: Date; + duration?: number; } - /** Partial interface for Mocha's `Runner` class. */ - interface IRunner extends GenericEventEmitter { - asyncOnly?: boolean; - stats?: IStats; - started: boolean; - suite: ISuite; - total: number; - failures: number; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; + type TestInterface = (suite: Suite) => void; + + interface ReporterConstructor { + new (runner: Runner, options: { reporterOptions?: any; }): reporters.Base; + } + + type Done = (err?: any) => void; + + /** + * Callback function used for tests and hooks. + */ + type Func = (this: Context, done: Done) => void; + + /** + * Async callback function used for tests and hooks. + */ + type AsyncFunc = (this: Context) => PromiseLike; + + /** + * Options to pass to Mocha. + */ + interface MochaOptions { + /** Test interfaces ("bdd", "tdd", "exports", etc.). */ + ui?: Interface; + + /** + * Reporter constructor, built-in reporter name, or reporter module path. Defaults to + * `"spec"`. + */ + reporter?: string | ReporterConstructor; + + /** Options to pass to the reporter. */ + reporterOptions?: any; + + /** Array of accepted globals. */ + globals?: string[]; + + /** timeout in milliseconds. */ + timeout?: number; + + enableTimeouts?: boolean; + + /** number of times to retry failed tests. */ + retries?: number; + + /** bail on the first test failure. */ + bail?: boolean; + + /** milliseconds to wait before considering a test slow. */ + slow?: number; + + /** ignore global leaks. */ ignoreLeaks?: boolean; - grep: (re: string, invert: boolean) => this; - grepTotal: (suite: ISuite) => number; - globals: (arr: ReadonlyArray) => this | string[]; - abort: () => this; - run: (fn?: (failures: number) => void) => this; + /** display the full stack trace on failure. */ + fullStackTrace?: boolean; + + /** string or regexp to filter tests with. */ + grep?: string | RegExp; + + /** Enable growl support. */ + growl?: boolean; + + /** Emit color output. */ + useColors?: boolean; + + /** Use inline diffs rather than +/-. */ + inlineDiffs?: boolean; + + /** Do not show diffs at all. */ + hideDiff?: boolean; + + asyncOnly?: boolean; + delay?: boolean; + forbidOnly?: boolean; + forbidPending?: boolean; + noHighlighting?: boolean; + allowUncaught?: boolean; } - interface IContextDefinition { - (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; - only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; - skip(description: string, callback: (this: ISuiteCallbackContext) => void): void; - timeout(ms: number | string): void; + interface MochaInstanceOptions extends MochaOptions { + files?: string[]; } - interface ITestDefinition { - (expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; - only(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; - skip(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): void; - timeout(ms: number | string): void; - state: "failed" | "passed"; - } - - namespace reporters { - class Base { - runner: IRunner; - stats: IStats; - - constructor(runner: IRunner); - } - - class Doc extends Base { } - class Dot extends Base { } - class HTML extends Base { } - class HTMLCov extends Base { } - class JSON extends Base { } - class JSONCov extends Base { } - class JSONStream extends Base { } - class Landing extends Base { } - class List extends Base { } - class Markdown extends Base { } - class Min extends Base { } - class Nyan extends Base { } - class Progress extends Base { - /** - * @param options.open String used to indicate the start of the progress bar. - * @param options.complete String used to indicate a complete test on the progress bar. - * @param options.incomplete String used to indicate an incomplete test on the progress bar. - * @param options.close String used to indicate the end of the progress bar. - */ - constructor(runner: IRunner, options?: { - open?: string; - complete?: string; - incomplete?: string; - close?: string; - }); - } - class Spec extends Base { } - class TAP extends Base { } - class XUnit extends Base { - constructor(runner: IRunner, options?: any); - } - } - - /* - * All ambient functions are also available via require('mocha') when invoked via the mocha CLI - * See for details: https://mochajs.org/#require - */ - - /** Only available when invoked via the mocha CLI */ - const describe: IContextDefinition; - /** Only available when invoked via the mocha CLI */ - const xdescribe: IContextDefinition; /** - * alias for `describe` - * Only available when invoked via the mocha CLI + * Variables added to the global scope by Mocha when run in the CLI. */ - const context: IContextDefinition; - /** - * alias for `describe` - * Only available when invoked via the mocha CLI - */ - const suite: IContextDefinition; - /** Only available when invoked via the mocha CLI */ - const it: ITestDefinition; - /** Only available when invoked via the mocha CLI */ - const xit: ITestDefinition; - /** - * alias for `it` - * Only available when invoked via the mocha CLI - */ - const test: ITestDefinition; - /** - * Alias for `it` - * Only available when invoked via the mocha CLI - */ - const specify: ITestDefinition; - /** Only available when invoked via the mocha CLI */ - function setup(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function teardown(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function suiteSetup(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function suiteTeardown(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function before(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function before(description: string, callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function after(callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function after(description: string, callback: (this: IHookCallbackContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function beforeEach(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function beforeEach(description: string, callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function afterEach(callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; - /** Only available when invoked via the mocha CLI */ - function afterEach(description: string, callback: (this: IBeforeAndAfterContext, done: MochaDone) => PromiseLike | void): void; + interface MochaGlobals { + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + before: HookFunction; - class Runnable extends GenericEventEmitter { - new(title: string, fn: () => any): IRunnable; + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + after: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + beforeEach: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + afterEach: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + describe: SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + context: SuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xdescribe: PendingSuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + xcontext: PendingSuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + it: TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + specify: TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xit: PendingTestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + xspecify: PendingTestFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + suiteSetup: HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + suiteTeardown: HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + setup: HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + teardown: HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + suite: SuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + test: TestFunction; + + run: typeof run; } - class Context implements IContext { - constructor(); + /** + * Third-party declarations that want to add new entries to the `Reporter` union can + * contribute names here. + */ + interface ReporterContributions { + Base: never; + base: never; + Dot: never; + dot: never; + TAP: never; + tap: never; + JSON: never; + json: never; + HTML: never; + html: never; + List: never; + list: never; + Min: never; + min: never; + Spec: never; + spec: never; + Nyan: never; + nyan: never; + XUnit: never; + xunit: never; + Markdown: never; + markdown: never; + Progress: never; + progress: never; + Landing: never; + landing: never; + JSONStream: never; + "json-stream": never; + } - _runnable?: IRunnable; + type Reporter = keyof ReporterContributions; + + /** + * Third-party declarations that want to add new entries to the `Interface` union can + * contribute names here. + */ + interface InterfaceContributions { + bdd: never; + tdd: never; + qunit: never; + exports: never; + } + + type Interface = keyof InterfaceContributions; + + // #region Deprecations + + /** @deprecated use `Mocha.Context` instead. */ + interface IContext { test?: IRunnable; - runnable(): IRunnable | undefined; + /** @deprecated `.runnable()` returns `this` in `Mocha.Context`. */ runnable(runnable: IRunnable): IContext; timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Context`. */ timeout(timeout: number): IContext; + /** @deprecated `.enableTimeouts()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.enableTimeouts()` returns `this` in `Mocha.Context`. */ enableTimeouts(enableTimeouts: boolean): IContext; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + /** @deprecated `.slow()` returns `this` in `Mocha.Context`. */ slow(slow: number): IContext; + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ skip(): IContext; retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Context`. */ retries(retries: number): IContext; - inspect(): string; } - class Runner extends GenericEventEmitter implements IRunner { - constructor(suite: ISuite, delay: boolean); - - asyncOnly?: boolean; - stats?: IStats; - started: boolean; - suite: ISuite; - total: number; - failures: number; - forbidOnly?: boolean; - forbidPending?: boolean; - fullStackTrace?: boolean; - hasOnly?: boolean; - ignoreLeaks?: boolean; - - grep: (re: string, invert: boolean) => this; - grepTotal: (suite: ISuite) => number; - globals: (arr: ReadonlyArray) => this | string[]; - abort: () => this; - run: (fn?: (failures: number) => void) => this; + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuiteCallbackContext { + /** @deprecated `.timeout()` has additional overloads in `Mocha.Suite`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Suite`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Suite`. */ + slow(ms: number): this; } - class Suite extends GenericEventEmitter implements ISuite { - constructor(title: string, parentContext: IContext); + /** @deprecated use `Mocha.Context` instead. */ + interface IHookCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + [index: string]: any; + } + /** @deprecated use `Mocha.Context` instead. */ + interface ITestCallbackContext { + /** @deprecated `.skip()` returns `never` in `Mocha.Context`. */ + skip(): this; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Context`. */ + timeout(ms: number | string): this; + /** @deprecated `.retries()` has additional overloads in `Mocha.Context`. */ + retries(n: number): this; + /** @deprecated `.slow()` has additional overloads in `Mocha.Context`. */ + slow(ms: number): this; + [index: string]: any; + } + + /** Partial interface for Mocha's `Runnable` class. */ + /** @deprecated use `Mocha.Runnable` instead. */ + interface IRunnable extends NodeJS.EventEmitter { + title: string; + /** @deprecated `.fn` has type `Func | AsyncFunc` in `Mocha.Runnable`. */ + fn: Function | undefined; + async: boolean; + sync: boolean; + timedOut: boolean; + /** @deprecated `.timeout()` has additional overloads in `Mocha.Runnable`. */ + timeout(n: number | string): this; + duration?: number; + } + + /** Partial interface for Mocha's `Suite` class. */ + /** @deprecated use `Mocha.Suite` instead. */ + interface ISuite { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Suite`. */ ctx: IContext; - parent: ISuite; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Suite`. */ + parent: ISuite | undefined; root: boolean; title: string; + /** @deprecated `.suites` has type `Mocha.Suite[]` in `Mocha.Suite`. */ suites: ISuite[]; + /** @deprecated `.tests` has type `Mocha.Test[]` in `Mocha.Suite`. */ tests: ITest[]; - _beforeEach: IHook[]; - _beforeAll: IHook[]; - _afterEach: IHook[]; - _afterAll: IHook[]; - bail(): boolean; + /** @deprecated `.bail()` returns `this` in `Mocha.Suite`. */ bail(bail: boolean): ISuite; fullTitle(): string; retries(): number; + /** @deprecated `.retries()` returns `this` in `Mocha.Suite`. */ retries(retries: number): ISuite; slow(): number; + /** @deprecated `.slow()` returns `this` in `Mocha.Suite`. */ slow(slow: number): ISuite; timeout(): number; + /** @deprecated `.timeout()` returns `this` in `Mocha.Suite`. */ timeout(timeout: number): ISuite; } - class Hook extends Runnable implements IHook { - constructor(title: string, fn: () => any); - - async: boolean; - ctx?: IContext; - duration?: number; - fn: Function; + /** Partial interface for Mocha's `Test` class. */ + /** @deprecated use `Mocha.Test` instead. */ + interface ITest extends IRunnable { + body?: string; + file?: string; + /** @deprecated `.parent` has type `Mocha.Suite | undefined` in `Mocha.Test`. */ parent?: ISuite; - sync: boolean; - timedOut: boolean; - timeout(n: number | string): this; - title: string; - type: 'hook'; + pending: boolean; + state?: 'failed' | 'passed'; + type: 'test'; + fullTitle(): string; + } + /** @deprecated use `Mocha.Hook` instead. */ + interface IHook extends IRunnable { + /** @deprecated `.ctx` has type `Mocha.Context` in `Mocha.Runnable`. */ + ctx?: IContext; + /** @deprecated `.parent` has type `Mocha.Suite` in `Mocha.Runnable`. */ + parent?: ISuite; + type: 'hook'; + /** @deprecated `.error()` has additional overloads in `Mocha.Hook`. */ error(err: Error): void; } - class Test extends Runnable implements ITest { - constructor(title: string, fn: () => any); - - async: boolean; - body?: string; - duration?: number; - file?: string; - fn: Function; - parent: ISuite; - pending: boolean; - state: 'failed' | 'passed' | undefined; - sync: boolean; - timedOut: boolean; - timeout(n: number | string): this; - title: string; - type: 'test'; - - fullTitle(): string; + /** @deprecated use `Mocha.Context` instead. */ + interface IBeforeAndAfterContext extends IHookCallbackContext { + /** @deprecated `.currentTest` has type `Mocha.Test` in `Mocha.Context`. */ + currentTest?: ITest; } - } - declare module "mocha" { - export = Mocha; - } + /** @deprecated use `Mocha.Stats` instead. */ + type IStats = Stats; + + /** Partial interface for Mocha's `Runner` class. */ + /** @deprecated use `Mocha.Runner` instead. */ + interface IRunner extends NodeJS.EventEmitter { + asyncOnly?: boolean; + stats?: IStats; + started: boolean; + /** @deprecated `.suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + suite: ISuite; + total: number; + failures: number; + forbidOnly?: boolean; + forbidPending?: boolean; + fullStackTrace?: boolean; + ignoreLeaks?: boolean; + grep(re: RegExp, invert: boolean): this; + /** @deprecated Parameter `suite` has type `Mocha.Suite` in `Mocha.Runner`. */ + grepTotal(suite: ISuite): number; + /** @deprecated `.globals()` has different overloads in `Mocha.Runner`. */ + globals(arr: ReadonlyArray): this | string[]; + abort(): this; + run(fn?: (failures: number) => void): this; + } + + /** @deprecated use `Mocha.SuiteFunction` instead. */ + interface IContextDefinition { + /** @deprecated use `Mocha.SuiteFunction` instead. */ + (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; + /** @deprecated use `Mocha.SuiteFunction` instead. */ + skip(description: string, callback: (this: ISuiteCallbackContext) => void): void; + } + + /** @deprecated use `Mocha.TestFunction` instead. */ + interface ITestDefinition { + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction` does not allow mixing `done` with a return type of `PromiseLike`. */ + (expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#only` does not allow mixing `done` with a return type of `PromiseLike`. */ + only(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): ITest; + /** @deprecated use `Mocha.TestFunction` instead. */ + /** @deprecated `Mocha.TestFunction#skip` does not allow mixing `done` with a return type of `PromiseLike`. */ + skip(expectation: string, callback?: (this: ITestCallbackContext, done: MochaDone) => PromiseLike | void): void; + } + + // #endregion +} + +declare global { + // #region Test interface augmentations + + /** + * Triggers root suite execution. + * + * - _Only available if flag --delay is passed into Mocha._ + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#runWithSuite + */ + function run(): void; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + var before: Mocha.HookFunction; + + /** + * Execute before running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#before + */ + var suiteSetup: Mocha.HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + var after: Mocha.HookFunction; + + /** + * Execute after running tests. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#after + */ + var suiteTeardown: Mocha.HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + var beforeEach: Mocha.HookFunction; + + /** + * Execute before each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#beforeEach + */ + var setup: Mocha.HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + var afterEach: Mocha.HookFunction; + + /** + * Execute after each test case. + * + * - _Only available when invoked via the mocha CLI._ + * + * @see https://mochajs.org/api/global.html#afterEach + */ + var teardown: Mocha.HookFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var describe: Mocha.SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var context: Mocha.SuiteFunction; + + /** + * Describe a "suite" containing nested suites and tests. + * + * - _Only available when invoked via the mocha CLI._ + */ + var suite: Mocha.SuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xdescribe: Mocha.PendingSuiteFunction; + + /** + * Pending suite. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xcontext: Mocha.PendingSuiteFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var it: Mocha.TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var specify: Mocha.TestFunction; + + /** + * Describes a test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var test: Mocha.TestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xit: Mocha.PendingTestFunction; + + /** + * Describes a pending test case. + * + * - _Only available when invoked via the mocha CLI._ + */ + var xspecify: Mocha.PendingTestFunction; + + // #endregion Test interface augmentations + + // #region Reporter augmentations + + // Forward declaration for `HTMLLIElement` from lib.dom.d.ts. + // Required by Mocha.reporters.HTML. + // NOTE: Mocha *must not* have a direct dependency on DOM types. + // tslint:disable-next-line no-empty-interface + interface HTMLLIElement { } + + // Augments the DOM `Window` object when lib.dom.d.ts is loaded. + // tslint:disable-next-line no-empty-interface + interface Window extends Mocha.MochaGlobals { } + + namespace NodeJS { + // Forward declaration for `NodeJS.EventEmitter` from node.d.ts. + // Required by Mocha.Runnable, Mocha.Runner, and Mocha.Suite. + // NOTE: Mocha *must not* have a direct dependency on @types/node. + // tslint:disable-next-line no-empty-interface + interface EventEmitter { } + + // Augments NodeJS's `global` object when node.d.ts is loaded + // tslint:disable-next-line no-empty-interface + interface Global extends Mocha.MochaGlobals { } + } + + // #endregion Reporter augmentations + + // #region Browser augmentations + + /** + * Mocha global. + * + * - _Only supported in the browser._ + */ + const mocha: BrowserMocha; + + interface BrowserMocha extends Mocha { + /** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + * + * - _Only supported in the browser._ + */ + throwError(err: any): never; + + /** + * Setup mocha with the given settings options. + * + * - _Only supported in the browser._ + */ + setup(opts?: Mocha.Interface | MochaSetupOptions): this; + } + + /** + * Options to pass to `mocha.setup` in the browser. + */ + interface MochaSetupOptions extends Mocha.MochaOptions { + // TODO: This does not seem to be supported according to the source. Should it be removed? + require?: string[]; + fullTrace?: boolean; + } + + // #endregion Browser augmentations + + // #region Deprecations + + /** @deprecated use `Mocha.DoneCallback` instead. */ + type MochaDone = Mocha.Done; + + /** @deprecated use `Mocha.ReporterConstructor` instead. */ + type ReporterConstructor = Mocha.ReporterConstructor; + + // #endregion Deprecations +} diff --git a/types/mocha/lib/interfaces/common.d.ts b/types/mocha/lib/interfaces/common.d.ts new file mode 100644 index 0000000000..9756482354 --- /dev/null +++ b/types/mocha/lib/interfaces/common.d.ts @@ -0,0 +1,109 @@ +import Mocha = require("../../"); + +export = common; + +declare function common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, mocha: Mocha): common.CommonFunctions; + +declare namespace common { + interface CommonFunctions { + /** + * This is only present if flag --delay is passed into Mocha. It triggers + * root suite execution. + */ + runWithSuite(suite: Mocha.Suite): () => void; + + /** + * Execute before running tests. + */ + before(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before running tests. + */ + before(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after running tests. + */ + after(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute before each test case. + */ + beforeEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(fn?: Mocha.Func | Mocha.AsyncFunc): void; + + /** + * Execute after each test case. + */ + afterEach(name: string, fn?: Mocha.Func | Mocha.AsyncFunc): void; + + suite: SuiteFunctions; + test: TestFunctions; + } + + interface CreateOptions { + /** Title of suite */ + title: string; + + /** Suite function */ + fn?: (this: Mocha.Suite) => void; + + /** Is suite pending? */ + pending?: boolean; + + /** Filepath where this Suite resides */ + file?: string; + + /** Is suite exclusive? */ + isOnly?: boolean; + } + + interface SuiteFunctions { + /** + * Create an exclusive Suite; convenience function + */ + only(opts: CreateOptions): Mocha.Suite; + + /** + * Create a Suite, but skip it; convenience function + */ + skip(opts: CreateOptions): Mocha.Suite; + + /** + * Creates a suite. + */ + create(opts: CreateOptions): Mocha.Suite; + } + + interface TestFunctions { + /** + * Exclusive test-case. + */ + only(mocha: Mocha, test: Mocha.Test): Mocha.Test; + + /** + * Pending test case. + */ + skip(title: string): void; + + /** + * Number of retry attempts + */ + retries(n: number): void; + } +} diff --git a/types/mocha/lib/ms.d.ts b/types/mocha/lib/ms.d.ts new file mode 100644 index 0000000000..3b89a55fc5 --- /dev/null +++ b/types/mocha/lib/ms.d.ts @@ -0,0 +1,17 @@ +export = milliseconds; + +/** + * Parse the given `str` and return milliseconds. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~parse} + */ +declare function milliseconds(val: string): number; + +/** + * Format for `ms`. + * + * @see {@link https://mochajs.org/api/module-milliseconds.html} + * @see {@link https://mochajs.org/api/module-milliseconds.html#~format} + */ +declare function milliseconds(val: number): string; diff --git a/types/mocha/mocha-node-tests.ts b/types/mocha/mocha-node-tests.ts deleted file mode 100644 index e5cd80c8cf..0000000000 --- a/types/mocha/mocha-node-tests.ts +++ /dev/null @@ -1,37 +0,0 @@ - - -import MochaDef = require('mocha'); - -class CustomSpecReporter extends MochaDef.reporters.Spec { - constructor(runner: Mocha.IRunner) { - super(runner); - - runner.on('test', (test: Mocha.ITest) => { - console.log(test.parent.title + '/' + test.title); - }); - } -} - -class MyReporter extends MochaDef.reporters.Base { - passes: number = 0; - failures: number = 0; - - constructor(runner: Mocha.IRunner) { - super(runner); - - runner.on('pass', (test: Mocha.ITest) => { - this.passes++; - console.log('pass: %s', test.fullTitle()); - }); - - runner.on('fail', (test: Mocha.ITest, err: Error) => { - this.failures++; - console.log('fail: %s -- error: %s', test.fullTitle(), err.message); - }); - - runner.on('end', () => { - console.log('end: %d/%d', this.passes, this.passes + this.failures); - process.exit(this.failures); - }); - } -} diff --git a/types/mocha/mocha-node.d.ts b/types/mocha/mocha-node.d.ts deleted file mode 100644 index dcee001b54..0000000000 --- a/types/mocha/mocha-node.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for mocha 2.2.5 -// Project: http://mochajs.org/ -// Definitions by: Vadim Macagon , vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -declare namespace Mocha { - interface IRunnable extends NodeJS.EventEmitter { - } - interface ISuite extends NodeJS.EventEmitter { - } - interface IRunner extends NodeJS.EventEmitter { - } -} diff --git a/types/mocha/mocha-tests.ts b/types/mocha/mocha-tests.ts index ec9b238d80..b80d7b415d 100644 --- a/types/mocha/mocha-tests.ts +++ b/types/mocha/mocha-tests.ts @@ -3,36 +3,36 @@ import { before as importedBefore, afterEach as importedAfterEach, beforeEach as importedBeforeEach, - context as importedContext, describe as importedDescribe, it as importedIt, - xdescribe as importedXdescribe, - xit as importedXit, + xit as importedXit } from 'mocha'; -// tslint:disable-next-line -import * as Mocha from 'mocha'; +import LocalMocha = require('mocha'); // Warning!! // Don't refer node.d.ts!! // See #22510. (): number => setTimeout(() => 0, 0); -let boolean: boolean; -let string: string; -let number: number; -let stringOrUndefined: string | undefined; -let dateOrUndefined: Date | undefined; -const resolved = Promise.resolve(); -const rejected = Promise.reject('some error'); +declare let number: number; +declare let boolean: boolean; +declare let string: string; +declare let stringOrUndefined: string | undefined; +declare let any: any; -// Use module augmentation to add a third-party interface +// Use module augmentation to add a third-party interface or reporter declare module 'mocha' { interface InterfaceContributions { - 'third-party-interface': any; + 'third-party-interface': never; + } + interface ReporterContributions { + 'third-party-reporter': never; } } -const i: Mocha.Interface = 'third-party-interface'; + +const thirdPartyInterface: Mocha.Interface = 'third-party-interface'; +const thirdPartyReporter: Mocha.Reporter = 'third-party-reporter'; // Lazy tests of compatibility between imported and global functions; should be identical const _after: typeof after = importedAfter; @@ -43,469 +43,786 @@ const _afterEach: typeof afterEach = importedAfterEach; const _afterEach2: typeof importedAfterEach = afterEach; const _beforeEach: typeof beforeEach = importedBeforeEach; const _beforeEach2: typeof importedBeforeEach = beforeEach; -const _context: typeof context = importedContext; -const _context2: typeof importedContext = context; const _describe: typeof describe = importedDescribe; const _describe2: typeof importedDescribe = describe; const _it: typeof it = importedIt; const _it2: typeof importedIt = it; -const _xdescribe: typeof xdescribe = importedXdescribe; -const _xdescribe2: typeof importedXdescribe = xdescribe; const _xit: typeof xit = importedXit; const _xit2: typeof importedXit = xit; -function test_describe() { - describe('something', () => { }); - - describe.only('something', () => { }); - - describe.skip('something', () => { }); - +function test_bdd_describe() { + // $ExpectType Suite describe('something', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); + // $ExpectType Suite + this; + }); + + // $ExpectType Suite + describe.only('something', function() { + // $ExpectType Suite + this; + }); + + // $ExpectType void | Suite + describe.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_context() { - context('some context', () => { }); +function test_bdd_context() { + // $ExpectType Suite + context('something', function() { + // $ExpectType Suite + this; + }); - context.only('some context', () => { }); + // $ExpectType Suite + context.only('something', function() { + // $ExpectType Suite + this; + }); - context.skip('some context', () => { }); - - context('some context', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); + // $ExpectType void | Suite + context.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_suite() { - suite('some context', () => { }); - - suite.only('some context', () => { }); - - suite.skip('some context', () => { }); - - suite('some context', function() { - this.retries(3).slow(1000).timeout(2000).retries(3); +function test_bdd_xdescribe() { + // $ExpectType void | Suite + xdescribe('something', function() { + // $ExpectType Suite + this; }); } -function test_it() { - it('does something', () => { }).timeout('2s'); - - it('does something', function() { this['sharedState'] = true; }); - - it('does something', (done) => { done(); }); - - it('does something', () => resolved); - it('does something', () => rejected); - - it.only('does something', () => { }); - - it.skip('does something', () => { }); - - it('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); +function test_bdd_xcontext() { + // $ExpectType void | Suite + xcontext('something', function() { + // $ExpectType Suite + this; }); } -function test_test() { - test('does something', () => { }); +function test_tdd_suite() { + // $ExpectType Suite + suite('something', function() { + // $ExpectType Suite + this; + }); - test('does something', function() { this['sharedState'] = true; }); + // $ExpectType Suite + suite.only('something', function() { + // $ExpectType Suite + this; + }); - test('does something', (done) => { done(); }); - - test('does something', () => resolved); - test('does something', () => rejected); - - test.only('does something', () => { }); - - test.skip('does something', () => { }); - - test('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); + // $ExpectType void | Suite + suite.skip('something', function() { + // $ExpectType Suite + this; }); } -function test_specify() { - specify('does something', () => { }); +function test_qunit_suite() { + // $ExpectType Suite + suite('some context'); - specify('does something', function() { this['sharedState'] = true; }); + // $ExpectType Suite + suite.only('some context'); +} - specify('does something', (done) => { done(); }); +function test_bdd_it() { + // $ExpectType Test + it(function doesSomething(done) { + // $ExpectType Done + done; - specify('does something', () => resolved); - specify('does something', () => rejected); + // $ExpectType Context + this; + }); - specify.only('does something', () => { }); + // $ExpectType Test + it(async function doesSomething() { + // $ExpectType Context + this; + }); - specify.skip('does something', () => { }); + // $ExpectType Test + it('does something', function(done) { + // $ExpectType Done + done; - specify('does something', function() { - this.skip().retries(3).slow(1000).timeout(2000).skip(); + // $ExpectType Context + this; + }); + + // $ExpectType Test + it('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + it.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + it.retries(number); +} + +function test_bdd_xit() { + // $ExpectType Test + xit(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xit('does something', async function() { + // $ExpectType Context + this; }); } -function test_before() { - before(() => { }); +function test_bdd_specify() { + // $ExpectType Test + specify(function doesSomething(done) { + // $ExpectType Done + done; - before(function() { this['sharedState'] = true; }); + // $ExpectType Context + this; + }); - before((done) => { done(); }); + // $ExpectType Test + specify(async function doesSomething() { + // $ExpectType Context + this; + }); - before(() => resolved); - before(() => rejected); + // $ExpectType Test + specify('does something', function(done) { + // $ExpectType Done + done; - before("my description", () => { }); + // $ExpectType Context + this; + }); - before("my description", done => { }); + // $ExpectType Test + specify('does something', async function() { + // $ExpectType Context + this; + }); - before("my description", () => resolved); + // $ExpectType Test + specify.only(function doesSomething(done) { + // $ExpectType Done + done; - before("my description", function() { - this.skip().timeout(2000).skip(); + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + specify.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + specify.retries(number); +} + +function test_bdd_xspecify() { + // $ExpectType Test + xspecify(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + xspecify('does something', async function() { + // $ExpectType Context + this; }); } -function test_setup() { - setup(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; +function test_tdd_qunit_test() { + // $ExpectType Test + test(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; }); - setup(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Test + test(async function doesSomething() { + // $ExpectType Context + this; }); + // $ExpectType Test + test('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.only('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip(function doesSomething(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip(async function doesSomething() { + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip('does something', function(done) { + // $ExpectType Done + done; + + // $ExpectType Context + this; + }); + + // $ExpectType Test + test.skip('does something', async function() { + // $ExpectType Context + this; + }); + + // $ExpectType void + test.retries(number); +} + +function test_bdd_qunit_before() { + before(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + before(async function() { + // $ExpectType Context + this; + }); + + before('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + before('description', async function() { + // $ExpectType Context + this; + }); +} + +function test_tdd_setup() { setup(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - setup(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + setup(async function() { + // $ExpectType Context + this; + }); + + setup('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + setup('description', async function() { + // $ExpectType Context + this; }); } -function test_after() { - after(() => { }); +function test_bdd_qunit_after() { + after(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - after(function() { this['sharedState'] = true; }); + after(async function() { + // $ExpectType Context + this; + }); - after((done) => { done(); }); + after('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - after(() => resolved); - - after("my description", () => { }); - - after("my description", done => { }); - - after("my description", () => resolved); + after('description', async function() { + // $ExpectType Context + this; + }); } -function test_teardown() { - teardown(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - teardown(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_tdd_teardown() { teardown(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - teardown(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + teardown(async function() { + // $ExpectType Context + this; + }); + + teardown('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); + + teardown('description', async function() { + // $ExpectType Context + this; }); } -function test_beforeEach() { - beforeEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - beforeEach(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_bdd_qunit_beforeEach() { beforeEach(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - beforeEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + beforeEach(async function() { + // $ExpectType Context + this; }); - beforeEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + beforeEach('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; }); - beforeEach("my description", function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - beforeEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + beforeEach('description', async function() { + // $ExpectType Context + this; }); } -function test_suiteSetup() { - suiteSetup(() => { }); +function test_tdd_suiteSetup() { + suiteSetup(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteSetup(function() { this['sharedState'] = true; }); + suiteSetup(async function() { + // $ExpectType Context + this; + }); - suiteSetup((done) => { done(); }); + suiteSetup('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteSetup(() => resolved); + suiteSetup('description', async function() { + // $ExpectType Context + this; + }); } -function test_afterEach() { - afterEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - afterEach(function() { - this['sharedState'] = true; - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - +function test_bdd_qunit_afterEach() { afterEach(function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + // $ExpectType Done + done; + // $ExpectType Context + this; }); - afterEach(function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + afterEach(async function() { + // $ExpectType Context + this; }); - afterEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; + afterEach('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; }); - afterEach("my description", function(done) { - done(); - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - }); - - afterEach("my description", function() { - boolean = this.currentTest.async; - boolean = this.currentTest.pending; - boolean = this.currentTest.sync; - boolean = this.currentTest.timedOut; - string = this.currentTest.title; - string = this.currentTest.fullTitle(); - stringOrUndefined = this.currentTest.state; - return resolved; + afterEach('description', async function() { + // $ExpectType Context + this; }); } -function test_suiteTeardown() { - suiteTeardown(() => { }); +function test_tdd_suiteTeardown() { + suiteTeardown(function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteTeardown(function() { this['sharedState'] = true; }); + suiteTeardown(async function() { + // $ExpectType Context + this; + }); - suiteTeardown((done) => { done(); }); + suiteTeardown('description', function(done) { + // $ExpectType Done + done; + // $ExpectType Context + this; + }); - suiteTeardown(() => resolved); + suiteTeardown('description', async function() { + // $ExpectType Context + this; + }); } -function test_reporter_string() { +function test_Context(ctx: LocalMocha.Context, runnable: LocalMocha.Runnable) { + // $ExpectType never + ctx.skip(); // throws + + // $ExpectType boolean + ctx.enableTimeouts(); + + // $ExpectType Context + ctx.enableTimeouts(boolean); + + // $ExpectType number + ctx.retries(); + + // $ExpectType Context + ctx.retries(number); + + // $ExpectType Runnable + ctx.runnable(); + + // $ExpectType Context + ctx.runnable(runnable); + + // $ExpectType number + ctx.slow(); + + // $ExpectType Context + ctx.slow(number); + + // $ExpectType number + ctx.timeout(); + + // $ExpectType Context + ctx.timeout(number); + + // $ExpectType Test | undefined + ctx.currentTest; + + // $ExpectType Runnable | undefined + ctx.test; + + ctx["extended"] = any; + + // $ExpectType any + ctx["extended"]; + + ctx.enableTimeouts(boolean) + .retries(number) + .runnable(runnable) + .slow(number) + .timeout(number) + .skip(); +} + +function test_reporter_string(localMocha: LocalMocha) { + // $ExpectType BrowserMocha mocha.reporter('html'); + + // $ExpectType Mocha + localMocha.reporter('html'); } -function test_reporter_function() { - mocha.reporter(class { }); +function test_reporter_function(localMocha: LocalMocha) { + // $ExpectType BrowserMocha + mocha.reporter(class extends LocalMocha.reporters.Base { }); + + // $ExpectType Mocha + localMocha.reporter(class extends LocalMocha.reporters.Base { }); } -function test_setup_slow_option() { - new Mocha({ slow: 25 }); +function test_browser_mocha_setup_slow_option() { + // $ExpectType BrowserMocha + mocha.setup({ slow: 25 }); } -function test_setup_timeout_option() { - new Mocha({ timeout: 25 }); +function test_browser_mocha_setup_timeout_option() { + // $ExpectType BrowserMocha + mocha.setup({ timeout: 25 }); } -function test_setup_globals_option() { - new Mocha({ globals: ['mocha'] }); +function test_browser_mocha_setup_globals_option() { + // $ExpectType BrowserMocha + mocha.setup({ globals: ['mocha'] }); } -function test_setup_ui_option() { - new Mocha({ ui: 'bdd' }); +function test_browser_mocha_setup_ui_option() { + // $ExpectType BrowserMocha + mocha.setup({ ui: 'bdd' }); } -function test_setup_reporter_string_option() { - new Mocha({ reporter: 'html' }); +function test_browser_mocha_setup_reporter_string_option() { + // $ExpectType BrowserMocha + mocha.setup({ reporter: 'html' }); } -function test_setup_require_stringArray_option() { - new Mocha({ require: ['ts-node/register'] }); +function test_browser_mocha_setup_require_stringArray_option() { + // $ExpectType BrowserMocha + mocha.setup({ require: ['ts-node/register'] }); } -function test_setup_reporter_function_option() { - new Mocha({ reporter: class { } }); +function test_browser_mocha_setup_reporter_function_option() { + // $ExpectType BrowserMocha + mocha.setup({ reporter: class extends LocalMocha.reporters.Base { } }); } -function test_setup_bail_option() { - new Mocha({ bail: false }); +function test_browser_mocha_setup_bail_option() { + // $ExpectType BrowserMocha + mocha.setup({ bail: false }); } -function test_setup_ignore_leaks_option() { - new Mocha({ ignoreLeaks: false }); +function test_browser_mocha_setup_ignore_leaks_option() { + // $ExpectType BrowserMocha + mocha.setup({ ignoreLeaks: false }); } -function test_setup_grep_string_option() { - new Mocha({ grep: "describe" }); +function test_browser_mocha_setup_grep_string_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: "describe" }); } -function test_setup_grep_regex_option() { - new Mocha({ grep: new RegExp('describe') }); +function test_browser_mocha_setup_grep_regex_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: new RegExp('describe') }); } -function test_setup_grep_regex_literal_option() { - new Mocha({ grep: /(expect|should)/i }); +function test_browser_mocha_setup_grep_regex_literal_option() { + // $ExpectType BrowserMocha + mocha.setup({ grep: /(expect|should)/i }); } -function test_setup_all_options() { - new Mocha({ +function test_browser_mocha_setup_all_options() { + // $ExpectType BrowserMocha + mocha.setup({ slow: 25, timeout: 25, ui: 'bdd', @@ -514,12 +831,97 @@ function test_setup_all_options() { bail: true, ignoreLeaks: true, grep: 'test', - require: ['ts-node/register'] + require: ['ts-node/register'] // TODO: It doesn't appear this is actually supported. Should it be removed? }); } -function test_run() { - mocha.run(() => {}); +function test_constructor_slow_option() { + // $ExpectType Mocha + new LocalMocha({ slow: 25 }); +} + +function test_constructor_timeout_option() { + // $ExpectType Mocha + new LocalMocha({ timeout: 25 }); +} + +function test_constructor_globals_option() { + // $ExpectType Mocha + new LocalMocha({ globals: ['mocha'] }); +} + +function test_constructor_ui_option() { + // $ExpectType Mocha + new LocalMocha({ ui: 'bdd' }); +} + +function test_constructor_reporter_string_option() { + // $ExpectType Mocha + new LocalMocha({ reporter: 'html' }); +} + +function test_constructor_reporter_function_option() { + // $ExpectType Mocha + new LocalMocha({ reporter: class extends LocalMocha.reporters.Base { } }); +} + +function test_constructor_bail_option() { + // $ExpectType Mocha + new LocalMocha({ bail: false }); +} + +function test_constructor_ignore_leaks_option() { + // $ExpectType Mocha + new LocalMocha({ ignoreLeaks: false }); +} + +function test_constructor_grep_string_option() { + // $ExpectType Mocha + new LocalMocha({ grep: "describe" }); +} + +function test_constructor_grep_regex_option() { + // $ExpectType Mocha + new LocalMocha({ grep: new RegExp('describe') }); +} + +function test_constructor_grep_regex_literal_option() { + // $ExpectType Mocha + new LocalMocha({ grep: /(expect|should)/i }); +} + +function test_constructor_all_options() { + // $ExpectType Mocha + new LocalMocha({ + slow: 25, + timeout: 25, + ui: 'bdd', + globals: ['mocha'], + reporter: 'html', + bail: true, + ignoreLeaks: true, + grep: 'test' + }); +} + +function test_run(localMocha: LocalMocha) { + // $ExpectType Runner + mocha.run(); + + // $ExpectType Runner + mocha.run((failures) => { + // $ExpectType number + failures; + }); + + // $ExpectType Runner + localMocha.run(); + + // $ExpectType Runner + localMocha.run((failures) => { + // $ExpectType number + failures; + }); } function test_growl() { @@ -527,24 +929,22 @@ function test_growl() { } function test_chaining() { - new Mocha({ slow: 25 }) + new LocalMocha({ slow: 25 }) .growl() .reporter('html') - .reporter(class { }); + .reporter(class extends LocalMocha.reporters.Base { }); } -import MochaDef = require('mocha'); - function test_require_constructor_empty() { - const instance = new MochaDef(); + const instance = new LocalMocha(); } function test_require_constructor_noOptions() { - const instance = new MochaDef({}); + const instance = new LocalMocha({}); } function test_require_constructor_allOptions() { - const instance = new MochaDef({ + const instance = new LocalMocha({ grep: /[a-z]*/, ui: 'tdd', reporter: 'dot', @@ -554,13 +954,13 @@ function test_require_constructor_allOptions() { } function test_require_fluentParams() { - const instance = new MochaDef(); + const instance = new LocalMocha(); instance.bail(true) .bail() .addFile('foo.js') - .reporter('bdd') - .ui('dot') + .reporter('dot') + .ui('bdd') .grep('[a-z]*') .grep(/[a-z]*/) .invert() @@ -574,60 +974,290 @@ function test_require_fluentParams() { .timeout(500) .slow(100) .enableTimeouts(true) - .asyncOnly(false) - .noHighlighting(true) + .asyncOnly() + .noHighlighting() .run(); } -function test_run_withOnComplete() { - const instance = new MochaDef(); - - instance.run((failures: number): void => { - console.log(failures); - }); -} - function test_throwError() { mocha.throwError(new Error("I'm an error!")); } -function test_mochaRunner_properties(runner: MochaDef.IRunner, suite: MochaDef.ISuite) { - runner = runner.abort(); +function test_mochaRunner_properties(runner: LocalMocha.Runner, suite: LocalMocha.Suite) { + // $Expecttype Runner + runner.abort(); - if (runner.stats !== undefined) { - number = runner.stats.failures; - number = runner.stats.passes; - number = runner.stats.pending; - number = runner.stats.suites; - number = runner.stats.tests; + // $ExpectType Suite + runner.suite; - dateOrUndefined = runner.stats.start; - dateOrUndefined = runner.stats.end; - dateOrUndefined = runner.stats.duration; - } + // $ExpectType boolean + runner.started; - const s: MochaDef.ISuite = runner.suite; - boolean = runner.started; - number = runner.total; - number = runner.failures; + // $ExpectType number + runner.total; - runner = runner.grep("regex", false); - number = runner.grepTotal(suite); + // $ExpectType number + runner.failures; - const globals: string[] | MochaDef.IRunner = runner.globals(["hello", "world"]); + // $ExpectType Runner + runner.grep(/regex/, false); - runner = runner.run(); - runner = runner.run((f: number) => {}); + // $ExpectType number + runner.grepTotal(suite); + + // $ExpectType string[] + runner.globals(); + + // $ExpectType Runner + runner.globals(["hello", "world"]); + + // $ExpectType Runner + runner.run(); + + // $ExpectType Runner + runner.run((failures) => { + // $ExpectType number + failures; + }); } -function test_base_reporter_properties(reporter: MochaDef.reporters.Base) { - number = reporter.stats.failures; - number = reporter.stats.passes; - number = reporter.stats.pending; - number = reporter.stats.suites; - number = reporter.stats.tests; +function test_base_reporter_properties(reporter: LocalMocha.reporters.Base) { + // $ExpectType number + reporter.stats.failures; - dateOrUndefined = reporter.stats.start; - dateOrUndefined = reporter.stats.end; - dateOrUndefined = reporter.stats.duration; + // $ExpectType number + reporter.stats.passes; + + // $ExpectType number + reporter.stats.pending; + + // $ExpectType number + reporter.stats.suites; + + // $ExpectType number + reporter.stats.tests; + + // $ExpectType Date | undefined + reporter.stats.start; + + // $ExpectType Date | undefined + reporter.stats.end; + + // $ExpectType number | undefined + reporter.stats.duration; +} + +function test_runner_events(runner: LocalMocha.Runner) { + // $ExpectType Runner + runner.on("start", () => {}); + + // $ExpectType Runner + runner.on("end", () => {}); + + // $ExpectType Runner + runner.on("suite", (suite) => { + // $ExpectType Suite + suite; + }); + + // $ExpectType Runner + runner.on("suite end", (suite) => { + // $ExpectType Suite + suite; + }); + + // $ExpectType Runner + runner.on("test", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("test end", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("hook", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Runner + runner.on("hook end", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Runner + runner.on("pass", (test) => { + // $ExpectType Test + test; + }); + + // $ExpectType Runner + runner.on("fail", (test, err) => { + // $ExpectType Test + test; + + // $ExpectType any + err; + }); + + // $ExpectType Runner + runner.on("pending", (test) => { + // $ExpectType Test + test; + }); +} + +function test_runnable_events(runnable: LocalMocha.Runnable) { + // $ExpectType Runnable + runnable.on("error", (error) => { + // $ExpectType any + error; + }); +} + +function test_suite_events(suite: LocalMocha.Suite) { + // $ExpectType Suite + suite.on("beforeAll", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("afterAll", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("beforeEach", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("afterEach", (hook) => { + // $ExpectType Hook + hook; + }); + + // $ExpectType Suite + suite.on("run", () => { }); + + // $ExpectType Suite + suite.on("pre-require", (context, file, mocha) => { + // $ExpectType MochaGlobals + context; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); + + // $ExpectType Suite + suite.on("require", (module, file, mocha) => { + // $ExpectType any + module; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); + + // $ExpectType Suite + suite.on("post-require", (context, file, mocha) => { + // $ExpectType MochaGlobals + context; + // $ExpectType string + file; + // $ExpectType Mocha + mocha; + }); +} + +function test_backcompat_Suite(suite: Mocha.Suite, iSuite: Mocha.ISuite, iSuiteContext: Mocha.ISuiteCallbackContext, iTest: Mocha.ITest, iContext: Mocha.IContext) { + iSuite = suite; + iSuiteContext = suite; + suite.addTest(iTest); + suite.addSuite(iSuite); + LocalMocha.Suite.create(iSuite, string); + new LocalMocha.Suite(string, iContext); +} + +function test_backcompat_Runner(runner: Mocha.Runner, iRunner: Mocha.IRunner, iSuite: Mocha.ISuite) { + iRunner = runner; + runner.grepTotal(iSuite); +} + +function test_backcompat_Runnable(runnable: Mocha.Runnable, iRunnable: Mocha.IRunnable) { + iRunnable = runnable; +} + +function test_backcompat_Test(test: Mocha.Test, iTest: Mocha.ITest) { + iTest = test; +} + +function test_backcompat_Hook(hook: Mocha.Hook, iHook: Mocha.IHook) { + iHook = hook; +} + +function test_backcompat_Context(context: Mocha.Context, iContext: Mocha.IContext, + iHookContext: Mocha.IHookCallbackContext, iBeforeAfterContext: Mocha.IBeforeAndAfterContext, + iTestContext: Mocha.ITestCallbackContext, iRunnable: Mocha.IRunnable) { + iContext = context; + iHookContext = context; + iBeforeAfterContext = context; + iTestContext = context; + context.runnable(iRunnable); +} + +function test_backcompat_Base(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.Base(iRunner); +} + +function test_backcompat_XUnit(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.XUnit(iRunner); +} + +function test_backcompat_Progress(iRunner: Mocha.IRunner) { + new LocalMocha.reporters.Progress(iRunner); +} + +import common = require("mocha/lib/interfaces/common"); + +function test_interfaces_common(suites: Mocha.Suite[], context: Mocha.MochaGlobals, localMocha: Mocha, + fn: Mocha.Func | Mocha.AsyncFunc, test: Mocha.Test) { + const funcs = common(suites, context, localMocha); + // $ExpectType CommonFunctions + funcs; + + funcs.before(fn); + funcs.before(string, fn); + funcs.beforeEach(fn); + funcs.beforeEach(string, fn); + funcs.after(fn); + funcs.after(string, fn); + funcs.afterEach(fn); + funcs.afterEach(string, fn); + + // $ExpectType Suite + funcs.suite.create({ title: string }); + funcs.suite.create({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Suite + funcs.suite.only({ title: string }); + funcs.suite.only({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Suite + funcs.suite.skip({ title: string }); + funcs.suite.skip({ title: string, file: string, fn: () => {}, pending: boolean, isOnly: boolean }); + + // $ExpectType Test + funcs.test.only(mocha, test); + funcs.test.skip(string); + funcs.test.retries(number); } diff --git a/types/mocha/tsconfig.json b/types/mocha/tsconfig.json index 6e88356fe4..f26091927f 100644 --- a/types/mocha/tsconfig.json +++ b/types/mocha/tsconfig.json @@ -19,6 +19,8 @@ }, "files": [ "index.d.ts", + "lib/ms.d.ts", + "lib/interfaces/common.d.ts", "mocha-tests.ts" ] } \ No newline at end of file diff --git a/types/moment-duration-format/index.d.ts b/types/moment-duration-format/index.d.ts index 4506311ab6..1716d55d83 100644 --- a/types/moment-duration-format/index.d.ts +++ b/types/moment-duration-format/index.d.ts @@ -80,12 +80,12 @@ declare module "moment" { } interface LocaleSpecification { - durationLabelsLong: DurationLabelDef; - durationLabelsStandard: DurationLabelDef; - durationLabelsShort: DurationLabelDef; - durationTimeTemplates: DurationTimeDef; - durationLabelTypes: DurationLabelTypeDef[]; - durationPluralKey: (token: string, integerValue: number, decimalValue: number) => string; + durationLabelsLong?: DurationLabelDef; + durationLabelsStandard?: DurationLabelDef; + durationLabelsShort?: DurationLabelDef; + durationTimeTemplates?: DurationTimeDef; + durationLabelTypes?: DurationLabelTypeDef[]; + durationPluralKey?: (token: string, integerValue: number, decimalValue: number) => string; } type TemplateFunction = ((this: DurationFormatSettings) => string); diff --git a/types/moment-shortformat/index.d.ts b/types/moment-shortformat/index.d.ts new file mode 100644 index 0000000000..d5125aac49 --- /dev/null +++ b/types/moment-shortformat/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for moment-shortformat 2.1 +// Project: https://github.com/researchgate/moment-shortformat#readme +// Definitions by: whatasoda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace moment; + +import moment = require('moment'); + +export = moment; + +declare module 'moment' { + interface Moment { + short(withoutPreOrSuffix?: boolean, now?: Moment): string; + } +} diff --git a/types/moment-shortformat/moment-shortformat-tests.ts b/types/moment-shortformat/moment-shortformat-tests.ts new file mode 100644 index 0000000000..84f754a750 --- /dev/null +++ b/types/moment-shortformat/moment-shortformat-tests.ts @@ -0,0 +1,20 @@ +import moment = require('moment'); +import 'moment-shortformat'; + +let formatted: string; +/*~ Formats time relative to current time. */ +formatted = moment(moment().valueOf() + (36e5 * 5)).short(); // 'in 5h' +formatted = moment(moment().valueOf() - (36e5 * 5)).short(); // '5h ago' +formatted = moment(moment().valueOf() + (36e5 * 5)).short(true); // '5h' +formatted = moment(moment().valueOf() - (36e5 * 5)).short(true); // '5h' + +/*~ Times greater than 1 week are converted to dates like Mar 7, + *~ or if the year of the date does not match the current year + *~ it is convert to Mar 7, 2031 + */ +formatted = moment(moment().valueOf() + 6048e5).short(); // 'Mar 7' + +/*~ Using a different "now" */ +formatted = moment(moment().valueOf() + (36e5 * 5)).short( + false, moment(moment().valueOf() + (36e5 * 3)) +); // 'in 2h' diff --git a/types/moment-shortformat/tsconfig.json b/types/moment-shortformat/tsconfig.json new file mode 100644 index 0000000000..96fd6c6524 --- /dev/null +++ b/types/moment-shortformat/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moment-shortformat-tests.ts" + ] +} diff --git a/types/moment-shortformat/tslint.json b/types/moment-shortformat/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-shortformat/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 98aa2daca8..3048da4dd4 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1252,7 +1252,7 @@ export class Cursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#limit */ limit(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#map */ - map(transform: Function): Cursor; + map(transform: (document: T) => U): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#max */ max(max: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#maxAwaitTimeMS */ diff --git a/types/mongodb/tsconfig.json b/types/mongodb/tsconfig.json index 8ed16ed7e6..aae592b3bd 100644 --- a/types/mongodb/tsconfig.json +++ b/types/mongodb/tsconfig.json @@ -4,7 +4,7 @@ "lib": [ "es6" ], - "noImplicitAny": false, + "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 59a5c95989..d67c143da1 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -103,7 +103,10 @@ declare module "mongoose" { export function createConnection(): Connection; export function createConnection(uri: string, options?: ConnectionOptions - ): Connection; + ): Connection & { + then: Promise["then"]; + catch: Promise["catch"]; + }; /** * Disconnects all connections. @@ -201,7 +204,7 @@ declare module "mongoose" { */ open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - + /** * Opens the connection to MongoDB. * @param mongodb://uri or the host to which you are connecting @@ -451,9 +454,6 @@ declare module "mongoose" { /** Expose the possible connection states. */ static STATES: any; - - then: Promise["then"]; - catch: Promise["catch"]; } /* @@ -854,6 +854,8 @@ declare module "mongoose" { typeKey?: string; /** defaults to false */ useNestedStrict?: boolean; + /** defaults to false */ + usePushEach?: boolean; /** defaults to true */ validateBeforeSave?: boolean; /** defaults to "__v" */ @@ -2274,6 +2276,12 @@ declare module "mongoose" { /** Adds a collation. */ collation(options: CollationOptions): this; + /** + * Appends a new $count operator to this aggregate pipeline. + * @param countName name of the count field + */ + count(countName: string): this; + /** * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). * Note the different syntax below: .exec() returns a cursor object, and no callback @@ -2727,9 +2735,9 @@ declare module "mongoose" { * This function does not trigger save middleware. * @param docs Documents to insert. * @param options Optional settings. - * @param options.ordered if true, will fail fast on the first error encountered. + * @param options.ordered if true, will fail fast on the first error encountered. * If false, will insert all the documents it can and report errors later. - * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. + * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. * If `false`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 90b6fc2561..796ae086e3 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -161,6 +161,13 @@ mongoose.Connection.STATES.hasOwnProperty(''); conn1.on('data', cb); conn1.addListener('close', cb); +// The connection returned by useDb is *not* thenable. +// From https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26057#issuecomment-396150819 +const getDB = async (tenant: string)=> { + return conn1.useDb(tenant); +}; + + /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js @@ -1193,6 +1200,7 @@ aggregate.allowDiskUse(true).allowDiskUse(false, []); aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); aggregate.collation({ locale: 'en_US', strength: 1 }); +aggregate.count('countName'); aggregate.cursor({ batchSize: 1000 }).exec().each(cb); aggregate.exec().then(cb).catch(cb); aggregate.option({foo: 'bar'}).exec(); diff --git a/types/mozilla-readability/tsconfig.json b/types/mozilla-readability/tsconfig.json index 6ec688cf2f..9679936061 100644 --- a/types/mozilla-readability/tsconfig.json +++ b/types/mozilla-readability/tsconfig.json @@ -15,10 +15,13 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "paths": { + "parse5": [ "parse5/v4" ] + } }, "files": [ "index.d.ts", "mozilla-readability-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/multer/index.d.ts b/types/multer/index.d.ts index d019b9fdcb..7d2bfefc26 100644 --- a/types/multer/index.d.ts +++ b/types/multer/index.d.ts @@ -71,6 +71,8 @@ declare namespace multer { fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ any(): express.RequestHandler; + /** Accept only text fields. If any file upload is made, error with code “LIMIT_UNEXPECTED_FILE” will be issued. This is the same as doing upload.fields([]). */ + none(): express.RequestHandler; } } diff --git a/types/named-routes/index.d.ts b/types/named-routes/index.d.ts new file mode 100644 index 0000000000..b983ba1911 --- /dev/null +++ b/types/named-routes/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for named-routes 2.0 +// Project: https://github.com/alubbe/named-routes#readme +// Definitions by: Philipp Katz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as express from 'express'; + +declare module 'express-serve-static-core' { + interface Application { + namedRoutes: NamedRouter; + } + // tslint:disable-next-line interface-name + interface IRouterMatcher { + (path: PathParams, name: string, ...handlers: RequestHandler[]): T; + (path: PathParams, name: string, ...handlers: RequestHandlerParams[]): T; + } +} + +interface RouterOptions { + caseSensitive: boolean; +} + +interface RouteOptions { + name: string; + recursiveWildcard: boolean; + caseSensitive: boolean; + wildcardInPairs: boolean; +} + +interface RouteParams { + [ key: string ]: string | string[] | number | number[] | boolean | boolean[] | null; +} + +declare class NamedRouter { + constructor(options?: Partial); + match(req: express.Request): boolean | object; + add(method: string, path: string, callbacks: express.RequestHandler | express.RequestHandler[], options?: Partial): void; + build(name: string, params?: RouteParams, method?: string): string; + registerAppHelpers(app: express.Express): NamedRouter; + param(name: string, callback: express.RequestHandler): NamedRouter; + param(callback: express.RequestHandler): NamedRouter; + dispatch(req: express.Request, res?: express.Response, next?: express.NextFunction): void; + extendExpress(app: express.Express | express.Router): NamedRouter; +} + +export = NamedRouter; diff --git a/types/named-routes/named-routes-tests.ts b/types/named-routes/named-routes-tests.ts new file mode 100644 index 0000000000..9b424a2c45 --- /dev/null +++ b/types/named-routes/named-routes-tests.ts @@ -0,0 +1,35 @@ +import NamedRouter = require('named-routes'); +import * as express from 'express'; +const app = express(); + +// constructor and `RouterOptions` +let router = new NamedRouter(); +router = new NamedRouter({ caseSensitive: true }); + +router.extendExpress(app); // $ExpectType NamedRouter +router.registerAppHelpers(app); // $ExpectType NamedRouter +app.get('/path/:id', 'foo', () => {}); // $ExpectType Express +app.namedRoutes.build('foo', { id: 1 }); // $ExpectType string + +const expressRouter = express.Router(); +router.extendExpress(expressRouter); // $ExpectType NamedRouter +expressRouter.post('/path/:id', 'foo', () => {}); // $ExpectType Router + +// `RouteOptions` +router.add('get', '/path/:id', () => {}); // $ExpectType void +router.add('get', '/path/:id', () => {}, { name: 'foo' }); // $ExpectType void +router.add('get', '/path/:id', () => {}, { name: 'foo', recursiveWildcard: true }); // $ExpectType void +router.add('get', '/path/:id', () => {}, { name: 'foo', caseSensitive: true }); // $ExpectType void +router.add('get', '/path/:id', () => {}, { name: 'foo', wildcardInPairs: true }); // $ExpectType void + +// `RouteParams` +router.build('foo', { string: 'a' }); // $ExpectType string +router.build('foo', { stringArray: [ 'a', 'b' ] }); // $ExpectType string +router.build('foo', { number: 1 }); // $ExpectType string +router.build('foo', { numberArray: [ 1, 2 ] }); // $ExpectType string +router.build('foo', { boolean: true }); // $ExpectType string +router.build('foo', { booleanArray: [ true, false ] }); // $ExpectType string +router.build('foo', { null: null }); // $ExpectType string + +const req: express.Request = {} as any; +router.dispatch(req); // $ExpectType void diff --git a/types/named-routes/tsconfig.json b/types/named-routes/tsconfig.json new file mode 100644 index 0000000000..28060f592f --- /dev/null +++ b/types/named-routes/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "named-routes-tests.ts" + ] +} diff --git a/types/named-routes/tslint.json b/types/named-routes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/named-routes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/navermaps/index.d.ts b/types/navermaps/index.d.ts index ec857696bf..8ba4d52bd5 100644 --- a/types/navermaps/index.d.ts +++ b/types/navermaps/index.d.ts @@ -39,7 +39,7 @@ declare namespace naver.maps { */ interface MapEventListener { eventName: string; - listener: () => any; + listener: (event: any) => any; listenerId: string; target: any; } @@ -1303,14 +1303,14 @@ declare namespace naver.maps { function Event(): void; namespace Event { - function addDOMListener(element: HTMLElement, eventName: string, listener: () => any): void; - function addListener(target: any, eventName: string, listener: () => any): MapEventListener; + function addDOMListener(element: HTMLElement, eventName: string, listener: (event: any) => any): void; + function addListener(target: any, eventName: string, listener: (event: any) => any): MapEventListener; function clearInstanceListeners(target: any): void; function clearListeners(target: any, fromEventName: string): void; function forward(source: any, fromEventName: string, target: any, toEventName: string): MapEventListener; function hasListener(target: any, eventName: string): boolean; - function once(target: any, eventName: string, listener: () => any): MapEventListener; - function removeDOMListener(element: HTMLElement, eventName: string, listener: () => any): void; + function once(target: any, eventName: string, listener: (event: any) => any): MapEventListener; + function removeDOMListener(element: HTMLElement, eventName: string, listener: (event: any) => any): void; function removeDOMListener(listeners: DOMEventListener | DOMEventListener[]): void; function removeListener(listeners: MapEventListener | MapEventListener[]): void; function resumeDispatch(target: any, eventName: string): void; diff --git a/types/new-relic-browser/index.d.ts b/types/new-relic-browser/index.d.ts index 0064ee4ad2..6d9fc22fdc 100644 --- a/types/new-relic-browser/index.d.ts +++ b/types/new-relic-browser/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Rene Hamburger , Piotr Kubisa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare const newrelic: NewRelic.Browser; - declare namespace NewRelic { interface Browser { /** @@ -186,7 +184,7 @@ declare namespace NewRelic { * Adds a custom SPA attribute only to the current interaction in New Relic Browser. * * @param key Used as the attribute name on the BrowserInteraction event. - * @param Used as the attribute value on the BrowserInteraction event. This can be a + * @param value Used as the attribute value on the BrowserInteraction event. This can be a * string, number, boolean, or object. If it is an object, New Relic serializes it to a JSON string. * @returns This method returns the same API object created by interaction(). * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-set-attribute @@ -205,3 +203,6 @@ declare namespace NewRelic { setName(name: string, trigger?: string): BrowserInteraction; } } + +declare const api: NewRelic.Browser; +export = api; diff --git a/types/new-relic-browser/new-relic-browser-tests.ts b/types/new-relic-browser/new-relic-browser-tests.ts index b9f75b142d..86ce781e18 100644 --- a/types/new-relic-browser/new-relic-browser-tests.ts +++ b/types/new-relic-browser/new-relic-browser-tests.ts @@ -1,3 +1,5 @@ +import newrelic = require("new-relic-browser"); + // The following tests are largely taken straight from the examples at https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api // --- NewRelic.Browser methods ---------------------------------------------- diff --git a/types/next/app.d.ts b/types/next/app.d.ts new file mode 100644 index 0000000000..18bca653cf --- /dev/null +++ b/types/next/app.d.ts @@ -0,0 +1,18 @@ +import * as React from "react"; +import { NextContext } from "."; +import { SingletonRouter } from "./router"; + +export interface AppComponentProps { + Component: React.ComponentType; + pageProps: any; +} + +export interface AppComponentContext { + Component: React.ComponentType; + router: SingletonRouter; + ctx: NextContext; +} + +export class Container extends React.Component {} + +export default class App extends React.Component {} diff --git a/types/next/document.d.ts b/types/next/document.d.ts index b8ae0864ba..38e20e00c0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,30 +1,5 @@ import * as React from "react"; -import * as http from "http"; - -export interface Context { - err?: Error; - req: http.IncomingMessage; - res: http.ServerResponse; - pathname: string; - query?: { - [key: string]: - | boolean - | boolean[] - | number - | number[] - | string - | string[]; - }; - asPath: string; - - renderPage( - enhancer?: (page: React.Component) => React.ComponentType - ): { - html?: string; - head: Array>; - errorHtml: string; - }; -} +import { NextContext } from "."; export interface DocumentProps { __NEXT_DATA__?: any; @@ -38,9 +13,21 @@ export interface DocumentProps { [key: string]: any; } +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage( + cb?: (enhancer: () => JSX.Element) => React.ComponentType + ): { + [key: string]: any + }; +} + export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} export default class extends React.Component { - static getInitialProps(ctx: Context): DocumentProps; + static getInitialProps(ctx: NextContext): DocumentProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 34bdba9047..95395bc2b8 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,7 +1,10 @@ -// Type definitions for next 2.4 +// Type definitions for next 6.0 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Brice BERNARD +// James Hegedus +// Resi Respati +// Scott Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -10,7 +13,44 @@ import * as http from "http"; import * as url from "url"; +import { Response as NodeResponse } from "node-fetch"; + declare namespace next { + /** + * Context object used in methods like `getInitialProps()` + * <> + */ + interface NextContext { + /** path section of URL */ + pathname: string; + /** query string section of URL parsed as an object */ + query: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + /** String of the actual path (including the query) shows in the browser */ + asPath: string; + /** HTTP request object (server only) */ + req?: http.IncomingMessage; + /** HTTP response object (server only) */ + res?: http.ServerResponse; + /** Fetch Response object (client only) - from https://developer.mozilla.org/en-US/docs/Web/API/Response */ + jsonPageRes?: NodeResponse; + /** Error object if any error is encountered during the rendering */ + err?: Error; + } + + type NextSFC = NextStatelessComponent; + interface NextStatelessComponent + extends React.StatelessComponent { + getInitialProps?: (ctx: NextContext) => Promise; + } + type UrlLike = url.UrlObject | url.Url; interface ServerConfig { @@ -40,12 +80,12 @@ declare namespace next { handleRequest( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; getRequestHandler(): ( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ) => Promise; prepare(): Promise; close(): Promise; @@ -54,7 +94,7 @@ declare namespace next { run( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; render( @@ -70,7 +110,7 @@ declare namespace next { | string | string[]; }, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; renderError( err: any, @@ -85,12 +125,12 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; render404( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; renderToHTML( req: http.IncomingMessage, @@ -104,7 +144,7 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; renderErrorToHTML( err: any, @@ -119,13 +159,13 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; serveStatic( req: http.IncomingMessage, res: http.ServerResponse, - path: string, + path: string ): Promise; isServeableUrl(path: string): boolean; isInternalUrl(req: http.IncomingMessage): boolean; @@ -134,12 +174,12 @@ declare namespace next { getCompilationError( page: string, req: http.IncomingMessage, - res: http.ServerResponse, + res: http.ServerResponse ): Promise; handleBuildHash( filename: string, hash: string, - res: http.ServerResponse, + res: http.ServerResponse ): void; send404(res: http.ServerResponse): void; } diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 181208518f..4eb24dc3ff 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -8,15 +8,11 @@ export interface EventChangeOptions { [key: string]: any; } -export type RouterCallback = () => void; -export interface SingletonRouter { - readyCallbacks: RouterCallback[]; - ready(cb: RouterCallback): void; +export type PopStateCallback = (state: any) => boolean | undefined; - // router properties - readonly components: { - [key: string]: { Component: React.ComponentType; err: any }; - }; +export type RouterCallback = () => void; +export interface RouterProps { + // url property fields readonly pathname: string; readonly route: string; readonly asPath?: string; @@ -30,32 +26,50 @@ export interface SingletonRouter { | string[]; }; - // router methods - reload(route: string): Promise; + // property fields + readonly components: { + [key: string]: { Component: React.ComponentType; err: any }; + }; + + // core method fields back(): void; + beforePopState(cb: PopStateCallback): boolean; + prefetch(url: string): Promise>; push( url: string | UrlLike, as?: string | UrlLike, options?: EventChangeOptions, ): Promise; + reload(route: string): Promise; replace( url: string | UrlLike, as?: string | UrlLike, options?: EventChangeOptions, ): Promise; - prefetch(url: string): Promise>; - // router events + // events onAppUpdated?(nextRoute: string): void; - onRouteChangeStart?(url: string): void; onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; onRouteChangeComplete?(url: string): void; onRouteChangeError?(error: any, url: string): void; + onRouteChangeStart?(url: string): void; +} + +export interface SingletonRouter extends RouterProps { + router: RouterProps | null; + readyCallbacks: RouterCallback[]; + ready(cb: RouterCallback): void; +} + +export interface WithRouterProps { + router: SingletonRouter; } export function withRouter( - Component: React.ComponentType, + Component: React.ComponentType, ): React.ComponentType; -export const Singleton: SingletonRouter; -export default Singleton; +declare const Router: SingletonRouter; +export default Router; diff --git a/types/next/test/next-app-tests.tsx b/types/next/test/next-app-tests.tsx new file mode 100644 index 0000000000..3e7c56f87c --- /dev/null +++ b/types/next/test/next-app-tests.tsx @@ -0,0 +1,27 @@ +import * as React from "react"; +import App, { Container } from "next/app"; + +interface NextComponentProps { + example: string; +} + +class TestApp extends App { + static async getInitialProps({ Component, router, ctx }: any) { + let pageProps = {}; + + if (Component.getInitialProps) { + pageProps = await Component.getInitialProps(ctx); + } + + return { pageProps }; + } + + render() { + const { Component, pageProps } = this.props; + return ( + + + + ); + } +} diff --git a/types/next/test/next-component-tests.tsx b/types/next/test/next-component-tests.tsx new file mode 100644 index 0000000000..55173fd25c --- /dev/null +++ b/types/next/test/next-component-tests.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import { NextStatelessComponent, NextContext } from "next"; + +interface NextComponentProps { + example: string; +} + +class ClassNext extends React.Component { + static async getInitialProps(ctx: NextContext) { + const { example } = ctx.query; + return { example }; + } + + render() { + return ( +

I'm a class component! {this.props.example}
+ ); + } +} + +const StatelessNext: NextStatelessComponent = ({ example }) => ( +
I'm a stateless component! {example}
+); + +StatelessNext.getInitialProps = async ({ query }: NextContext) => { + const { example } = query; + return { example: example as string }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 0177d1d451..2b3257cd25 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,40 @@ -import Document, * as document from "next/document"; +import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as React from "react"; const results = ( - + - - - + +
+ ); + +const Wrapper: React.SFC = ({ children }) => {children}; + +export default class MyDocument extends Document { + static async getInitialProps({ renderPage }: NextDocumentContext) { + // Without callback + const page = renderPage(); + // With callback + const differentPage = renderPage(App => props => ); + const style = {}; + return { ...page, style }; + } + + render() { + return ( + + + My page +