diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 86b77f8c6b..2d28d19f8c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1104,6 +1104,7 @@ /types/ffprobe-static/ @iamstevetran /types/fhir-js-client/ @rmchndrng /types/fibers/ @soywiz +/types/fibjs/ @richardo2016 /types/figures/ @BendingBender /types/file-exists/ @BendingBender /types/file-saver/ @cyrilschumacher @DaIgeb @chrismbarr @@ -3383,7 +3384,7 @@ /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @sirreal @iplus26 @KurtPreston +/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston /types/react-lazyload/ @m0a /types/react-leaflet/ @danzel @davschne @yuit /types/react-list/ @buptyyf @tomshen 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/ace/index.d.ts b/types/ace/index.d.ts index 828aab87c2..7faa5da4f8 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -832,8 +832,9 @@ declare namespace AceAjax { /** * [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft} + * @param scrollLeft The new scroll left value **/ - setScrollLeft(): void; + setScrollLeft(scrollLeft: number): void; /** * [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft} diff --git a/types/ace/test/edit_session.ts b/types/ace/test/edit_session.ts index 4713495f7a..29b3bb6bd8 100644 --- a/types/ace/test/edit_session.ts +++ b/types/ace/test/edit_session.ts @@ -18,6 +18,23 @@ function createFoldTestSession() { return session; } +function createScrollTestRenderer(): AceAjax.VirtualRenderer | null { + var el = document.createElement("div"); + + if (!el.getBoundingClientRect) { + console.log("Skipping test: This test only runs in the browser"); + return null; + } + + el.style.left = "20px"; + el.style.top = "30px"; + el.style.width = "300px"; + el.style.height = "100px"; + document.body.appendChild(el); + + return new AceAjax.VirtualRenderer(el); +} + function assertArray(a, b) { assert.equal(a + "", b + ""); assert.ok(a.length == b.length); @@ -915,5 +932,25 @@ const aceEditSessionTests = { session = new AceAjax.EditSession(new Array(30).join("\n")); session.documentToScreenPosition(2, 0); session.documentToScreenPosition(2, 0); + }, + + "test setScrollTop()": function() { + var renderer = createScrollTestRenderer(); + var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]); + renderer.setSession(session); + assert.equal(renderer.getScrollTop(), 0); + session.setScrollTop(40); + assert.equal(renderer.getScrollTop(), 40); + renderer.getScrollTop() + }, + + "test setScrollLeft()": function() { + var renderer = createScrollTestRenderer(); + var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]); + renderer.setSession(session); + assert.equal(renderer.getScrollLeft(), 0); + session.setScrollLeft(40); + assert.equal(renderer.getScrollLeft(), 40); + renderer.getScrollLeft() } -}; \ No newline at end of file +}; 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 051539e2ac..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: (...args: any[]) => T, 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 89e897a7ad..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. * 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-types/index.d.ts b/types/babel-types/index.d.ts index 47068c3481..c464c4bc3f 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -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/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/bencode/bencode-tests.ts b/types/bencode/bencode-tests.ts new file mode 100644 index 0000000000..f6ad3c8292 --- /dev/null +++ b/types/bencode/bencode-tests.ts @@ -0,0 +1,6 @@ +import * as bencode from "bencode"; + +bencode.byteLength("abcde"); // $ExpectType number +bencode.encodingLength("abcde"); // $ExpectType number +bencode.encode([1, 2, 3, 4], new Buffer([]), 1); // $ExpectType Buffer +bencode.decode(new Buffer("abcde"), 1, 3); // $ExpectType any diff --git a/types/bencode/index.d.ts b/types/bencode/index.d.ts new file mode 100644 index 0000000000..444513192c --- /dev/null +++ b/types/bencode/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for bencode 2.0 +// Project: https://github.com/themasch/node-bencode#readme +// Definitions by: Tobenna +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function byteLength(value: any): number; +export function encodingLength(value: any): number; +export function encode(data: any, buffer?: Buffer, offset?: number): Buffer; +export function decode( + data: Buffer, + start?: number, + end?: number, + encoding?: string +): any; diff --git a/types/bencode/tsconfig.json b/types/bencode/tsconfig.json new file mode 100644 index 0000000000..47220efa5a --- /dev/null +++ b/types/bencode/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", + "bencode-tests.ts" + ] +} diff --git a/types/bencode/tslint.json b/types/bencode/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bencode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bigi/bigi-tests.ts b/types/bigi/bigi-tests.ts index 0e4822aeb6..23bffb0477 100644 --- a/types/bigi/bigi-tests.ts +++ b/types/bigi/bigi-tests.ts @@ -14,3 +14,6 @@ const b6 = b4.multiply(b5); console.log(b6); // => BigInteger { '0': 420, '1': 0, t: 1, s: 0 } + +console.log(b1.compareTo(b2)); +// => 70 diff --git a/types/bigi/index.d.ts b/types/bigi/index.d.ts index 7b44ff75e4..de849587ac 100644 --- a/types/bigi/index.d.ts +++ b/types/bigi/index.d.ts @@ -23,7 +23,7 @@ declare class bigi { clamp(): void; clearBit(n: number): bigi; clone(): bigi; - compareTo(a: bigi): bigi; + compareTo(a: bigi): number; copyTo(r: any): void; dAddOffset(n: any, w: any): void; dMultiply(n: number): void; 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/chance/chance-tests.ts b/types/chance/chance-tests.ts index 00d8752118..238fd97cf3 100644 --- a/types/chance/chance-tests.ts +++ b/types/chance/chance-tests.ts @@ -71,3 +71,18 @@ euro = chance.euro({opt: 'abc'}); let coin = chance.coin(); coin = chance.coin(); + +// Make sure date works with min and max parameters +let date: string|Date = chance.date(); + +let min = new Date(); +let max = new Date(); +date = chance.date({min, max}); + +min = new Date(); +min.setFullYear(new Date().getFullYear() - 15); +max = new Date(); +max.setFullYear(new Date().getFullYear() + 15); +date = chance.date({min, max}); +date = chance.date({min}); +date = chance.date({max}); diff --git a/types/chance/index.d.ts b/types/chance/index.d.ts index 07418e45be..17708acc5a 100644 --- a/types/chance/index.d.ts +++ b/types/chance/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chance 1.0.13 +// Type definitions for Chance 1.0.16 // Project: http://chancejs.com // Definitions by: Chris Bowdon // Brice BERNARD @@ -189,6 +189,8 @@ declare namespace Chance { year?: number; month?: number; day?: number; + min?: Date; + max?: Date; } interface Month { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index cb3db72855..de72e30427 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -12,6 +12,7 @@ // Simon Archer // Ken Elkabany // Slavik Nychkalo +// Francesco Benedetto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -483,7 +484,7 @@ declare namespace Chart { pointHoverBackgroundColor?: ChartColor | ChartColor[]; pointHoverBorderColor?: ChartColor | ChartColor[]; pointHoverBorderWidth?: number | number[]; - pointStyle?: PointStyle | HTMLImageElement | Array; + pointStyle?: PointStyle | HTMLImageElement | HTMLCanvasElement | Array; xAxisID?: string; yAxisID?: string; type?: string; @@ -506,6 +507,7 @@ declare namespace Chart { } interface CommonAxe { + bounds?: string; type?: ScaleType | string; display?: boolean; id?: string; @@ -516,6 +518,7 @@ declare namespace Chart { barThickness?: number; maxBarThickness?: number; scaleLabel?: ScaleTitleOptions; + time?: TimeScale; offset?: boolean; beforeUpdate?(scale?: any): void; beforeSetDimension?(scale?: any): void; @@ -537,7 +540,6 @@ declare namespace Chart { categoryPercentage?: number; barPercentage?: number; distribution?: 'linear' | 'series'; - time?: TimeScale; } // tslint:disable-next-line no-empty-interface diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 957c409a4f..a1713aa6f9 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,25 +1,30 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle +// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/// +/// -/////////////// -// WebView ref: https://chromium.googlesource.com/chromium/src/+/68.0.3432.1/chrome/common/extensions/api/webview_tag.json -/////////////// +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// WebView ref // +// https://chromium.googlesource.com/chromium/src/+/68.0.3432.1/chrome/common/extensions/api/webview_tag.json // +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// -// Accessibility Features -//////////////////// -/** - * Use the chrome.accessibilityFeatures API to manage Chrome's accessibility features. This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. In order to get feature states the extension must request accessibilityFeatures.read permission. For modifying feature state, the extension needs accessibilityFeatures.modify permission. Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. - * @since Availability: Since Chrome 37. - * Permissions: "accessibilityFeatures.read" (For read access); "accessibilityFeatures.modify" (For modifications; Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission.) - * Important: This API works only on Chrome OS. - */ declare namespace chrome { + //////////////////// + // Accessibility Features + //////////////////// + /** + * Use the chrome.accessibilityFeatures API to manage Chrome's accessibility features. + * This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. + * In order to get feature states the extension must request accessibilityFeatures.read permission. + * For modifying feature state, the extension needs accessibilityFeatures.modify permission. + * Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. + * Permissions: 'accessibilityFeatures.read' (For read access); 'accessibilityFeatures.modify' (For modifications; Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission.) + * Important: This API works only on Chrome OS. + * @since Availability: Since Chrome 37. + */ namespace accessibilityFeatures { interface AccessibilityFeaturesGetArg { /** Optional. Whether to return the value that applies to the incognito session (default false). */ @@ -36,7 +41,7 @@ declare namespace chrome { * • controllable_by_this_extension: can be controlled by this extension * • controlled_by_this_extension: controlled by this extension */ - levelOfControl: string; + levelOfControl: 'not_controllable' | 'controlled_by_other_extensions' | 'controllable_by_this_extension' | 'controlled_by_this_extension'; /** Optional. Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ incognitoSpecific?: boolean; } @@ -55,7 +60,7 @@ declare namespace chrome { * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: string; + scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; } interface AccessibilityFeaturesClearArg { @@ -67,7 +72,7 @@ declare namespace chrome { * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: string; + scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; } interface AccessibilityFeaturesSetting { @@ -96,13 +101,63 @@ declare namespace chrome { clear(details: AccessibilityFeaturesClearArg, callback?: () => void): void; } + /** + * Spoken feedback (text-to-speech). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var spokenFeedback: AccessibilityFeaturesSetting; + /** + * Enlarged cursor. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var largeCursor: AccessibilityFeaturesSetting; + /** + * Sticky modifier keys (like shift or alt). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var stickyKeys: AccessibilityFeaturesSetting; + /** + * High contrast rendering mode. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var highContrast: AccessibilityFeaturesSetting; + /** + * Full screen magnification. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var screenMagnifier: AccessibilityFeaturesSetting; + /** + * Auto mouse click after mouse stops moving. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var autoclick: AccessibilityFeaturesSetting; + /** + * Virtual on-screen keyboard. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + */ export var virtualKeyboard: AccessibilityFeaturesSetting; + /** + * Caret highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 51. + */ + export var caretHighlight: AccessibilityFeaturesSetting; + /** + * Cursor highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 51. + */ + export var cursorHighlight: AccessibilityFeaturesSetting; + /** + * Focus highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 51. + */ + export var focusHighlight: AccessibilityFeaturesSetting; + /** + * Select-to-speak. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 51. + */ + export var selectToSpeak: AccessibilityFeaturesSetting; + /** + * Switch access. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 51. + */ + export var switchAccess: AccessibilityFeaturesSetting; + /** + * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 42. + */ export var animationPolicy: AccessibilityFeaturesSetting; } @@ -111,8 +166,8 @@ declare namespace chrome { //////////////////// /** * Use the chrome.alarms API to schedule code to run periodically or at a specified time in the future. - * Availability: Since Chrome 22. - * Permissions: "alarms" + * Permissions: 'alarms' + * @since Availability: Since Chrome 22. */ namespace alarms { interface AlarmCreateInfo { @@ -137,14 +192,19 @@ declare namespace chrome { /** * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. + * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. + * That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. + * `when` can be set to less than 1 minute after 'now' without warning but won't actually cause the alarm to fire for at least 1 minute. * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. */ export function create(alarmInfo: AlarmCreateInfo): void; /** - * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. + * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. + * If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. + * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. + * That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. + * `when` can be set to less than 1 minute after 'now' without warning but won't actually cause the alarm to fire for at least 1 minute. * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. * @param name Optional name to identify this alarm. Defaults to the empty string. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. @@ -153,39 +213,39 @@ declare namespace chrome { /** * Gets an array of all the alarms. * @param callback The callback parameter should be a function that looks like this: - * function(array of Alarm alarms) {...}; + * @example function(array of Alarm alarms) {...}; */ export function getAll(callback: (alarms: Alarm[]) => void): void; /** * Clears all alarms. * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export function clearAll(callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm with the given name. * @param name The name of the alarm to clear. Defaults to the empty string. * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export function clear(name?: string, callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm without a name. * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export function clear(callback: (wasCleared: boolean) => void): void; /** * Retrieves details about the specified alarm. * @param callback The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; + * @example function( Alarm alarm) {...}; */ export function get(callback: (alarm: Alarm) => void): void; /** * Retrieves details about the specified alarm. * @param name The name of the alarm to get. Defaults to the empty string. * @param callback The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; + * @example function( Alarm alarm) {...}; */ export function get(name: string, callback: (alarm: Alarm) => void): void; @@ -193,54 +253,125 @@ declare namespace chrome { export var onAlarm: AlarmEvent; } - - //////////////////// - // App - //////////////////// - namespace app { - interface AppDetails extends chrome.runtime.Manifest { - id: string; - } - - export function getDetails(): AppDetails; - } - //////////////////// // App Runtime //////////////////// + + /** + * Use the chrome.app.runtime API to manage the app lifecycle. + * The app runtime manages app installation, controls the event page, and can shut down the app at anytime. + * @since Availability: Since Chrome 24. + */ namespace app.runtime { type LaunchSource = 'untracked' | 'app_launcher' | 'new_tab_page' | 'reload' | 'restart' | 'load_and_launch' | 'command_line' | 'file_handler' | 'url_handler' | 'system_tray' | 'about_page' | 'keyboard' | 'extensions_page' | 'management_api' | 'ephemeral_app' | 'background' | 'kiosk' | 'chrome_internal' | 'test' | 'installed_notification' | 'context_menu'; + interface EmbedRequest { + /** + * Optional developer specified data that the app to be embedded can use when making an embedding decision. + */ + data?: any; + /** + * Allows embedderId to embed this app in an element. The url specifies the content to embed. + */ + allow: (url: string) => void; + /** + * Prevents embedderId from embedding this app in an element. + */ + deny: () => void; + } + + type actionType = 'new_note'; + interface LaunchData { + /** + * The ID of the file or URL handler that the app is being invoked with. + * Handler IDs are the top-level keys in the file_handlers and/or url_handlers dictionaries in the manifest. + */ id?: string; + /** + * The file entries for the onLaunched event triggered by a matching file handler in the file_handlers manifest key. + */ items?: LaunchDataItem[]; + /** + * The URL for the onLaunched event triggered by a matching URL handler in the url_handlers manifest key. + */ url?: string; + /** + * The referrer URL for the onLaunched event triggered by a matching URL handler in the url_handlers manifest key. + */ referrerUrl?: string; + /** + * Whether the app is being launched in a Chrome OS kiosk session. + */ isKioskSession?: boolean; + /** + * Whether the app is being launched in a Chrome OS public session. + * @since Since Chrome 47. + */ isPublicSession?: boolean; + /** + * Where the app is launched from. + */ source?: LaunchSource; - actionData?: {}; + /** + * Contains data that specifies the ActionType this app was launched with. This is null if the app was not launched with a specific action intent. + * ______________________________________________________________________________ + * | enum of 'new_note' | actionType | new_note | + * | | | The user wants to quickly take a new note. | + * |____________________|____________|____________________________________________| + * @since Since Chrome 54. + */ + actionData?: actionType; } interface LaunchDataItem { + /** + * Entry for the item + */ entry: FileEntry; - type: string; + /** + * The MIME type of the file. + */ + type?: string; } + interface EmbedRequestedEvent extends chrome.events.Event<(request: EmbedRequest) => void> { } + interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> { } interface RestartedEvent extends chrome.events.Event<() => void> { } + /** + * Fired when an embedding app requests to embed this app. This event is only available on dev channel with the flag --enable-app-view. + * @since Since Chrome 38. + */ + export var onEmbedRequest: EmbedRequestedEvent; + /** + * Fired when an app is launched from the launcher. + */ export var onLaunched: LaunchedEvent; + /** + * Fired at Chrome startup to apps that were running when Chrome last shut down, + * or when apps have been requested to restart from their previous state for other reasons + * (e.g. when the user revokes access to an app's retained files the runtime will restart the app). + * In these situations if apps do not have an onRestarted handler they will be sent an onLaunched event instead. + */ export var onRestarted: RestartedEvent; } //////////////////// // App Window //////////////////// + /** + * Use the chrome.app.window API to create windows. + * Windows have an optional frame with title bar and size controls. + * They are not associated with any Chrome browser windows. + * See the Window State Sample for a demonstration of these options. + * @since Availability: Since Chrome 24. + */ namespace app.window { interface ContentBounds { left?: number; @@ -250,114 +381,327 @@ declare namespace chrome { } interface BoundsSpecification { + /** The X coordinate of the content or window. */ left?: number; + /** The Y coordinate of the content or window. */ top?: number; + /** The width of the content or window. */ width?: number; + /** The height of the content or window. */ height?: number; + /** The minimum width of the content or window. */ minWidth?: number; + /** The minimum height of the content or window. */ minHeight?: number; + /** The maximum width of the content or window. */ maxWidth?: number; + /** The maximum height of the content or window. */ maxHeight?: number; } interface Bounds { + /** This property can be used to read or write the current X coordinate of the content or window. */ left: number; + /** This property can be used to read or write the current Y coordinate of the content or window. */ top: number; + /** This property can be used to read or write the current width of the content or window. */ width: number; + /** This property can be used to read or write the current height of the content or window. */ height: number; - minWidth?: number; - minHeight?: number; - maxWidth?: number; - maxHeight?: number; + /** This property can be used to read or write the current minimum width of the content or window. A value of null indicates 'unspecified'. */ + minWidth?: number | null; + /** This property can be used to read or write the current minimum height of the content or window. A value of null indicates 'unspecified'. */ + minHeight?: number | null; + /** This property can be used to read or write the current maximum width of the content or window. A value of null indicates 'unspecified'. */ + maxWidth?: number | null; + /** This property can be used to read or write the current maximum height of the content or window. A value of null indicates 'unspecified'. */ + maxHeight?: number | null; + /** Set the left and top position of the content or window. */ setPosition(left: number, top: number): void; + /** Set the width and height of the content or window. */ setSize(width: number, height: number): void; - setMinimumSize(minWidth: number, minHeight: number): void; - setMaximumSize(maxWidth: number, maxHeight: number): void; + /** Set the minimum size constraints of the content or window. + * The minimum width or height can be set to null to remove the constraint. + * A value of undefined will leave a constraint unchanged. + **/ + setMinimumSize(minWidth: number | null | undefined, minHeight: number | null | undefined): void; + /** + * Set the maximum size constraints of the content or window. + * The maximum width or height can be set to null to remove the constraint. + * A value of undefined will leave a constraint unchanged. + */ + setMaximumSize(maxWidth: number | null | undefined, maxHeight: number | null | undefined): void; } interface FrameOptions { - type?: string; + /** + * Frame type: none or chrome (defaults to chrome). + * + * For none, the -webkit-app-region CSS property can be used to apply draggability to the app's window. + * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. + */ + type: 'none'; + } + interface FrameOptionsChrome { + /** + * Frame type: none or chrome (defaults to chrome). + * + * For none, the -webkit-app-region CSS property can be used to apply draggability to the app's window. + * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. + */ + type?: 'chrome'; + /** + * Allows the frame color to be set. Frame coloring is only available if the frame type is chrome. + * @since Frame coloring is new in Chrome 36. + */ color?: string; + /** + * Allows the frame color of the window when active to be set. Frame coloring is only available if the frame type is chrome. + * Frame coloring is only available if the frame type is chrome. + * @since Frame coloring is new in Chrome 36. + */ activeColor?: string; + /** + * Allows the frame color of the window when inactive to be set differently to the active color. Frame coloring is only available if the frame type is chrome. + * inactiveColor must be used in conjunction with color. + * @since Frame coloring is new in Chrome 36. + */ inactiveColor?: string; } interface CreateWindowOptions { + /** + * Id to identify the window. + * + * This will be used to remember the size and position of the window and restore that geometry when a window with the same id is later opened. + * If a window with a given id is created while another window with the same id already exists, + * the currently opened window will be focused instead of creating a new window. + */ id?: string; + /** + * Used to specify the initial position, initial size and constraints of the window's content (excluding window decorations). + * If an id is also specified and a window with a matching id has been shown before, the remembered bounds will be used instead. + * Note that the padding between the inner and outer bounds is determined by the OS. + * Therefore setting the same bounds property for both the innerBounds and outerBounds will result in an error. + * @since This property is new in Chrome 36. + */ innerBounds?: BoundsSpecification; + /** + * Used to specify the initial position, initial size and constraints of the window (including window decorations such as the title bar and frame). + * If an id is also specified and a window with a matching id has been shown before, the remembered bounds will be used instead. + * Note that the padding between the inner and outer bounds is determined by the OS. + * Therefore setting the same bounds property for both the innerBounds and outerBounds will result in an error. + * @since This property is new in Chrome 36. + */ outerBounds?: BoundsSpecification; + /** + * Minimum width of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ minWidth?: number; + /** + * Minimum height of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ minHeight?: number; + /** + * Maximum width of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ maxWidth?: number; + /** + * Maximum height of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ maxHeight?: number; + /** Type of window to create */ + type?: 'shell'; /** - * @description - * @type {(string | FrameOptions)} string ("none", "chrome") or FrameOptions - * @memberof CreateWindowOptions + * If true, the window will have its own shelf icon. + * Otherwise the window will be grouped in the shelf with other windows that are associated with the app. + * Defaults to false. + * If showInShelf is set to true you need to specify an id for the window. + * @since Since Chrome 54. + */ + showInShelf?: boolean; + /** + * URL of the window icon. A window can have its own icon when showInShelf is set to true. The URL should be a global or an extension local URL. + * @since Since Chrome 54. + */ + icon?: string; + /** + * Frame type: none or chrome (defaults to chrome). + * For none, the -webkit-app-region CSS property can be used to apply draggability to the app's window. + * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. + * @since Use of FrameOptions is new in M36. + */ + frame?: 'none' | 'chrome' | FrameOptions | FrameOptionsChrome; + /** + * Size and position of the content in the window (excluding the titlebar). + * If an id is also specified and a window with a matching id has been shown before, + * the remembered bounds of the window will be used instead. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - frame?: string | FrameOptions; bounds?: ContentBounds; - alphaEnabled?: boolean; /** - * @description - * @type {string} "normal", "fullscreen", "maximized", "minimized" - * @memberof CreateWindowOptions + * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. + */ + state?: 'normal' | 'fullscreen' | 'maximized' | 'minimized'; + /** + * If true, the window will be created in a hidden state. Call show() on the window to show it once it has been created. Defaults to false. */ - state?: string; hidden?: boolean; + /** + * If true, the window will be resizable by the user. Defaults to true. + */ resizable?: boolean; + /** + * @deprecated Deprecated since Chrome 34. Multiple windows with the same id is no longer supported. + * By default if you specify an id for the window, + * the window will only be created if another window with the same id doesn't already exist. + * If a window with the same id already exists that window is activated instead. + * If you do want to create multiple windows with the same id, you can set this property to false. + */ singleton?: boolean; + /** + * If true, the window will stay above most other windows. + * If there are multiple windows of this kind, the currently focused window will be in the foreground. + * @requires alwaysOnTopWindows-permission. + * Defaults to false. + * Call setAlwaysOnTop() on the window to change this property after creation. + */ alwaysOnTop?: boolean; + /** If true, the window will be focused when created. Defaults to true. */ focused?: boolean; + /** + * If true, and supported by the platform, the window will be visible on all workspaces. + * @since Since Chrome 39. + */ visibleOnAllWorkspaces?: boolean; } interface AppWindow { + /** Focus the window. */ focus: () => void; + /** + * Fullscreens the window. + * The user will be able to restore the window by pressing ESC. + * An application can prevent the fullscreen state to be left when ESC is pressed by requesting the + * app.window.fullscreen.overrideEsc permission and canceling the event by calling .preventDefault(), + * in the keydown and keyup handlers, like this: + * @example window.onkeydown = window.onkeyup = function(e) { if (e.keyCode == 27 <<--``ESC``) { e.preventDefault(); } + * Note window.fullscreen() will cause the entire window to become fullscreen and does not require a user gesture. + * The HTML5 fullscreen API can also be used to enter fullscreen mode(see Web APIs for more details). + **/ fullscreen: () => void; + /** Is the window fullscreen? This will be true if the window has been created fullscreen or was made fullscreen via the AppWindow or HTML5 fullscreen APIs. */ isFullscreen: () => boolean; + /** Minimize the window. */ minimize: () => void; + /** Is the window minimized? */ isMinimized: () => boolean; + /** Maximize the window. */ maximize: () => void; + /** Is the window maximized? */ isMaximized: () => boolean; + /** Restore the window, exiting a maximized, minimized, or fullscreen state. */ restore: () => void; + /** + * Move the window to the position (|left|, |top|). + * @deprecated Deprecated since Chrome 43. Use outerBounds. + */ moveTo: (left: number, top: number) => void; + /** + * Resize the window to |width|x|height| pixels in size. + * @deprecated Deprecated since Chrome 43. Use outerBounds. + */ resizeTo: (width: number, height: number) => void; + /** Draw attention to the window. */ drawAttention: () => void; + /** Clear attention to the window. */ clearAttention: () => void; + /** Close the window. */ close: () => void; - show: () => void; + /** Show the window. Does nothing if the window is already visible. Focus the window if |focused| is set to true or omitted. */ + show: (focused?: boolean) => void; + /** Hide the window. Does nothing if the window is already hidden. */ hide: () => void; + /** + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + * @description Get the window's inner bounds as a ContentBounds object. + */ getBounds: () => ContentBounds; + /** + * Set the window's inner bounds. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ setBounds: (bounds: ContentBounds) => void; + /** Is the window always on top? */ isAlwaysOnTop: () => boolean; + /** Set whether the window should stay above most other windows. Requires the alwaysOnTopWindows permission. */ setAlwaysOnTop: (alwaysOnTop: boolean) => void; + /** Set whether the window is visible on all workspaces. (Only for platforms that support this). */ setVisibleOnAllWorkspaces: (alwaysVisible: boolean) => void; + /** The JavaScript 'window' object for the created child. */ contentWindow: Window; + /** The id the window was created with. */ id: string; + /** + * The position, size and constraints of the window's content, which does not include window decorations. + * @since This property is new in Chrome 36. + * */ innerBounds: Bounds; + /** + * The position, size and constraints of the window, which includes window decorations, such as the title bar and frame. + * @since This property is new in Chrome 36. + */ outerBounds: Bounds; + + + /** Fired when the window is resized. */ onBoundsChanged: WindowEvent; + /** + * Fired when the window is closed. + * Note, this should be listened to from a window other than the window being closed, for example from the background page. + * This is because the window being closed will be in the process of being torn down when the event is fired, + * which means not all APIs in the window's script context will be functional. + */ onClosed: WindowEvent; + /** Fired when the window is fullscreened (either via the AppWindow or HTML5 APIs). */ onFullscreened: WindowEvent; + /** Fired when the window is maximized. */ onMaximized: WindowEvent; + /** Fired when the window is minimized. */ onMinimized: WindowEvent; + /** Fired when the window is restored from being minimized or maximized. */ onRestored: WindowEvent; } - - export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; - export function current(): AppWindow; - export function get(id: string): AppWindow; - export function getAll(): AppWindow[]; - export function canSetVisibleOnAllWorkspaces(): boolean; - interface WindowEvent extends chrome.events.Event<() => void> { } - - export var onBoundsChanged: WindowEvent; - export var onClosed: WindowEvent; - export var onFullscreened: WindowEvent; - export var onMaximized: WindowEvent; - export var onMinimized: WindowEvent; - export var onRestored: WindowEvent; + /** + * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. + * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). + * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. + * + * @param url + * @param [options] + * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; + */ + export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; + /** + * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). + */ + export function current(): AppWindow; + /** + * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. + */ + export function get(id: string): AppWindow; + /** + * Gets an array of all currently created app windows. This method is new in Chrome 33. + */ + export function getAll(): AppWindow[]; + /** + * Whether the current platform supports windows being visible on all workspaces. + */ + export function canSetVisibleOnAllWorkspaces(): boolean; } @@ -365,8 +709,9 @@ declare namespace chrome { // Audio //////////////////// /** - * The chrome.audio API is provided to allow users to get information about and control the audio devices attached to the system. This API is currently only implemented for ChromeOS. - * @since Chrome 59 + * The chrome.audio API is provided to allow users to get information about and control the audio devices attached to the system. + * This API is currently only implemented for ChromeOS. + * @since Since Chrome 59. */ namespace audio { export type StreamType = 'INPUT' | 'OUTPUT'; @@ -376,8 +721,8 @@ declare namespace chrome { /** Stream type associated with this device. */ streamType: StreamType; /** Type of the device. */ - deviceType: "HEADPHONE" | "MIC" | "USB" | "BLUETOOTH" | "HDMI" | "INTERNAL_SPEAKER" | "INTERNAL_MIC" | "FRONT_MIC" | "REAR_MIC" | "KEYBOARD_MIC" | "HOTWORD" | "LINEOUT" | "POST_MIX_LOOPBACK" | "POST_DSP_LOOPBACK" | "OTHER"; - /** The user-friendly name (e.g. "USB Microphone"). */ + deviceType: 'HEADPHONE' | 'MIC' | 'USB' | 'BLUETOOTH' | 'HDMI' | 'INTERNAL_SPEAKER' | 'INTERNAL_MIC' | 'FRONT_MIC' | 'REAR_MIC' | 'KEYBOARD_MIC' | 'HOTWORD' | 'LINEOUT' | 'POST_MIX_LOOPBACK' | 'POST_DSP_LOOPBACK' | 'OTHER'; + /** The user-friendly name (e.g. 'USB Microphone'). */ displayName: string; /** Device name. */ deviceName: string; @@ -443,15 +788,15 @@ declare namespace chrome { addListener(callback: (devices: AudioDeviceInfo[]) => void): void; } /** - * @description Device properties by which to filter the list of returned audio devices. If the filter is not set or set to {}, returned device list will contain all available audio devices. + * Device properties by which to filter the list of returned audio devices. If the filter is not set or set to {}, returned device list will contain all available audio devices. */ interface Filter { /** - * @description If set, only audio devices whose stream type is included in this list will satisfy the filter. + * If set, only audio devices whose stream type is included in this list will satisfy the filter. */ streamTypes?: StreamType[]; /** - * @description If set, only audio devices whose active state matches this value will satisfy the filter. + * If set, only audio devices whose active state matches this value will satisfy the filter. */ isActive?: boolean; } @@ -490,42 +835,68 @@ declare namespace chrome { //////////////////// /** * Use the chrome.bluetooth API to connect to a Bluetooth device. All functions report failures via chrome.runtime.lastError. - * Manifest: "bluetooth": {...} + * Manifest: 'bluetooth': {...} * @since Chrome 37 */ namespace bluetooth { interface AdapterState { + /** The address of the adapter, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; + /** The human-readable name of the adapter. */ name: string; + /** Indicates whether or not the adapter has power. */ powered: boolean; + /** Indicates whether or not the adapter is available (i.e. enabled). */ available: boolean; + /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } interface Device { + /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; + /** The human-readable name of the device. */ name?: string; + /** The class of the device, a bit-field defined by http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband. */ deviceClass?: number; + /** The Device ID record of the device, where available. */ vendorIdSource?: 'bluetooth' | 'usb'; vendorId?: number; productId?: number; deviceId?: number; - type?: "computer" | "phone" | "modem" | "audio" | "carAudio" | "video" | "peripheral" | "joystick" | "gamepad" | "keyboard" | "mouse" | "tablet" | "keyboardMouseCombo"; + /** + * The type of the device, if recognized by Chrome. + * This is obtained from the |deviceClass| field and only represents a small fraction of the possible device types. + * When in doubt you should use the |deviceClass| field directly. + */ + type?: 'computer' | 'phone' | 'modem' | 'audio' | 'carAudio' | 'video' | 'peripheral' | 'joystick' | 'gamepad' | 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + /** Indicates whether or not the device is paired with the system. */ paired?: boolean; + /** Indicates whether the device is currently connected to the system. */ connected?: boolean; /** + * Indicates whether the device is currently connecting to the system. * @since Chrome 48 */ connecting?: boolean; /** + * Indicates whether the device is connectable. * @since Chrome 48 */ connectable?: boolean; + /** + * UUIDs of protocols, profiles and services advertised by the device. + * For classic Bluetooth devices, this list is obtained from EIR data and SDP tables. + * For Low Energy devices, this list is obtained from AD and GATT primary services. + * For dual mode devices this may be obtained from both. + */ uuids?: string[]; /** + * The received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. * @since Chrome 44 */ inquiryRssi: number; /** + * The transmitted power level. This field is avaliable only for LE devices that include this field in AD. It is avaliable and valid only during discovery. * @since Chrome 44 */ inquiryTxPower: number; @@ -572,25 +943,438 @@ declare namespace chrome { } /** * The chrome.bluetoothLowEnergy API is used to communicate with Bluetooth Smart (Low Energy) devices using the Generic Attribute Profile (GATT). - * Manifest: "bluetooth": {...} + * Manifest: 'bluetooth': {...} * @since Chrome 37 * Important: This API works only on Chrome OS. * Note: With Chrome 56, users can select nearby Bluetooth Low Energy devices to provide to web sites that use the Web Bluetooth API. */ namespace bluetoothLowEnergy { + interface Service { + /** The UUID of the service, e.g. 0000180d-0000-1000-8000-00805f9b34fb. */ + uuid: string; + /** Indicates whether the type of this service is primary or secondary. */ + isPrimary: boolean; + /** + * Returns the identifier assigned to this service. + * Use the instance ID to distinguish between services from a peripheral with the same UUID and to make function calls that take in a service identifier. + * Present, if this instance represents a remote service. + **/ + instanceId?: string; + /** + * The device address of the remote peripheral that the GATT service belongs to. + * Present, if this instance represents a remote service. + */ + deviceAddress?: string; + } + enum CharacteristicProperties { + 'broadcast', + 'read', + 'writeWithoutResponse', + 'write', + 'notify', + 'indicate', + 'authenticatedSignedWrites', + 'extendedProperties', + 'reliableWrite', + 'writableAuxiliaries', + 'encryptRead', + 'encryptWrite', + 'encryptAuthenticatedRead', + 'encryptAuthenticatedWrite' + } + interface Characteristic { + /** The UUID of the characteristic, e.g. 00002a37-0000-1000-8000-00805f9b34fb. */ + uuid: string; + /** The GATT service this characteristic belongs to. */ + service?: Service; + /** The properties of this characteristic. */ + properties: CharacteristicProperties[]; + /** Returns the identifier assigned to this characteristic. Use the instance ID to distinguish between characteristics from a peripheral with the same UUID and to make function calls that take in a characteristic identifier. Present, if this instance represents a remote characteristic. */ + instanceId?: string; + /** The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication. */ + value?: ArrayBuffer; + } + enum DescriptorPermissions { + 'read', + 'write', + 'encryptedRead', + 'encryptedWrite', + 'encryptedAuthenticatedRead', + 'encryptedAuthenticatedWrite' + } + interface Descriptor { + /** The UUID of the characteristic descriptor, e.g. 00002902-0000-1000-8000-00805f9b34fb. */ + uuid: string; + /** The GATT characteristic this descriptor belongs to. */ + characteristic?: Characteristic; + /** + * The permissions of this descriptor. + * @since Since Chrome 52. + */ + permissions: DescriptorPermissions[]; + /** Returns the identifier assigned to this descriptor. Use the instance ID to distinguish between descriptors from a peripheral with the same UUID and to make function calls that take in a descriptor identifier. Present, if this instance represents a remote characteristic. */ + instanceId?: string; + /** The currently cached descriptor value. This value gets updated when the value of the descriptor is read. */ + value?: ArrayBuffer; + } + interface RequestDevice { + /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ + address: string; + /** The human-readable name of the device. */ + name?: string; + /** The class of the device, a bit - field defined by: + * @see [Specs]{@link http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband} + **/ + deviceClass?: number; + } + interface Request { + /** Unique ID for this request. Use this ID when responding to this request. */ + requestId: number; + /** Device that send this request. */ + device: RequestDevice; + /** Value to write (if this is a write request). */ + value?: ArrayBuffer; + } + interface IProperties { + /** + * Flag indicating whether a connection to the device is left open when the event page of the application is unloaded. The default value is false. + * @see [HowToManageAppLifecycle]{@link https://developer.chrome.com/apps/app_lifecycle} + * @default false + */ + persistent: boolean; + } + interface INotification { + /** New value of the characteristic. */ + value: ArrayBuffer; + /** Optional flag for sending an indication instead of a notification. */ + shouldIndicate: boolean; + } + enum AdvertisementType { + 'broadcast', 'peripheral' + } + interface Advertisement { + /** Type of advertisement. */ + type: AdvertisementType; + /** List of UUIDs to include in the 'Service UUIDs' field of the Advertising Data. These UUIDs can be of the 16bit, 32bit or 128 formats. */ + serviceUuids?: string[]; + /** List of manufacturer specific data to be included in 'Manufacturer Specific Data' fields of the advertising data. */ + manufacturerData?: { id: number, data: number[] }; + /** List of UUIDs to include in the 'Solicit UUIDs' field of the Advertising Data. These UUIDs can be of the 16bit, 32bit or 128 formats. */ + solicitUuids?: string[]; + /** List of service data to be included in 'Service Data' fields of the advertising data. */ + serviceData: { uuid: string, data: number[] }; + } + interface IResponse { + /** Id of the request this is a response to. */ + requestId: number; + /** If this is an error response, this should be true. */ + isError: boolean; + /** Response value. Write requests and error responses will ignore this parameter. */ + value?: ArrayBuffer; + } /** - * NOT IMPLEMENTED YET - * @see https://developer.chrome.com/apps/bluetoothLowEnergy - * */ + * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect. + * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened. + * @param callback Called when the connect request has completed. + */ + function connect(deviceAddress: string, callback: () => void): void; + /** + * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect. + * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened. + * @param properties Connection properties (optional). + * @param callback Called when the connect request has completed. + */ + function connect(deviceAddress: string, properties: IProperties, callback: () => void): void; + /** + * Closes the app's connection to the device with the given address. Note that this will not always destroy the physical link itself, since there may be other apps with open connections. + * @param deviceAddress The Bluetooth address of the remote device. + * @param [callback] Called when the disconnect request has completed. + */ + function disconnect(deviceAddress: string, callback?: () => void): void; + /** + * Get the GATT service with the given instance ID. + * @param serviceId The instance ID of the requested GATT service. + * @param callback Called with the requested Service object. + */ + function getService(serviceId: string, callback: (result: Service) => void): void; + /** + * @description Create a locally hosted GATT service. This service can be registered to be available on a local GATT server. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param service The service to create. + * @param callback Called with the created services's unique ID. + */ + function createService(service: Service, callback: () => void): void; + /** + * Get all the GATT services that were discovered on the remote device with the given device address. + * Note: If service discovery is not yet complete on the device, this API will return a subset (possibly empty) of services. A work around is to add a time based delay and/or call repeatedly until the expected number of services is returned. + * @param deviceAddress The Bluetooth address of the remote device whose GATT services should be returned. + * @param callback Called with the list of requested Service objects. + */ + function getServices(deviceAddress: string, callback: (result: Service[]) => void): void; + /** + * Get the GATT characteristic with the given instance ID that belongs to the given GATT service, if the characteristic exists. + * @param characteristicId The instance ID of the requested GATT characteristic. + * @param callback Called with the requested Characteristic object. + */ + function getCharacteristic(characteristicId: string, callback: (result: Characteristic) => void): void; + /** + * @description Create a locally hosted GATT characteristic. This characteristic must be hosted under a valid service. If the service ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param characteristic The characteristic to create. + * @param serviceId ID of the service to create this characteristic for. + * @param callback Called with the created characteristic's unique ID. + */ + function createCharacteristic(characteristic: Characteristic, serviceId: string, callback: (characteristicId: string) => void): void; + /** + * Get a list of all discovered GATT characteristics that belong to the given service. + * @param serviceId The instance ID of the GATT service whose characteristics should be returned. + * @param callback Called with the list of characteristics that belong to the given service. + */ + function getCharacteristics(serviceId: string, callback: (result: Characteristic[]) => void): void; + /** + * Get a list of GATT services that are included by the given service. + * @param serviceId The instance ID of the GATT service whose included services should be returned. + * @param callback Called with the list of GATT services included from the given service. + */ + function getIncludedServices(serviceId: string, callback: (result: Service[]) => void): void; + /** + * Get the GATT characteristic descriptor with the given instance ID. + * @param descriptorId The instance ID of the requested GATT characteristic descriptor. + * @param callback Called with the requested Descriptor object. + */ + function getDescriptor(descriptorId: string, callback: (result: Descriptor) => void): void; + /** + * Create a locally hosted GATT descriptor. This descriptor must be hosted under a valid characteristic. If the characteristic ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param descriptor The descriptor to create. + * @param characteristicId ID of the characteristic to create this descriptor for. + * @param callback Called with the created desciptor's unique ID. + */ + function createDescriptor(descriptor: Descriptor, characteristicId: string, callback: (descriptorId: string) => void): void; + /** + * Get a list of GATT characteristic descriptors that belong to the given characteristic. + * @param characteristicId The instance ID of the GATT characteristic whose descriptors should be returned. + * @param callback Called with the list of descriptors that belong to the given characteristic. + */ + function getDescriptors(characteristicId: string, callback: (result: Descriptor[]) => void): void; + /** + * Retrieve the value of a specified characteristic from a remote peripheral. + * @param characteristicId The instance ID of the GATT characteristic whose value should be read from the remote device. + * @param callback Called with the Characteristic object whose value was requested. The value field of the returned Characteristic object contains the result of the read request. + */ + function readCharacteristicValue(characteristicId: string, callback: (result: Characteristic) => void): void; + /** + * Write the value of a specified characteristic from a remote peripheral. + * @param characteristicId The instance ID of the GATT characteristic whose value should be written to. + * @param value The value that should be sent to the remote characteristic as part of the write request. + * @param callback Called when the write request has completed. + */ + function writeCharacteristicValue(characteristicId: string, value: ArrayBuffer, callback: () => void): void; + /** + * Enable value notifications/indications from the specified characteristic. Once enabled, an application can listen to notifications using the onCharacteristicValueChanged event. + * @see onCharacteristicValueChanged + * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on. + * @param callback Called when the request has completed. + */ + function startCharacteristicNotifications(characteristicId: string, callback: () => void): void; + /** + * Enable value notifications/indications from the specified characteristic. Once enabled, an application can listen to notifications using the onCharacteristicValueChanged event. + * @see onCharacteristicValueChanged + * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on. + * @param properties Notification session properties (optional). + * @param callback Called when the request has completed. + */ + function startCharacteristicNotifications(characteristicId: string, properties: IProperties, callback: () => void): void; + /** + * Disable value notifications/indications from the specified characteristic. After a successful call, the application will stop receiving notifications/indications from this characteristic. + * @param characteristicId The instance ID of the GATT characteristic on which this app's notification session should be stopped. + * @param [callback] Called when the request has completed (optional). + */ + function stopCharacteristicNotifications(characteristicId: string, callback?: () => void): void; + /** + * Notify a remote device of a new value for a characteristic. + * If the shouldIndicate flag in the notification object is true, an indication will be sent instead of a notification. + * Note, the characteristic needs to correctly set the 'notify' or 'indicate' property during creation for this call to succeed. + * This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param characteristicId The characteristic to send the notication for. + * @param notification Notification object + * @param callback Callback called once the notification or indication has been sent successfully. + */ + function notifyCharacteristicValueChanged(characteristicId: string, notification: INotification, callback: () => void): void; + /** + * Retrieve the value of a specified characteristic descriptor from a remote peripheral. + * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be read from the remote device. + * @param callback Called with the Descriptor object whose value was requested. The value field of the returned Descriptor object contains the result of the read request. + */ + function readDescriptorValue(descriptorId: string, callback: (result: Descriptor) => void): void; + /** + * Write the value of a specified characteristic descriptor from a remote peripheral. + * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be written to. + * @param value The value that should be sent to the remote descriptor as part of the write request. + * @param callback Called when the write request has completed. + */ + function writeDescriptorValue(descriptorId: string, value: ArrayBuffer, callback: () => void): void; + /** + * Register the given service with the local GATT server. + * If the service ID is invalid, the lastError will be set. + * This function is only available if the app has both + * the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param serviceId Unique ID of a created service. + * @param callback Callback with the result of the register operation. + */ + function registerService(serviceId: string, callback: () => void): void; + /** + * Unregister the given service with the local GATT server. + * If the service ID is invalid, the lastError will be set. + * This function is only available if the app has both + * the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param serviceId Unique ID of a current registered service. + * @param callback Callback with the result of the register operation. + */ + function unregisterService(serviceId: string, callback: () => void): void; + /** + * Remove the specified service, unregistering it if it was registered. + * If the service ID is invalid, the lastError will be set. + * This function is only available if the app has both + * the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param serviceId Unique ID of a current registered service. + * @param [callback] Callback called once the service is removed. + */ + function removeService(serviceId: string, callback?: () => void): void; + /** + * Create an advertisement and register it for advertising. + * To call this function, the app must have + * the bluetooth:low_energy and bluetooth:peripheral permissions set to true. + * Additionally this API is only available to auto launched apps in Kiosk Mode + * of by setting the 'enable-ble-advertising-in-apps' flag. + * See https://developer.chrome.com/apps/manifest/bluetooth + * Note: On some hardware, central and peripheral modes at the same time + * is supported but on hardware that doesn't support this, + * making this call will switch the device to peripheral mode. + * In the case of hardware which does not support both central and peripheral mode, + * attempting to use the device in both modes will lead to undefined behavior + * or prevent other central-role applications from behaving correctly + * (including the discovery of Bluetooth Low Energy devices). + * @since Since Chrome 47. + * @param advertisement The advertisement to advertise. + * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement. + */ + function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: number) => void): void; + /** + * Unregisters an advertisement and stops its advertising. + * If the advertisement fails to unregister the only way + * to stop advertising might be to restart the device. + * @since Since Chrome 47. + * @param advertisementId Id of the advertisement to unregister. + * @param callback Called once the advertisement is unregistered and is no longer being advertised. + */ + function unregisterAdvertisement(advertisementId: number, callback: () => void): void; + /** + * Resets advertising on the current device. It will unregister and stop all existing advertisements. + * @since Since Chrome 61. + * @param callback Called once the advertisements are reset. + */ + function resetAdvertising(callback: () => void): void; + /** + * Set's the interval betweeen two consecutive advertisements. + * Note: This is a best effort. + * The actual interval may vary non-trivially from the requested intervals. + * On some hardware, there is a minimum interval of 100ms. + * The minimum and maximum values cannot exceed the the range allowed by the Bluetooth 4.2 specification. + * @since Since Chrome 55. + * @param minInterval Minimum interval between advertisments (in milliseconds). This cannot be lower than 20ms (as per the spec). + * @param maxInterval Maximum interval between advertisments (in milliseconds). This cannot be more than 10240ms (as per the spec). + * @param callback Called once the interval has been set. + */ + function setAdvertisingInterval(minInterval: number, maxInterval: number, callback: () => void): void; + /** + * Sends a response for a characteristic or descriptor read/write request. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + * @param response The response to the request. + */ + function sendRequestResponse(response: IResponse): void; + /** Fired whan a new GATT service has been discovered on a remote device. */ + var onServiceAdded: chrome.events.Event<(service: Service) => void>; + /** + * Fired when the state of a remote GATT service changes. + * This involves any characteristics and/or descriptors + * that get added or removed from the service, as well as + * "ServiceChanged" notifications from the remote device. + */ + var onServiceChanged: chrome.events.Event<(service: Service) => void>; + /** Fired when a GATT service that was previously discovered on a remote device has been removed. */ + var onServiceRemoved: chrome.events.Event<(service: Service) => void>; + /** + * Fired when the value of a remote GATT characteristic changes, + * either as a result of a read request, + * or a value change notification/indication. + * This event will only be sent if the app has enabled notifications + * by calling startCharacteristicNotifications. + */ + var onCharacteristicValueChanged: chrome.events.Event<(characteristic: Characteristic) => void>; + /** + * Fired when the value of a remote GATT characteristic descriptor changes, + * usually as a result of a read request. + * This event exists mostly for convenience and will always be sent after + * a successful call to readDescriptorValue. + */ + var onDescriptorValueChanged: chrome.events.Event<(descriptor: Descriptor) => void>; + /** + * Fired when a connected central device requests to read the value of + * a characteristic registered on the local GATT server. + * Not responding to this request for a long time may lead to a disconnection. + * This event is only available if the app has both the bluetooth:low_energy + * and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + */ + var onCharacteristicReadRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + /** + * Fired when a connected central device requests to write the value of + * a characteristic registered on the local GATT server. + * Not responding to this request for a long time may lead to a disconnection. + * This event is only available if the app has both the bluetooth:low_energy + * and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + */ + var onCharacteristicWriteRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + /** + * Fired when a connected central device requests to read the value of + * a descriptor registered on the local GATT server. + * Not responding to this request for a long time may lead to a disconnection. + * This event is only available if the app has both the bluetooth:low_energy + * and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + * @since Since Chrome 52. + */ + var onDescriptorReadRequest: chrome.events.Event<(descriptor: Descriptor) => void>; + /** + * Fired when a connected central device requests to write the value of + * a descriptor registered on the local GATT server. + * Not responding to this request for a long time may lead to a disconnection. + * This event is only available if the app has both the bluetooth:low_energy + * and the bluetooth:peripheral permissions set to true. + * The peripheral permission may not be available to all apps. + */ + var onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; } /** * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. * @since Chrome 37 - * Manifest: "bluetooth": {...} + * Manifest: 'bluetooth': {...} * Important: This API works only on OS X, Windows and Chrome OS. */ namespace bluetoothSocket { - /** NOT IMPLEMENTED YET */ + /* NOT IMPLEMENTED YET */ } //////////////////// @@ -631,7 +1415,7 @@ declare namespace chrome { /** * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. * Availability: Since Chrome 25. - * Manifest: "commands": {...} + * Manifest: 'commands': {...} */ namespace commands { interface Command { @@ -663,17 +1447,17 @@ declare namespace chrome { /** * Use the chrome.contextMenus API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. * Availability: Since Chrome 6. - * Permissions: "contextMenus" + * Permissions: 'contextMenus' */ namespace contextMenus { /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is used to add menu items to the context menu that appears when clicking on the app icon in the launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported in a launcher context menu. **/ - export type ContextType = "all" | "page" | "frame" | "selection" | "link" | "editable" | "image" | "video" | "audio" | "launcher" | "browser_action" | "page_action"; + export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio' | 'launcher' | 'browser_action' | 'page_action'; /** * The type of menu item. **/ - export type ItemType = "normal" | "checkbox" | "radio" | "separator"; + export type ItemType = 'normal' | 'checkbox' | 'radio' | 'separator'; interface OnClickData { /** @@ -746,7 +1530,7 @@ declare namespace chrome { documentUrlPatterns?: string[]; /** Optional. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. */ checked?: boolean; - /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin". */ + /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ title?: string; /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ contexts?: string[]; @@ -873,7 +1657,7 @@ declare namespace chrome { /** * Use the chrome.documentScan API to discover and retrieve images from attached paper document scanners. * Availability: Since Chrome 44. - * Permissions: "documentScan" + * Permissions: 'documentScan' * Important: This API works only on Chrome OS. */ namespace documentScan { @@ -885,7 +1669,7 @@ declare namespace chrome { } interface DocumentScanCallbackArg { - /** The data image URLs in a form that can be passed as the "src" value to an image tag. */ + /** The data image URLs in a form that can be passed as the 'src' value to an image tag. */ dataUrls: string[]; /** The MIME type of dataUrls. */ mimeType: string; @@ -1062,13 +1846,13 @@ declare namespace chrome { */ interface ImageDetails { /** - * @description The format of the resulting image. Default is "jpeg". + * @description The format of the resulting image. Default is 'jpeg'. * @type {ImageFormat} * @memberof ImageDetails */ format?: ImageFormat; /** - * @description When format is "jpeg", controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. + * @description When format is 'jpeg', controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. * @type {number} * @memberof ImageDetails */ @@ -1121,13 +1905,13 @@ declare namespace chrome { */ matchAboutBlank?: boolean; /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". + * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. * @type {RunAt} * @memberof InjectDetails */ runAt: RunAt; /** - * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to "author". + * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to 'author'. * @since Since Chrome 66. * @type {CSSOrigin} * @memberof InjectDetails @@ -1139,32 +1923,118 @@ declare namespace chrome { //////////////////// // FileSystem //////////////////// + /** + * Use the chrome.fileSystem API to create, read, navigate, and write to the user's local file system. + * With this API, Chrome Apps can read and write to a user-selected location. + * For example, a text editor app can use the API to read and write local documents. + * All failures are notified via chrome.runtime.lastError. + */ namespace fileSystem { interface AcceptOptions { + /** + * This is the optional text description for this option. + * If not present, a description will be automatically generated; + * typically containing an expanded list of valid extensions (e.g. 'text/html' may expand to '*.html, *.htm'). + */ description?: string; + /** + * Mime-types to accept, e.g. 'image/jpeg' or 'audio/*'. One of mimeTypes or extensions must contain at least one valid element. + */ mimeTypes?: string[]; + /** + * Extensions to accept, e.g. 'jpg' | 'gif' | 'crx'. + */ extensions?: string[]; } interface ChooseEntryOptions { - type?: string; + /** + * Type of the prompt to show. The default is 'openFile'. + * openFile + * - Prompts the user to open an existing file and returns a FileEntry on success. From Chrome 31 onwards, the FileEntry will be writable if the application has the 'write' permission under 'fileSystem'; otherwise, the FileEntry will be read-only. + * openWritableFile + * - Prompts the user to open an existing file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * saveFile + * - Prompts the user to open an existing file or a new file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * openDirectory + * - Prompts the user to open a directory and returns a DirectoryEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'directory' permission under 'fileSystem'. If the application has the 'write' permission under 'fileSystem', the returned DirectoryEntry will be writable; otherwise it will be read-only. New in Chrome 31. + */ + type?: 'openFile' | 'openWritableFile' | 'saveFile' | 'openDirectory'; + /** The suggested file name that will be presented to the user as the default name to read or write. This is optional. */ suggestedName?: string; + /** The optional list of accept options for this file opener. Each option will be presented as a unique group to the end-user. */ accepts?: AcceptOptions[]; + /** + * Whether to accept all file types, in addition to the options specified in the accepts argument. + * The default is true. If the accepts field is unset or contains no valid entries, this will always be reset to true. + */ acceptsAllTypes?: boolean; + /** + * Whether to accept multiple files. This is only supported for openFile and openWritableFile. + * The callback to chooseEntry will be called with a list of entries if this is set to true. Otherwise it will be called with a single Entry. + */ acceptsMultiple?: boolean; } + type ChildChangeType = 'created' | 'removed' | 'changed'; + + interface Volume { + /** The ID of the requested volume. */ + volumeId: string; + /** Whether the requested file system should be writable. The default is read-only. */ + writable?: boolean; + } + + /** + * Get the display path of an Entry object. + * The display path is based on the full path of the file or directory on the local file system, but may be made more readable for display purposes. + */ export function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void; + /** + * Get a writable Entry from another Entry. This call will fail with a runtime error if the application does not have the 'write' permission under 'fileSystem'. + * If entry is a DirectoryEntry, this call will fail if the application does not have the 'directory' permission under 'fileSystem'. + */ export function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void; + /** Gets whether this Entry is writable or not. */ export function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void; + /** Ask the user to choose a file or directory. */ export function chooseEntry(callback: (entry: Entry) => void): void; + /** Ask the user to choose a file or directory. */ export function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void; + /** Ask the user to choose a file or directory. */ export function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void; + /** Ask the user to choose a file or directory. */ export function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; + /** Returns the file entry with the given id if it can be restored. This call will fail with a runtime error otherwise. */ export function restoreEntry(id: string, callback: (entry: Entry) => void): void; + /** Returns whether the app has permission to restore the entry with the given id. */ export function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; + /** + * Returns an id that can be passed to restoreEntry to regain access to a given file entry. + * Only the 500 most recently used entries are retained, where calls to retainEntry and restoreEntry count as use. + * If the app has the 'retainEntries' permission under 'fileSystem', entries are retained indefinitely. + * Otherwise, entries are retained only while the app is running and across restarts. + * */ export function retainEntry(entry: Entry): string; + /** + * Requests access to a file system for a volume represented by options.volumeId. + * If options.writable is set to true, then the file system will be writable. + * Otherwise, it will be read-only. + * The writable option requires the 'fileSystem': {'write'} permission in the manifest. + * Available to kiosk apps running in kiosk session only. + * For manual-launch kiosk mode, a confirmation dialog will be shown on top of the active app window. + * In case of an error, fileSystem will be undefined, and chrome.runtime.lastError will be set. + */ + export function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; + /** + * Returns a list of volumes available for requestFileSystem(). + * The 'fileSystem': {'requestFileSystem'} manifest permission is required. + * Available to kiosk apps running in the kiosk session only. + * In case of an error, volumes will be undefined, and chrome.runtime.lastError will be set. + */ + export function getVolumeList(callback: (volumes: Volume[]) => void): void; + export var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; } @@ -1174,7 +2044,7 @@ declare namespace chrome { /** * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. * Availability: Since Chrome 40. - * Permissions: "fileSystemProvider" + * Permissions: 'fileSystemProvider' * Important: This API works only on Chrome OS. */ namespace fileSystemProvider { @@ -1204,7 +2074,7 @@ declare namespace chrome { /** File size in bytes. */ size: number; /** The last modified time of this entry. */ - modificationTime: Date; + modificationTime: any; /** Optional. Mime type for the entry. */ mimeType?: string; /** Optional. Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. Optional, but can be provided only when explicitly requested by the onGetMetadataRequested event. */ @@ -1460,7 +2330,7 @@ declare namespace chrome { /** * Notifies about changes in the watched directory at observedPath in recursive mode. If the file system is mounted with supportsNofityTag, then tag must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with getAll. * To use, the file_system_provider.notify manifest option must be set to true. - * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to "123", then it should call notify for all changes which happened since the change tagged as "123". It cannot be an empty string. + * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to '123', then it should call notify for all changes which happened since the change tagged as '123'. It cannot be an empty string. * Not all providers are able to provide a tag, but if the file system has a changelog, then the tag can be eg. a change number, or a revision number. * Note that if a parent directory is removed, then all descendant entries are also removed, and if they are watched, then the API must be notified about the fact. Also, if a directory is renamed, then all descendant entries are in fact removed, as there is no entry under their original paths anymore. * In case of an error, runtime.lastError will be set will a corresponding error code. @@ -1486,7 +2356,7 @@ declare namespace chrome { export var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; /** Raised when deleting an entry is requested. If recursive is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ export var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; - /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the "EXISTS" error code. */ + /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the 'EXISTS' error code. */ export var onCreateFileRequested: FilePathRequestedEvent; /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ export var onCopyEntryRequested: SourceTargetPathRequestedEvent; @@ -1526,9 +2396,17 @@ declare namespace chrome { /** * Use chrome.gcm to enable apps and extensions to send and receive messages through the Google Cloud Messaging Service. * Availability: Since Chrome 35. - * Permissions: "gcm" + * Permissions: 'gcm' */ namespace gcm { + interface IGCMData { + 'collapse_key'?: never; + 'goog'?: never; + 'goog.'?: never; + 'google'?: never; + 'GOOGLE'?: never; + [key: string]: any; + } interface OutgoingMessage { /** The ID of the server to send the message to as assigned by Google API Console. */ destinationId: string; @@ -1536,13 +2414,15 @@ declare namespace chrome { messageId: string; /** Optional. Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ timeToLive?: number; - /** Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes. Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. */ - data: Object; + /** + * @description Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes. Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. + **/ + data: IGCMData; } interface IncomingMessage { /** The message data. */ - data: Object; + data: IGCMData; /** * Optional. * The sender who issued the message. @@ -1571,7 +2451,7 @@ declare namespace chrome { interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> { } - /** The maximum size (in bytes) of all key/value pairs in a message. */ + /** The maximum size (in bytes) of all key/value pairs in a message. Default: 4096 */ export var MAX_MESSAGE_SIZE: number; /** @@ -1629,9 +2509,11 @@ declare namespace chrome { namespace i18n { /** Holds detected ISO language code and its percentage in the input string */ interface DetectedLanguage { - /** An ISO language code such as 'en' or 'fr'. - * For a complete list of languages supported by this method, see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}. - * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ + /** + * @description An ISO language code such as 'en' or 'fr'. + * @description For a complete list of languages supported by this method: + * @see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}. + * @description For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ language: string; /** The percentage of the detected language */ @@ -1659,7 +2541,7 @@ declare namespace chrome { * @param messageName The name of the message, as specified in the messages.json file. * @param substitutions Optional. Up to 9 substitution strings, if the message requires any. */ - export function getMessage(messageName: string, substitutions?: any): string; + export function getMessage(messageName: string, substitutions?: any): string | undefined; /** * Gets the browser UI language of the browser. This is different from i18n.getAcceptLanguages which returns the preferred user languages. * @since Chrome 35. @@ -1678,7 +2560,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.identity API to get OAuth2 access tokens. - * Permissions: "identity" + * Permissions: 'identity' * @since Chrome 29. */ namespace identity { @@ -1697,7 +2579,7 @@ declare namespace chrome { /** * Optional. * The account ID whose token should be returned. If not specified, the primary account for the profile will be used. - * account is only supported when the "enable-new-profile-management" flag is set. + * account is only supported when the 'enable-new-profile-management' flag is set. * @since Chrome 37. */ account?: AccountInfo; @@ -1797,14 +2679,14 @@ declare namespace chrome { //////////////////// /** * Use the chrome.idle API to detect when the machine's idle state changes. - * Permissions: "idle" + * Permissions: 'idle' * @since Chrome 6. */ namespace idle { interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> { } /** - * Returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. + * Returns 'locked' if the system is locked, 'idle' if the user has not generated any input for a specified number of seconds, or 'active' otherwise. * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. * Since Chrome 25. * @param callback The callback parameter should be a function that looks like this: @@ -1818,7 +2700,7 @@ declare namespace chrome { */ export function setDetectionInterval(intervalInSeconds: number): void; - /** Fired when the system changes to an active, idle or locked state. The event fires with "locked" if the screen is locked or the screensaver activates, "idle" if the system is unlocked and the user has not generated any input for a specified number of seconds, and "active" when the user generates input on an idle system. */ + /** Fired when the system changes to an active, idle or locked state. The event fires with 'locked' if the screen is locked or the screensaver activates, 'idle' if the system is unlocked and the user has not generated any input for a specified number of seconds, and 'active' when the user generates input on an idle system. */ export var onStateChanged: IdleStateChangedEvent; } @@ -2071,7 +2953,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.notifications API to create rich notifications using templates and show these notifications to users in the system tray. - * Permissions: "notifications" + * Permissions: 'notifications' * @since Chrome 28. */ namespace notifications { @@ -2307,7 +3189,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.power API to override the system's power management features. - * Permissions: "power" + * Permissions: 'power' * @since Chrome 27. */ namespace power { @@ -2322,7 +3204,7 @@ declare namespace chrome { //////////////////// /** * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. - * Permissions: "printerProvider" + * Permissions: 'printerProvider' * @since Chrome 44. */ namespace printerProvider { @@ -2347,7 +3229,7 @@ declare namespace chrome { title: string; /** Print ticket in CJT format. */ ticket: Object; - /** The document content type. Supported formats are "application/pdf" and "image/pwg-raster". */ + /** The document content type. Supported formats are 'application/pdf' and 'image/pwg-raster'. */ contentType: string; /** Blob containing the document data to print. Format must match |contentType|. */ document: Blob; @@ -2400,7 +3282,7 @@ declare namespace chrome { interface InstalledDetails { /** * The reason that this event is being dispatched. - * One of: "install", "update", "chrome_update", or "shared_module_update" + * One of: 'install', 'update', 'chrome_update', or 'shared_module_update' */ reason: string; /** @@ -2452,17 +3334,17 @@ declare namespace chrome { interface PlatformInfo { /** * The operating system chrome is running on. - * One of: "mac", "win", "android", "cros", "linux", or "openbsd" + * One of: 'mac', 'win', 'android', 'cros', 'linux', or 'openbsd' */ os: string; /** * The machine's processor architecture. - * One of: "arm", "x86-32", or "x86-64" + * One of: 'arm', 'x86-32', or 'x86-64' */ arch: string; /** * The native client architecture. This may be different from arch on some platforms. - * One of: "arm", "x86-32", or "x86-64" + * One of: 'arm', 'x86-32', or 'x86-64' */ nacl_arch: string; } @@ -2629,14 +3511,14 @@ declare namespace chrome { sub_package_path: string; }[]; /** - * Technologies required by the app or extension. Hosting sites such as the Chrome Web Store may use this list to dissuade users from installing apps or extensions that will not work on their computer. Supported requirements currently include "3D" and "plugins"; additional requirements checks may be added in the future. + * Technologies required by the app or extension. Hosting sites such as the Chrome Web Store may use this list to dissuade users from installing apps or extensions that will not work on their computer. Supported requirements currently include '3D' and 'plugins'; additional requirements checks may be added in the future. */ requirements?: { /** - * The "3D" requirement denotes GPU hardware acceleration. The "webgl" requirement refers to the WebGL API. For more information on Chrome 3D graphics support, see the help article on WebGL and 3D graphics. You can list the 3D-related features your app requires, as demonstrated in the following example: - * "requirements": { - * "3D": { - * "features": ["webgl"] + * The '3D' requirement denotes GPU hardware acceleration. The 'webgl' requirement refers to the WebGL API. For more information on Chrome 3D graphics support, see the help article on WebGL and 3D graphics. You can list the 3D-related features your app requires, as demonstrated in the following example: + * 'requirements': { + * '3D': { + * 'features': ['webgl'] * } * } */ @@ -2644,10 +3526,10 @@ declare namespace chrome { features?: Array; }; /** - * The "plugins" requirement indicates if an app or extension requires NPAPI to run. This requirement is enabled by default when the manifest includes the "plugins" field. For apps and extensions that still work when plugins aren't available, you can disable this requirement by setting NPAPI to false. You can also enable this requirement manually, by setting NPAPI to true, as shown in this example: - * "requirements": { - * "plugins": { - * "npapi": true + * The 'plugins' requirement indicates if an app or extension requires NPAPI to run. This requirement is enabled by default when the manifest includes the 'plugins' field. For apps and extensions that still work when plugins aren't available, you can disable this requirement by setting NPAPI to false. You can also enable this requirement manually, by setting NPAPI to true, as shown in this example: + * 'requirements': { + * 'plugins': { + * 'npapi': true * } * } */ @@ -2754,7 +3636,7 @@ declare namespace chrome { * Requests an update check for this app/extension. * @since Chrome 25. * @param callback - * Parameter status: Result of the update check. One of: "throttled", "no_update", or "update_available" + * Parameter status: Result of the update check. One of: 'throttled', 'no_update', or 'update_available' * Optional parameter details: If an update is available, this contains more information about the available update. */ export function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; @@ -3029,7 +3911,7 @@ declare namespace chrome { interface SocketProperties { /** * Flag indicating if the socket remains open when the event page of the - * application is unloaded. The default value is "false." When the + * application is unloaded. The default value is 'false.' When the * application is loaded, any sockets previously opened with * persistent=true can be fetched with getSockets. * @@ -3051,7 +3933,7 @@ declare namespace chrome { /** * Flag indicating if the socket remains open when the event page of the * application is unloaded (see SocketProperties.persistent). The - * default value is "false". + * default value is 'false'. */ persistent: boolean; @@ -3061,7 +3943,7 @@ declare namespace chrome { /** * Flag indicating whether connection requests on a listening socket are * dispatched through the onAccept event or queued up in the listen - * queue backlog. See setPaused. The default value is "false" + * queue backlog. See setPaused. The default value is 'false' */ paused: boolean; @@ -3203,7 +4085,7 @@ declare namespace chrome { /** * Use the chrome.sockets.udp API to send and receive data over the network * using UDP connections. This API supersedes the UDP functionality previously - * found in the "socket" API. + * found in the 'socket' API. * * @since Chrome 33 * @see https://developer.chrome.com/apps/sockets_udp @@ -3236,7 +4118,7 @@ declare namespace chrome { interface SocketProperties { /** * Flag indicating if the socket is left open when the event page of the - * application is unloaded. The default value is "false." When the + * application is unloaded. The default value is 'false.' When the * application is loaded, any sockets previously opened with * persistent=true can be fetched with getSockets. * @see http://developer.chrome.com/apps/app_lifecycle.html @@ -3343,9 +4225,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-bind * @param socketId The socket ID. * @param address The address of the local machine. DNS name, IPv4 and IPv6 - * formats are supported. Use "0.0.0.0" to accept packets + * formats are supported. Use '0.0.0.0' to accept packets * from all local available network interfaces. - * @param port The port of the local machine. Use "0" to bind to a free + * @param port The port of the local machine. Use '0' to bind to a free * port. * @param callback Called when the bind operation completes. */ @@ -3499,7 +4381,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.storage API to store, retrieve, and track changes to user data. - * Permissions: "storage" + * Permissions: 'storage' * @since Chrome 20. */ namespace storage { @@ -3526,7 +4408,7 @@ declare namespace chrome { /** * Sets multiple items. * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. - * Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation). + * Primitive values such as numbers will serialize as expected. Values with a typeof 'object' and 'function' will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation). * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ @@ -3622,7 +4504,7 @@ declare namespace chrome { //////////////////// /** * Use the system.cpu API to query CPU metadata. - * Permissions: "system.cpu" + * Permissions: 'system.cpu' * @since Chrome 32. */ namespace system.cpu { @@ -3651,7 +4533,7 @@ declare namespace chrome { modelName: string; /** * A set of feature codes indicating some of the processor's capabilities. - * The currently supported codes are "mmx", "sse", "sse2", "sse3", "ssse3", "sse4_1", "sse4_2", and "avx". + * The currently supported codes are 'mmx', 'sse', 'sse2', 'sse3', 'ssse3', 'sse4_1', 'sse4_2', and 'avx'. */ features: string[]; /** Information about each logical processor. */ @@ -3667,7 +4549,7 @@ declare namespace chrome { //////////////////// /** * Use the system.display API to query display metadata. - * Permissions: "system.display" + * Permissions: 'system.display' * @since Chrome 30. */ namespace system.display { @@ -3830,7 +4712,7 @@ declare namespace chrome { interface DisplayInfo { /** The unique identifier of the display. */ id: string; - /** The user-friendly name (e.g. "HP LCD monitor"). */ + /** The user-friendly name (e.g. 'HP LCD monitor'). */ name: string; /** Identifier of the display that is being mirrored on the display unit. If mirroring is not in progress, set to an empty string. Currently exposed only on ChromeOS. Will be empty string on other platforms. */ mirroringSourceId: string; @@ -4003,7 +4885,7 @@ declare namespace chrome { //////////////////// /** * The chrome.system.memory API. - * Permissions: "system.memory" + * Permissions: 'system.memory' * @since Chrome 32. */ namespace system.memory { @@ -4036,7 +4918,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.system.storage API to query storage device information and be notified when a removable storage device is attached and detached. - * Permissions: "system.storage" + * Permissions: 'system.storage' * @since Chrome 30. */ namespace system.storage { @@ -4092,7 +4974,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.tts API to play synthesized text-to-speech (TTS). See also the related ttsEngine API, which allows an extension to implement a speech engine. - * Permissions: "tts" + * Permissions: 'tts' * @since Chrome 14. */ namespace tts { @@ -4104,7 +4986,7 @@ declare namespace chrome { errorMessage?: string; /** * The type can be 'start' as soon as speech has started, 'word' when a word boundary is reached, 'sentence' when a sentence boundary is reached, 'marker' when an SSML mark element is reached, 'end' when the end of the utterance is reached, 'interrupted' when the utterance is stopped or interrupted before reaching the end, 'cancelled' when it's removed from the queue before ever being synthesized, or 'error' when any other error occurs. When pausing speech, a 'pause' event is fired if a particular utterance is paused in the middle, and 'resume' if an utterance resumes speech. Note that pause and resume events may not fire if speech is paused in-between utterances. - * One of: "start", "end", "word", "sentence", "marker", "interrupted", "cancelled", "error", "pause", or "resume" + * One of: 'start', 'end', 'word', 'sentence', 'marker', 'interrupted', 'cancelled', 'error', 'pause', or 'resume' */ type: string; } @@ -4115,7 +4997,7 @@ declare namespace chrome { lang?: string; /** * Optional. This voice's gender. - * One of: "male", or "female" + * One of: 'male', or 'female' */ gender?: string; /** Optional. The name of the voice. */ @@ -4162,7 +5044,7 @@ declare namespace chrome { extensionId?: string; /** * Optional. Gender of voice for synthesized speech. - * One of: "male", or "female" + * One of: 'male', or 'female' */ gender?: string; /** Optional. The TTS event types the voice must support. */ @@ -4412,7 +5294,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.vpnProvider API to implement a VPN client. - * Permissions: "vpnProvider" + * Permissions: 'vpnProvider' * Important: This API works only on Chrome OS. * @since Chrome 43. */ @@ -4429,7 +5311,7 @@ declare namespace chrome { */ exclusionList: string[]; /** - * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry "0.0.0.0/0" to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. + * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry '0.0.0.0/0' to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. */ inclusionList: string[]; /** Optional. A list of search domains. (default: no search domain) */ @@ -4462,7 +5344,7 @@ declare namespace chrome { */ export function destroyConfig(id: string, callback?: Function): void; /** - * Sets the parameters for the VPN session. This should be called immediately after "connected" is received from the platform. This will succeed only when the VPN session is owned by the extension. + * Sets the parameters for the VPN session. This should be called immediately after 'connected' is received from the platform. This will succeed only when the VPN session is owned by the extension. * @param parameters The parameters for the VPN session. * @param callback Called when the parameters are set or if there is an error. */ @@ -4499,7 +5381,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.wallpaper API to change the ChromeOS wallpaper. - * Permissions: "wallpaper" + * Permissions: 'wallpaper' * Important: This API works only on Chrome OS. * @since Chrome 43. */ @@ -4511,7 +5393,7 @@ declare namespace chrome { url?: string; /** * The supported wallpaper layouts. - * One of: "STRETCH", "CENTER", or "CENTER_CROPPED" + * One of: 'STRETCH', 'CENTER', or 'CENTER_CROPPED' */ layout: string; /** The file name of the saved wallpaper. */ @@ -4533,7 +5415,7 @@ declare namespace chrome { // Webview Tag /////////////////// /** - * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. Your app can control the appearance of the webview and interact with the web content, initiate navigations in an embedded web page, react to error events that happen within it, and more (see Usage). + * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. Your app can control the appearance of the webview and interact with the web content, initiate navigations in an embedded web page, react to error events that happen within it, and more (see Usage). */ namespace webview { /** Options that determine what data should be cleared by `clearData`. */ @@ -4611,7 +5493,7 @@ declare namespace chrome { */ interface InjectDetails { /** - * @description JavaScript or CSS code to inject.

Warning:
Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. + * @description JavaScript or CSS code to inject.

Warning:
Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. * @type {string} * @memberof InjectDetails */ @@ -4624,38 +5506,501 @@ declare namespace chrome { file?: string } - interface WebViewElementEventMap { - 'close': Event, - 'consolemessage': IConsolemessage, - 'contentload': Event, - 'dialog': IDialog, - 'exit': IExit, - 'findupdate': IFindupdate, - 'loadabort': ILoadabort, - 'loadcommit': ILoadcommit, - 'loadredirect': ILoadredirect, - 'loadstart': ILoadstart, - 'loadstop': Event, - 'newwindow': INewwindow, - 'permissionrequest': IPermissionrequest, - 'responsive': IResponsive, - 'sizechanged': ISizechanged, - 'unresponsive': IUnresponsive, - 'zoomchange': IZoomchange, - } - - /** - * @description - * @export - * @interface HTMLWebViewElement - * @extends {Element} + * @description WebView element from html */ interface HTMLWebViewElement extends Element { - executeScript?: (details: InjectDetails, callback?: (result: any) => void) => void; + /** + * This sets the guest content's window.name object. + */ + name: string; + /** + * Returns the visible URL. Mirrors the logic in the browser's omnibox: either returning a pending new navigation if initiated by the embedder page, or the last committed navigation. Writing to this attribute initiates top-level navigation. + * Assigning src its own value will reload the current page. + * The src attribute cannot be cleared or removed once it has been set, unless the webview is removed from the DOM. + * The src attribute can also accept data URLs, such as 'data:text/plain,Hello, world!'. + */ src: string; - contentWindow: Window; - addEventListener(type: K, listener: (this: HTMLWebViewElement, ev: WebViewElementEventMap[K]) => any, useCapture?: boolean): void; + /** + * Storage partition ID used by the webview tag. If the storage partition ID starts with persist: (partition='persist:googlepluswidgets'), the webview will use a persistent storage partition available to all guests in the app with the same storage partition ID. If the ID is unset or if there is no 'persist': prefix, the webview will use an in-memory storage partition. This value can only be modified before the first navigation, since the storage partition of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. By assigning the same partition ID, multiple webviews can share the same storage partition. + */ + partition?: string; + /** + * If present, portions of the embedder could be visible through the webview, where the contents are transparent. Without allowtransparency enabled, no part of the embedder will be shown through the webview, even if elements exist that are specified as transparent. + * This does not affect transparency within the contents of the webview itself. + */ + allowtransparency?: boolean; + /** + * If 'on', the webview container will automatically resize within the bounds specified by the attributes minwidth, minheight, maxwidth, and maxheight. + * These constraints do not impact the webview UNLESS autosize is enabled. + * When autosize is enabled, the webview container size cannot be less than the minimum values or greater than the maximum. + */ + autosize?: 'on'; + /** + * Object reference which can be used to post messages into the guest page. + */ + contentWindow: ContentWindow; + /** Interface which provides access to webRequest events on the guest page. */ + request: WebRequestEventInterface; + /** Similar to chrome's ContextMenus API, but applies to webview instead of browser. Use the webview.contextMenus API to add items to webview's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. */ + contextMenus: webview.ContextMenus; + /** + * Fired when the guest window attempts to close itself. + * The following example code navigates the webview to about:blank when the guest attempts to close itself. + */ + addEventListener(type: 'close', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * Fired when the guest window logs a console message. + * The following example code forwards all log messages to the embedder's console without regard for log level or other properties. + */ + addEventListener(type: 'consolemessage', listener: (this: HTMLWebViewElement, ev: IConsoleMessage) => void, useCapture?: boolean): void; + /** + * Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads. + * The following example code modifies the default font size of the guest's body element after the page loads: + * @example + * webview.addEventListener('contentload', function() { + * webview.executeScript({ code: 'document.body.style.fontSize = '42px'' }) + * }); + */ + addEventListener(type: 'contentload', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt. + * Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.) + * The default behavior is to cancel the dialog. + */ + addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: IDialog) => void, useCapture?: boolean): void; + /** + * Fired when the process rendering the guest web content has exited. + */ + addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: IExit) => void, useCapture?: boolean): void; + /** + * Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. + */ + addEventListener(type: 'findupdate', listener: (this: HTMLWebViewElement, ev: IFindupdate) => void, useCapture?: boolean): void; + /** + * Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented. + * Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted. + * Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'. + */ + addEventListener(type: 'loadabort', listener: (this: HTMLWebViewElement, ev: ILoadabort) => void, useCapture?: boolean): void; + /** + * Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. + */ + addEventListener(type: 'loadcommit', listener: (this: HTMLWebViewElement, ev: ILoadcommit) => void, useCapture?: boolean): void; + /** + * Fired when a top-level load request has redirected to a different URL. + */ + addEventListener(type: 'loadredirect', listener: (this: HTMLWebViewElement, ev: ILoadredirect) => void, useCapture?: boolean): void; + /** + * Fired when a load has begun. + */ + addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: ILoadstart) => void, useCapture?: boolean): void; + /** + * Fired when all frame-level loads in a guest page (including all its subframes) have completed. + * This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. + * This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. + * This pattern is commonly observed on pages that load ads. + * Note: When a committed load is aborted, a loadstop event will eventually follow a loadabort event, even if all committed loads since the last loadstop event (if any) were aborted. + */ + addEventListener(type: 'loadstop', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * Fired when the guest page attempts to open a new browser window. + * The following example code will create and navigate a new webview in the embedder for each requested new window: + * @example + * webview.addEventListener('newwindow', function(e) { + * var newWebview = document.createElement('webview'); + * document.body.appendChild(newWebview); + * e.window.attach(newWebview); + * }); + */ + addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: INewwindow) => void, useCapture?: boolean): void; + /** + * Fired when the guest page needs to request special permission from the embedder. + * The following example code will grant the guest page access to the webkitGetUserMedia API. + * Note that an app using this example code must itself specify audioCapture and/or videoCapture manifest permissions: + * @example + * webview.addEventListener('permissionrequest', function(e) { + * if (e.permission === 'media') { + * e.request.allow(); + * } + * }); + */ + addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: IPermissionrequest) => void, useCapture?: boolean): void; + /** Fired when the process rendering the guest web content has become responsive again after being unresponsive. */ + addEventListener(type: 'response', listener: (this: HTMLWebViewElement, ev: IResponsive) => void, useCapture?: boolean): void; + /** Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. */ + addEventListener(type: 'sizechanged', listener: (this: HTMLWebViewElement, ev: ISizechanged) => void, useCapture?: boolean): void; + /** Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. */ + addEventListener(type: 'unresponsive', listener: (this: HTMLWebViewElement, ev: IUnresponsive) => void, useCapture?: boolean): void; + /** Fired when the page's zoom changes. */ + addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: IZoomchange) => void, useCapture?: boolean): void; + /** + * @description Queries audio state. + */ + getAudioState(callback: (audible: boolean) => void): void; + + /** + * @description Sets audio mute state of the webview. + * @param {boolean} mute Mute audio value + */ + setAudioMuted(mute: boolean): void; + + /** + * @description Queries whether audio is muted. + */ + isAudioMuted(callback: (muted: boolean) => void): void; + + /** + * @description Captures the visible region of the webview. + * @param {(dataUrl: string) => void} callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. + */ + captureVisibleRegion(callback: (dataUrl: string) => void): void; + /** + * @description Captures the visible region of the webview. + * @param {*} options + * @param {(dataUrl: string) => void} callback + */ + captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; + + /** + * Adds content script injection rules to the webview. + * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. + * You can programmatically add rules or update existing rules. + * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. + * webview.addContentScripts([ + * { + * name: 'myRule', + * matches: ['http://www.foo.com/*'], + * css: { files: ['mystyles.css'] }, + * js: { files: ['jquery.js', 'myscript.js'] }, + * run_at: 'document_start' + * }, + * { + * name: 'anotherRule', + * matches: ['http://www.bar.com/*'], + * js: { code: 'document.body.style.backgroundColor = 'red';' }, + * run_at: 'document_end' + * }]); + * ... + * + * // Navigates webview. + * webview.src = 'http://www.foo.com'; + * You can defer addContentScripts call until you needs to inject scripts. + * The following example shows how to overwrite an existing rule. + * + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.foo.com/*'], + * js: { files: ['scriptA.js'] }, + * run_at: 'document_start'}]); + * + * // Do something. + * webview.src = 'http://www.foo.com/*'; + * ... + * // Overwrite 'rule' defined before. + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.bar.com/*'], + * js: { files: ['scriptB.js'] }, + * run_at: 'document_end'}]); + * If webview has been naviagted to the origin (e.g., foo.com) and calls webview.addContentScripts to add 'myRule', + * you need to wait for next navigation to make the scripts injected. + * If you want immediate injection, executeScript will do the right thing. + * Rules are preserved even if the guest process crashes or is killed or even if the webview is reparented. + * Refer to the /extensions/content_scripts documentation for more details. + * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. + */ + addContentScripts(contentScriptList: ContentScriptDetails[]): void; + + /** + * @description Navigates backward one history entry if possible. Equivalent to go(-1). + * @param {(success: boolean) => void} [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. + */ + back(callback?: (success: boolean) => void): void; + + /** + * @description Indicates whether or not it is possible to navigate backward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + */ + canGoBack(): void; + + /** + * @description Indicates whether or not it is possible to navigate forward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + */ + canGoForward(): void; + + /** + * @description

Clears browsing data for the webview partition.

+ * @param options Options determining which data to clear. + * @param types The types of data to be cleared. + * @param callback + */ + clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; + + /** + * @description

Injects JavaScript code into the guest page.

The following sample code uses script injection to set the guest page's background color to red:

webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' });
+ * @param details Details of the script to run. + * @param callback + */ + executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; + + /** + * @description Initiates a find-in-page request. + * @param {string} searchText The string to find in the page. + * @param options Options for the find request. + * @param callback + */ + find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; + + /** + * @description Navigates forward one history entry if possible. Equivalent to go(1). + * @param callback + */ + forward(callback?: (success: boolean) => void): void; + + /** + * @description Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. + */ + getProcessId(): void; + + /** + * @description Returns the user agent string used by the webview for guest page requests. + */ + getUserAgent(): void; + + /** + * @description Gets the current zoom factor. + * @param callback + */ + getZoom(callback: (zoomFactor: number) => void): void; + + /** + * @description Gets the current zoom mode. + * @param callback + */ + getZoomMode(callback: (ZoomMode: any) => void): void; + + /** + * @description Navigates to a history entry using a history index relative to the current navigation. If the requested navigation is impossible, this method has no effect. + * @param {number} relativeIndex Relative history index to which the webview should be navigated. For example, a value of 2 will navigate forward 2 history entries if possible; a value of -3 will navigate backward 3 entries. + * @param callback + */ + go(relativeIndex: number, callback?: (success: boolean) => void): void; + + /** + * @description Injects CSS into the guest page. + * @param details Details of the CSS to insert. + * @param callback + */ + insertCSS(details: InjectDetails, callback?: () => void): void; + + /** + * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). + */ + isUserAgentOverridden(): void; + + /** + * @description Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. + */ + print(): void; + + /** + * @description Reloads the current top-level page. + */ + reload(): void; + + /** + * @description Removes content scripts from a webview. + * @description The following example removes 'myRule' which was added before. + * @example webview.removeContentScripts(['myRule']); + * @description You can remove all the rules by calling: + * @example webview.removeContentScripts(); + * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. + */ + removeContentScripts(scriptNameList?: any[]): void; + + /** + * @description Override the user agent string used by the webview for guest page requests. + * @param {string} userAgent The user agent string to use. + */ + setUserAgentOverride(userAgent: string): void; + + /** + * @description Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see $(ref:webviewTag.ZoomMode)). + * @param {number} zoomFactor The new zoom factor. + * @param callback + */ + setZoom(zoomFactor: number, callback?: () => void): void; + + /** + * @description Sets the zoom mode of the webview. + * @param ZoomMode Defines how zooming is handled in the webview. + * @param callback + */ + setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; + + /** + * @description Stops loading the current webview navigation if in progress. + */ + stop(): void; + + /** + * @description Ends the current find session (clearing all highlighting) and cancels all find requests in progress. + * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. + */ + stopFinding(action?: string): void; + + /** + * @description Loads a data URL with a specified base URL used for relative links. Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. + * @param {string} dataUrl The data URL to load. + * @param {string} baseUrl The base URL that will be used for relative links. + * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). + */ + loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; + + /** + * @description Forcibly kills the guest web page's renderer process. This may affect multiple webview tags in the current app if they share the same process, but it will not affect webview tags in other apps. + */ + terminate(): void; + + /** + * @description Fired when the guest window attempts to close itself.

The following example code navigates the webview to about:blank when the guest attempts to close itself.

webview.addEventListener('close', function() {
+              webview.src = 'about:blank';
+            });
+ */ + + close(event: chrome.events.Event): void; + + /** + * @description Fired when the guest window logs a console message.

The following example code forwards all log messages to the embedder's console without regard for log level or other properties.

webview.addEventListener('consolemessage', function(e) {
+              console.log('Guest page logged a message: ', e.message);
+            });
+ * @param callback + */ + + consolemessage: chrome.events.Event; + + /** + * @description Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads.

The following example code modifies the default font size of the guest's body element after the page loads:

webview.addEventListener('contentload', function() {
+              webview.executeScript({ code: 'document.body.style.fontSize = '42px'' });
+            });
+ */ + + contentload: (event: chrome.events.Event) => void; + + /** + * @description Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

+ * @param callback + */ + + dialog: chrome.events.Event; + + /** + * @description Fired when the process rendering the guest web content has exited.

The following example code will show a farewell message whenever the guest page crashes:

webview.addEventListener('exit', function(e) {
+              if (e.reason === 'crash') {
+                webview.src = 'data:text/plain,Goodbye, world!';
+              }
+            });
+ * @param callback + */ + + exit: chrome.events.Event; + + /** + * @description Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. + * @param callback + */ + + findupdate: chrome.events.Event; + + /** + * @description Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented.

Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted.

Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'.

+ * @param callback + */ + + loadabort: chrome.events.Event; + + /** + * @description Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. + * @param callback + */ + + loadcommit: chrome.events.Event; + + /** + * @description Fired when a top-level load request has redirected to a different URL. + * @param callback + */ + + loadredirect: chrome.events.Event; + + /** + * @description Fired when a load has begun. + * @param callback + */ + + loadstart: chrome.events.Event; + + /** + * @description Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.

Note: When a committed load is aborted, a loadstop event will eventually follow a loadabort event, even if all committed loads since the last loadstop event (if any) were aborted.

+ */ + + loadstop(event: chrome.events.Event): void; + + /** + * @description Fired when the guest page attempts to open a new browser window.

The following example code will create and navigate a new webview in the embedder for each requested new window:

webview.addEventListener('newwindow', function(e) {
+              var newWebview = document.createElement('webview');
+              document.body.appendChild(newWebview);
+              e.window.attach(newWebview);
+            });
+ * @param callback + */ + + newwindow: chrome.events.Event; + + /** + * @description Fired when the guest page needs to request special permission from the embedder.

The following example code will grant the guest page access to the webkitGetUserMedia API. Note that an app using this example code must itself specify audioCapture and/or videoCapture manifest permissions:

webview.addEventListener('permissionrequest', function(e) {
+              if (e.permission === 'media') {
+                e.request.allow();
+              }
+            });
+ * @param callback + */ + + permissionrequest: chrome.events.Event; + + /** + * @description Fired when the process rendering the guest web content has become responsive again after being unresponsive.

The following example code will fade the webview element in or out as it becomes responsive or unresponsive:

webview.style.webkitTransition = 'opacity 250ms';
+            webview.addEventListener('unresponsive', function() {
+              webview.style.opacity = '0.5';
+            });
+            webview.addEventListener('responsive', function() {
+              webview.style.opacity = '1';
+            });
+ * @param callback + */ + + responsive: chrome.events.Event; + + /** + * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. + * @param callback + */ + + sizechanged: chrome.events.Event; + + /** + * @description Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. + * @param callback + */ + + unresponsive: chrome.events.Event; + + /** + * @description Fired when the page's zoom changes. + * @param callback + */ + + zoomchange: chrome.events.Event; } /**Options that determine what data should be cleared by clearData. */ @@ -4717,21 +6062,21 @@ declare namespace chrome { /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts. * Enum values: - * "all" - * "page" - * "frame" - * "selection" - * "link" - * "editable" - * "image" - * "video" - * "audio" */ - export type ContextType = "all" | "page" | "frame" | "selection" | "link" | "editable" | "image" | "video" | "audio"; + * 'all' + * 'page' + * 'frame' + * 'selection' + * 'link' + * 'editable' + * 'image' + * 'video' + * 'audio' */ + export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio'; /**Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ interface InjectDetails { /** - * @description JavaScript or CSS code to inject. Warning: Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. + * @description JavaScript or CSS code to inject. Warning: Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. */ code?: string @@ -4787,7 +6132,7 @@ declare namespace chrome { js?: InjectionItems /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". + * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. */ run_at?: chrome.extensionTypes.RunAt; @@ -4820,7 +6165,7 @@ declare namespace chrome { id?: string /** - * @description The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin". + * @description The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ title?: string @@ -4836,7 +6181,7 @@ declare namespace chrome { /** * @description A function that will be called back when the menu item is clicked. - * @param {any} [object Object] + * @param callback */ onclick?: (info: any) => void @@ -4885,7 +6230,7 @@ declare namespace chrome { /** * @description A function that will be called back when the menu item is clicked. - * @param {any} [object Object] + * @param callback */ onclick?: (info: any) => void @@ -4914,28 +6259,28 @@ declare namespace chrome { /** * @description Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). * @param {object} createProperties The properties used to create the item - * @param {any} [object Object] + * @param callback */ create(createProperties: object, callback?: () => void): void; /** * @description Updates a previously created context menu item. - * @param {any} id The ID of the item to update. + * @param id The ID of the item to update. * @param {object} updateProperties The properties to update. Accepts the same values as the create function. - * @param {any} [object Object] + * @param callback */ update(id: number | string, updateProperties: object, callback?: () => void): void; /** * @description Removes a context menu item. - * @param {any} menuItemId The ID of the context menu item to remove. - * @param {any} [object Object] + * @param menuItemId The ID of the context menu item to remove. + * @param callback */ remove(menuItemId: number | string, callback?: () => void): void; /** * @description Removes all context menu items added to this webview. - * @param {any} [object Object] + * @param callback */ removeAll(callback?: () => void): void; @@ -4956,8 +6301,8 @@ declare namespace chrome { interface ContentWindow { /** - * @description

Posts a message to the embedded web content as long as the embedded content is displaying a page from the target origin. This method is available once the page has completed loading. Listen for the contentload event and then call the method.

The guest will be able to send replies to the embedder by posting message to event.source on the message event it receives.

This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a message event listener to its own frame.

- * @param {any} message Message object to send to the guest. + * @description

Posts a message to the embedded web content as long as the embedded content is displaying a page from the target origin. This method is available once the page has completed loading. Listen for the contentload event and then call the method.

The guest will be able to send replies to the embedder by posting message to event.source on the message event it receives.

This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a message event listener to its own frame.

+ * @param message Message object to send to the guest. * @param {string} targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched. */ postMessage(message: any, targetOrigin: string): void; @@ -5118,7 +6463,11 @@ declare namespace chrome { deny(): void; } - /**

Describes a rectangle in screen coordinates.

The containment semantics are array-like; that is, the coordinate (left, top) is considered to be contained by the rectangle, but the coordinate (left + width, top) is not.

*/ + /** + * Fescribes a rectangle in screen coordinates. + * The containment semantics are array-like; that is, the coordinate (left, top) is considered to be contained by the rectangle, + * but the coordinate (left + width, top) is not. + **/ interface SelectionRect { /** @@ -5141,388 +6490,39 @@ declare namespace chrome { */ height: number } - /**Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts.

To illustrate how usage differs from the extensions webRequest API, consider the following example code which blocks any guest requests for URLs which match *://www.evil.com/*:

webview.request.onBeforeRequest.addListener(
-          function(details) { return {cancel: true}; },
-          {urls: ["*://www.evil.com/*"]},
-          ["blocking"]);

Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events. See declarativeWebRequest for API details.

Note that conditions and actions for declarative webview webRequests should be instantiated from their chrome.webViewRequest.* counterparts. The following example code declaratively blocks all requests to "example.com" on the webview myWebview:

var rule = {
-          conditions: [
-            new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } })
-          ],
-          actions: [ new chrome.webViewRequest.CancelRequest() ]
-        };
-        myWebview.request.onRequest.addRules([rule]);
*/ + /** + * @description Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts.

To illustrate how usage differs from the extensions webRequest API, consider the following example code which blocks any guest requests for URLs which match *://www.evil.com/*:

webview.request.onBeforeRequest.addListener(
+         * @example function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
+         * @description Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
+         * @see http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest
+         * @description Note that conditions and actions for declarative webview webRequests should be instantiated from their chrome.webViewRequest.* counterparts. The following example code declaratively blocks all requests to 'example.com' on the webview myWebview:
+         * @example var rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
+         **/
         interface WebRequestEventInterface {
         }
         /**
         * Defines the how zooming is handled in the webview.
         * Enum values:
-        * "per-origin"
+        * 'per-origin'
         * * Zoom changes will persist in the zoomed page's origin, i.e. all other webviews in the same partition that are navigated to that same origin will be zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they will all be zoomed to the same zoom factor.
-        * "per-view"
+        * 'per-view'
         * * Zoom changes only take effect in this webview, and zoom changes in other webviews will not affect the zooming of this webview. Also, per-view zoom changes are reset on navigation; navigating a webview will always load pages with their per-origin zoom factors (within the scope of the partition).
-        * "disabled"
+        * 'disabled'
         * * Disables all zooming in the webview. The content will revert to the default zoom level, and all attempted zoom changes will be ignored. */
-        export type ZoomMode = "per-origin" | "per-view" | "disabled";
-
-        /**
-        * @description Queries audio state.
-        * @param {any} [object Object]
-         */
-        export function getAudioState(callback: (audible: boolean) => void): void;
-
-        /**
-        * @description Sets audio mute state of the webview.
-        * @param {boolean} mute Mute audio value
-         */
-        export function setAudioMuted(mute: boolean): void;
-
-        /**
-        * @description Queries whether audio is muted.
-        * @param {any} [object Object]
-         */
-        export function isAudioMuted(callback: (muted: boolean) => void): void;
-
-        /**
-         * @description Captures the visible region of the webview.
-         * @param {(dataUrl: string) => void} callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display.
-         */
-        export function captureVisibleRegion(callback: (dataUrl: string) => void): void;
-        /**
-         * @description Captures the visible region of the webview.
-         * @param {*} options
-         * @param {(dataUrl: string) => void} callback
-         */
-        export function captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void;
-
-        /**
-        * @description 

Adds content script injection rules to the webview. When the webview navigates to a page matching one or more rules, the associated scripts will be injected. You can programmatically add rules or update existing rules.

The following example adds two rules to the webview: 'myRule' and 'anotherRule'.

webview.addContentScripts([
-          {
-            name: 'myRule',
-            matches: ['http://www.foo.com/*'],
-            css: { files: ['mystyles.css'] },
-            js: { files: ['jquery.js', 'myscript.js'] },
-            run_at: 'document_start'
-          },
-          {
-            name: 'anotherRule',
-            matches: ['http://www.bar.com/*'],
-            js: { code: "document.body.style.backgroundColor = 'red';" },
-            run_at: 'document_end'
-          }]);
-         ...
-
-        // Navigates webview.
-        webview.src = 'http://www.foo.com';

You can defer addContentScripts call until you needs to inject scripts.

The following example shows how to overwrite an existing rule.

webview.addContentScripts([{
-            name: 'rule',
-            matches: ['http://www.foo.com/*'],
-            js: { files: ['scriptA.js'] },
-            run_at: 'document_start'}]);
-
-        // Do something.
-        webview.src = 'http://www.foo.com/*';
-         ...
-        // Overwrite 'rule' defined before.
-        webview.addContentScripts([{
-            name: 'rule',
-            matches: ['http://www.bar.com/*'],
-            js: { files: ['scriptB.js'] },
-            run_at: 'document_end'}]);

If webview has been naviagted to the origin (e.g., foo.com) and calls webview.addContentScripts to add 'myRule', you need to wait for next navigation to make the scripts injected. If you want immediate injection, executeScript will do the right thing.

Rules are preserved even if the guest process crashes or is killed or even if the webview is reparented.

Refer to the content scripts documentation for more details.

- * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. - */ - export function addContentScripts(contentScriptList: ContentScriptDetails[]): void; - - /** - * @description Navigates backward one history entry if possible. Equivalent to go(-1). - * @param {(success: boolean) => void} [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. - */ - export function back(callback?: (success: boolean) => void): void; - - /** - * @description Indicates whether or not it is possible to navigate backward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. - */ - export function canGoBack(): void; - - /** - * @description Indicates whether or not it is possible to navigate forward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. - */ - export function canGoForward(): void; - - /** - * @description

Clears browsing data for the webview partition.

- * @param {any} options Options determining which data to clear. - * @param {any} types The types of data to be cleared. - * @param {any} [object Object] - */ - export function clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; - - /** - * @description

Injects JavaScript code into the guest page.

The following sample code uses script injection to set the guest page's background color to red:

webview.executeScript({ code: "document.body.style.backgroundColor = 'red'" });
- * @param {any} details Details of the script to run. - * @param {any} [object Object] - */ - export function executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; - - /** - * @description Initiates a find-in-page request. - * @param {string} searchText The string to find in the page. - * @param {any} options Options for the find request. - * @param {any} [object Object] - */ - export function find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; - - /** - * @description Navigates forward one history entry if possible. Equivalent to go(1). - * @param {any} [object Object] - */ - export function forward(callback?: (success: boolean) => void): void; - - /** - * @description Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. - */ - export function getProcessId(): void; - - /** - * @description Returns the user agent string used by the webview for guest page requests. - */ - export function getUserAgent(): void; - - /** - * @description Gets the current zoom factor. - * @param {any} [object Object] - */ - export function getZoom(callback: (zoomFactor: number) => void): void; - - /** - * @description Gets the current zoom mode. - * @param {any} [object Object] - */ - export function getZoomMode(callback: (ZoomMode: any) => void): void; - - /** - * @description Navigates to a history entry using a history index relative to the current navigation. If the requested navigation is impossible, this method has no effect. - * @param {number} relativeIndex Relative history index to which the webview should be navigated. For example, a value of 2 will navigate forward 2 history entries if possible; a value of -3 will navigate backward 3 entries. - * @param {any} [object Object] - */ - export function go(relativeIndex: number, callback?: (success: boolean) => void): void; - - /** - * @description Injects CSS into the guest page. - * @param {any} details Details of the CSS to insert. - * @param {any} [object Object] - */ - export function insertCSS(details: InjectDetails, callback?: () => void): void; - - /** - * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). - */ - export function isUserAgentOverridden(): void; - - /** - * @description Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. - */ - export function print(): void; - - /** - * @description Reloads the current top-level page. - */ - export function reload(): void; - - /** - * @description

Removes content scripts from a webview.

The following example removes "myRule" which was added before.

webview.removeContentScripts(['myRule']);

You can remove all the rules by calling:

webview.removeContentScripts();
- * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. - */ - export function removeContentScripts(scriptNameList?: any[]): void; - - /** - * @description Override the user agent string used by the webview for guest page requests. - * @param {string} userAgent The user agent string to use. - */ - export function setUserAgentOverride(userAgent: string): void; - - /** - * @description Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see $(ref:webviewTag.ZoomMode)). - * @param {number} zoomFactor The new zoom factor. - * @param {any} [object Object] - */ - export function setZoom(zoomFactor: number, callback?: () => void): void; - - /** - * @description Sets the zoom mode of the webview. - * @param {any} ZoomMode Defines how zooming is handled in the webview. - * @param {any} [object Object] - */ - export function setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; - - /** - * @description Stops loading the current webview navigation if in progress. - */ - export function stop(): void; - - /** - * @description Ends the current find session (clearing all highlighting) and cancels all find requests in progress. - * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. - */ - export function stopFinding(action?: string): void; - - /** - * @description Loads a data URL with a specified base URL used for relative links. Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. - * @param {string} dataUrl The data URL to load. - * @param {string} baseUrl The base URL that will be used for relative links. - * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). - */ - export function loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; - - /** - * @description Forcibly kills the guest web page's renderer process. This may affect multiple webview tags in the current app if they share the same process, but it will not affect webview tags in other apps. - */ - export function terminate(): void; - - /** - * @description Fired when the guest window attempts to close itself.

The following example code navigates the webview to about:blank when the guest attempts to close itself.

webview.addEventListener('close', function() {
-          webview.src = 'about:blank';
-        });
- */ - - export function close(event: chrome.events.Event): void; - - /** - * @description Fired when the guest window logs a console message.

The following example code forwards all log messages to the embedder's console without regard for log level or other properties.

webview.addEventListener('consolemessage', function(e) {
-          console.log('Guest page logged a message: ', e.message);
-        });
- * @param {any} [object Object] - */ - - export var consolemessage: chrome.events.Event; - - /** - * @description Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads.

The following example code modifies the default font size of the guest's body element after the page loads:

webview.addEventListener('contentload', function() {
-          webview.executeScript({ code: 'document.body.style.fontSize = "42px"' });
-        });
- */ - - export var contentload: (event: chrome.events.Event) => void; - - /** - * @description Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

- * @param {any} [object Object] - */ - - export var dialog: chrome.events.Event; - - /** - * @description Fired when the process rendering the guest web content has exited.

The following example code will show a farewell message whenever the guest page crashes:

webview.addEventListener('exit', function(e) {
-          if (e.reason === 'crash') {
-            webview.src = 'data:text/plain,Goodbye, world!';
-          }
-        });
- * @param {any} [object Object] - */ - - export var exit: chrome.events.Event; - - /** - * @description Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. - * @param {any} [object Object] - */ - - export var findupdate: chrome.events.Event; - - /** - * @description Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented.

Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted.

Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'.

- * @param {any} [object Object] - */ - - export var loadabort: chrome.events.Event; - - /** - * @description Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. - * @param {any} [object Object] - */ - - export var loadcommit: chrome.events.Event; - - /** - * @description Fired when a top-level load request has redirected to a different URL. - * @param {any} [object Object] - */ - - export var loadredirect: chrome.events.Event; - - /** - * @description Fired when a load has begun. - * @param {any} [object Object] - */ - - export var loadstart: chrome.events.Event; - - /** - * @description Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.

Note: When a committed load is aborted, a loadstop event will eventually follow a loadabort event, even if all committed loads since the last loadstop event (if any) were aborted.

- */ - - export function loadstop(event: chrome.events.Event): void; - - /** - * @description Fired when the guest page attempts to open a new browser window.

The following example code will create and navigate a new webview in the embedder for each requested new window:

webview.addEventListener('newwindow', function(e) {
-          var newWebview = document.createElement('webview');
-          document.body.appendChild(newWebview);
-          e.window.attach(newWebview);
-        });
- * @param {any} [object Object] - */ - - export var newwindow: chrome.events.Event; - - /** - * @description Fired when the guest page needs to request special permission from the embedder.

The following example code will grant the guest page access to the webkitGetUserMedia API. Note that an app using this example code must itself specify audioCapture and/or videoCapture manifest permissions:

webview.addEventListener('permissionrequest', function(e) {
-          if (e.permission === 'media') {
-            e.request.allow();
-          }
-        });
- * @param {any} [object Object] - */ - - export var permissionrequest: chrome.events.Event; - - /** - * @description Fired when the process rendering the guest web content has become responsive again after being unresponsive.

The following example code will fade the webview element in or out as it becomes responsive or unresponsive:

webview.style.webkitTransition = 'opacity 250ms';
-        webview.addEventListener('unresponsive', function() {
-          webview.style.opacity = '0.5';
-        });
-        webview.addEventListener('responsive', function() {
-          webview.style.opacity = '1';
-        });
- * @param {any} [object Object] - */ - - export var responsive: chrome.events.Event; - - /** - * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. - * @param {any} [object Object] - */ - - export var sizechanged: chrome.events.Event; - - /** - * @description Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. - * @param {any} [object Object] - */ - - export var unresponsive: chrome.events.Event; - - /** - * @description Fired when the page's zoom changes. - * @param {any} [object Object] - */ - - export var zoomchange: chrome.events.Event; - /**IConsolemessage (Auto generated interface) */ - interface IConsolemessage { + export type ZoomMode = 'per-origin' | 'per-view' | 'disabled'; + + export enum ConsoleMessageLevel { + LOG_VERBOSE = -1, + LOG_INFO = 0, + LOG_WARNING = 1, + LOG_ERROR = 2 + } + interface IConsoleMessage { /** * @description The severity level of the log message. Ranges from -1 to 2. LOG_VERBOSE (console.debug) = -1, LOG_INFO (console.log, console.info) = 0, LOG_WARNING (console.warn) = 1, LOG_ERROR (console.error) = 2. */ - level: number + level: ConsoleMessageLevel; /** * @description The logged message contents. @@ -5539,7 +6539,6 @@ declare namespace chrome { */ sourceId: string } - /**IDialog (Auto generated interface) */ interface IDialog { /** @@ -5557,7 +6556,6 @@ declare namespace chrome { */ dialog: DialogController } - /**IExit (Auto generated interface) */ interface IExit { /** @@ -5570,7 +6568,6 @@ declare namespace chrome { */ reason: 'normal' | 'abnormal' | 'crash' | 'kill' } - /**IFindupdate (Auto generated interface) */ interface IFindupdate { /** @@ -5603,7 +6600,6 @@ declare namespace chrome { */ finalUpdate: string } - /**ILoadabort (Auto generated interface) */ interface ILoadabort { /** @@ -5626,7 +6622,6 @@ declare namespace chrome { */ reason: 'ERR_ABORTED' | 'ERR_INVALID_URL' | 'ERR_DISALLOWED_URL_SCHEME' | 'ERR_BLOCKED_BY_CLIENT' | 'ERR_ADDRESS_UNREACHABLE' | 'ERR_EMPTY_RESPONSE' | 'ERR_FILE_NOT_FOUND' | 'ERR_UNKNOWN_URL_SCHEME' } - /**ILoadcommit (Auto generated interface) */ interface ILoadcommit { /** @@ -5703,7 +6698,6 @@ declare namespace chrome { */ windowOpenDisposition: 'ignore' | 'save_to_disk' | 'current_tab' | 'new_background_tab' | 'new_foreground_tab' | 'new_window' | 'new_popup' } - /**IPermissionrequest (Auto generated interface) */ interface IPermissionrequest { /** @@ -5714,8 +6708,9 @@ declare namespace chrome { /** * @description An object which holds details of the requested permission. Depending on the type of permission requested, this may be a $(ref:webviewTag.MediaPermissionRequest), $(ref:webviewTag.GeolocationPermissionRequest), $(ref:webviewTag.PointerLockPermissionRequest), $(ref:webviewTag.DownloadPermissionRequest), $(ref:webviewTag.LoadPluginPermissionRequest), or $(ref:webviewTag.FullscreenPermissionRequest). */ - request: object + request: GeolocationPermissionRequest | PointerLockPermissionRequest | DownloadPermissionRequest | LoadPluginPermissionRequest | FullscreenPermissionRequest; } + /**IResponsive (Auto generated interface) */ interface IResponsive { diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index f976fc57b4..c0dc6402a6 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,7 +1,7 @@ import runtime = chrome.app.runtime; import cwindow = chrome.app.window; -var createOptions: cwindow.CreateWindowOptions = { +const createOptions: cwindow.CreateWindowOptions = { id: "My Window", bounds: { left: 0, @@ -324,5 +324,40 @@ function testSystemNetwork() { }); } -import webview = chrome.webview; -let element: webview.HTMLWebViewElement; +const gcmMessage = {}; +gcmMessage.data = { + /*goog: 'any', should not be allowed, and it is not :) */ + test: true +}; + +let wve: chrome.webview.HTMLWebViewElement = (document.getElementById('webview')); +wve.name = 'test'; +wve.src = 'https://github.com/DefinitelyTyped'; +wve.allowtransparency = true; +wve.autosize = 'on'; +wve.partition = 'persist:githubwebview'; +wve.addEventListener('close', () => { + return; +}); +wve.addEventListener('consolemessage', (ev) => { + if (ev.level === chrome.webview.ConsoleMessageLevel.LOG_ERROR) { + const msg = ev.message; + } +}); +wve.addEventListener('dialog', (ev) => { + ev.dialog.ok('Hello World!'); +}); +wve.addEventListener('loadstart', (ev) => { + if (ev.isTopLevel) { + return ev.url; + } + return; +}); +wve.addEventListener('zoomchange', (ev) => { + return ev.newZoomFactor || ev.oldZoomFactor; +}); +wve.addEventListener('loadredirect', (ev) => { + return ev.newUrl || ev.oldUrl; +}); + +chrome.bluetoothLowEnergy.connect('1111111', () => { }); diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 0c69727a05..03b70ca459 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -367,9 +367,15 @@ declare namespace cast.framework.events { total?: number, whenSkippable?: number, endedReason?: EndedReason, - breakClipId?: string + breakClipId?: string, + breakId?: string ); + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + /** * The break clip's id. Refer to BreakClip.id */ diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index a75834b0a8..08ce57cf86 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -8,7 +8,8 @@ import { } from "chromecast-caf-receiver/cast.framework.system"; import { RequestEvent, - Event + Event, + BreaksEvent } from "chromecast-caf-receiver/cast.framework.events"; import { QueueBase, @@ -29,12 +30,16 @@ import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; +const breaksEvent = new BreaksEvent('BREAK_STARTED'); +breaksEvent.breakId = 'some-break-id'; +breaksEvent.breakClipId = 'some-break-clip-id'; + const track = new Track(1, "TEXT"); const breakClip = new BreakClip("id"); const adBreak = new Break("id", ["id"], 1); const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); const pManager = new PlayerManager(); -pManager.addEventListener("STALLED", () => {}); +pManager.addEventListener("STALLED", () => { }); const ttManager = new TextTracksManager(); const qManager = new QueueManager(); const qBase = new QueueBase(); @@ -47,10 +52,10 @@ const breakManager: BreakManager = { getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => {}, - setBreakSeekInterceptor: () => {}, - setPlayWatchedBreak: () => {}, - setVastTrackingInterceptor: () => {} + setBreakClipLoadInterceptor: () => { }, + setBreakSeekInterceptor: () => { }, + setPlayWatchedBreak: () => { }, + setVastTrackingInterceptor: () => { } }; const lrd: LoadRequestData = { @@ -103,4 +108,4 @@ const pData: PlayerData = { whenSkippable: 321 }; const binder = new PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => {}); +binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts b/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts new file mode 100644 index 0000000000..c46d48d563 --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts @@ -0,0 +1,33 @@ +const startupConfiguration: any = { camera_position: 'back' }; + +// Some code samples from the wikitude ionic starter +WikitudePlugin.loadARchitectWorld( + success => { + console.log('ARchitect World loaded successfully.'); + }, + fail => { + console.log('Failed to load ARchitect World!'); + }, + 'www/assets/07_3dModels_6_3dModelAtGeoLocation/index.html', + ['geo'], + startupConfiguration +); + +WikitudePlugin.setOnUrlInvokeCallback(url => { + if (url.indexOf('captureScreen') > -1) { + WikitudePlugin.captureScreen( + absoluteFilePath => { + WikitudePlugin.callJavaScript( + `World.testFunction('Screenshot saved at: ${absoluteFilePath}');` + ); + }, + errorMessage => { + console.log(errorMessage); + }, + true, + null + ); + } else { + alert(url + 'not handled'); + } +}); diff --git a/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts b/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts new file mode 100644 index 0000000000..50307d57c8 --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for com.wikitude.phonegap.wikitudeplugin 7.2 +// Project: https://github.com/Wikitude/wikitude-cordova-plugin +// Definitions by: zbarbuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// The following types are taken directly (unmodified) from the wikitude-ionic-3-starter-app +// https://github.com/pbreuss/wikitude-ionic-3-starter-app +// Latest commit at time of writing was 647cd546f6d1805765c4cee725566e246ca6259d + +/** + * Wrapper for the Wikitude SDK Phonegap Plugin - to use with IONIC2 + * (c) 2016 Schneeweis.Technology + */ +interface WikitudePlugin { + isDeviceSupported( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + requiredFeatures: [string] + ): void; + + loadARchitectWorld( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + architectWorldPath: string, + requiredFeatures: [string], + startupConfiguration: JSON | object + ): void; + + close(): void; + + hide(): void; + + show(): void; + + // test type ok? + callJavaScript(js: any): void; + + setOnUrlInvokeCallback(onUrlInvokeCallback: (success: string) => void): void; + + setLocation(latitude: any, longitude: any, altitude: any, accuracy: any): void; + + captureScreen( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + includeWebView: boolean, + imagePathInBundleOrNullForPhotoLibrary: string | null + ): void; + + setErrorHandler(errorHandler: (message: string) => void): void; + + setDeviceSensorsNeedCalibrationHandler( + startCalibrationHandler: (message: string) => void + ): void; + + setDeviceSensorsFinishedCalibrationHandler( + finishedCalibrationHandler: (message: string) => void + ): void; + + setBackButtonCallback(onBackButtonCallback: (message: string) => void): void; + + /* Lifecycle updates */ + + onResume(): void; + onBackButton(): void; + onPause(): void; + + onWikitudeOK(): void; + onWikitudeError(): void; + + _sdkKey: string; + FeatureGeo: string; + Feature2DTracking: string; + CameraPositionUndefined: number; + CameraPositionFront: number; + CameraPositionBack: number; + CameraFocusRangeNone: number; + CameraFocusRangeNear: number; + CameraFocusRangeFar: number; +} + +declare var WikitudePlugin: WikitudePlugin; diff --git a/types/com.wikitude.phonegap.wikitudeplugin/tsconfig.json b/types/com.wikitude.phonegap.wikitudeplugin/tsconfig.json new file mode 100644 index 0000000000..ed0ce7783e --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/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", + "com.wikitude.phonegap.wikitudeplugin-tests.ts" + ] +} diff --git a/types/com.wikitude.phonegap.wikitudeplugin/tslint.json b/types/com.wikitude.phonegap.wikitudeplugin/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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/connect-mongo/tsconfig.json b/types/connect-mongo/tsconfig.json index ca12068b57..c0c9ab3043 100644 --- a/types/connect-mongo/tsconfig.json +++ b/types/connect-mongo/tsconfig.json @@ -7,7 +7,10 @@ "paths": { "mongodb": [ "mongodb/v2" - ] + ], + "mongoose": [ + "mongoose/v4" + ] }, "noImplicitAny": true, "noImplicitThis": true, @@ -25,4 +28,4 @@ "index.d.ts", "connect-mongo-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/cosmiconfig/cosmiconfig-tests.ts b/types/cosmiconfig/cosmiconfig-tests.ts index c477eedb3e..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", { diff --git a/types/cosmiconfig/index.d.ts b/types/cosmiconfig/index.d.ts index 16ba1967f3..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/csso/csso-tests.ts b/types/csso/csso-tests.ts new file mode 100644 index 0000000000..74e0b51dd9 --- /dev/null +++ b/types/csso/csso-tests.ts @@ -0,0 +1,40 @@ +import csso = require('csso'); + +csso.minify('.test { color: #ff0000; }').css; +csso.minify('.test { color: #ff0000; }').map; +csso.minify('.test { color: #ff0000; }', { + sourceMap: true, + filename: '', + debug: true, + beforeCompress: () => {}, + afterCompress: () => {}, + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}); + +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000').css; +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000').map; +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000', { + sourceMap: true, + filename: '', + debug: true, + beforeCompress: () => {}, + afterCompress: () => {}, + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}); + +csso.compress({}).ast; +csso.compress({}, { + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}).ast; diff --git a/types/csso/index.d.ts b/types/csso/index.d.ts new file mode 100644 index 0000000000..f89f395129 --- /dev/null +++ b/types/csso/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for csso 3.5 +// Project: https://github.com/css/csso +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace csso { + interface Result { + /** + * Resulting CSS. + */ + css: string; + /** + * Instance of SourceMapGenerator or null. + */ + map: object | null; + } + + interface CompressOptions { + /** + * Disable or enable a structure optimisations. + * @default true + */ + restructure?: boolean; + /** + * Enables merging of @media rules with the same media query by splitted by other rules. + * The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk. + * @default false + */ + forceMediaMerge?: boolean; + /** + * Transform a copy of input AST if true. Useful in case of AST reuse. + * @default false + */ + clone?: boolean; + /** + * Specify what comments to leave: + * - 'exclamation' or true – leave all exclamation comments + * - 'first-exclamation' – remove every comment except first one + * - false – remove all comments + * @default true + */ + comments?: string | boolean; + /** + * Usage data for advanced optimisations. + */ + usage?: object; + /** + * Function to track every step of transformation. + */ + logger?: () => void; + } + + interface MinifyOptions { + /** + * Generate a source map when true. + * @default false + */ + sourceMap?: boolean; + /** + * Filename of input CSS, uses for source map generation. + * @default '' + */ + filename?: string; + /** + * Output debug information to stderr. + * @default false + */ + debug?: boolean; + /** + * Called right after parse is run. + */ + beforeCompress?: BeforeCompressFn | BeforeCompressFn[]; + /** + * Called right after compress() is run. + */ + afterCompress?: AfterCompressFn | AfterCompressFn[]; + restructure?: boolean; + } + + type BeforeCompressFn = (ast: object, options: CompressOptions) => void; + type AfterCompressFn = (compressResult: string, options: CompressOptions) => void; +} + +interface Csso { + /** + * Minify source CSS passed as String + * @param source + * @param options + */ + minify(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result; + + /** + * The same as minify() but for list of declarations. Usually it's a style attribute value. + * @param source + * @param options + */ + minifyBlock(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result; + + /** + * Does the main task – compress an AST. + */ + compress(ast: object, options?: csso.CompressOptions): { ast: object }; +} + +declare const csso: Csso; +export = csso; diff --git a/types/csso/tsconfig.json b/types/csso/tsconfig.json new file mode 100644 index 0000000000..9ed6695bc9 --- /dev/null +++ b/types/csso/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", + "csso-tests.ts" + ] +} diff --git a/types/csso/tslint.json b/types/csso/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/csso/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 25d6151259..10a38145de 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -1,6 +1,20 @@ 'use strict'; -import cytoscape = require('cytoscape'); +// TODO: document all aliases as aliases, not as duplicates! + +const assert = (tag: boolean) => {}; +const aliases = (...obj: Array<{}>) => {}; + +// 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 +83,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 +122,42 @@ cy.on('zoom', (event) => { cy.nodes('$node > node').style('opacity', 0); } }); +cy.off('zoom'); +// events(cy); - TODO + +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 +167,330 @@ 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.SingularElementReturnValue, + cytoscape.CollectionReturnValue, + cytoscape.NodeSingular, + cytoscape.NodeCollection, + cytoscape.EdgeSingular, + cytoscape.EdgeCollection +]).forEach((elemType) => { + aliases(elemType.clone, elemType.copy); + // events(elemType); - TODO + aliases(elemType.data, elemType.attr); + aliases(elemType.removeData, elemType.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/edges 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..1fcdcb0f08 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,19 +1117,22 @@ 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 CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, CollectionSelection, CollectionStyle, CollectionAnimation, - CollectionComparision, CollectionIteration, - CollectionBuildingUnion, CollectionAlgorithms { } + CollectionComparision, CollectionIteration, + CollectionBuildingFiltering, CollectionAlgorithms { } /** * ele --> Cy.Singular * a collection of a single element (node or edge) + * NB: every singular collection is a general collection too (but not vice versa)! */ - interface Singular extends + interface Singular + extends Collection, SingularGraphManipulation, SingularData, SingularPosition, SingularSelection, SingularStyle, SingularAnimation { } @@ -1127,7 +1147,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 +1156,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1143,25 +1164,24 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends 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 { } + interface EdgeSingular extends Singular, + EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular * a collection of a single node */ - interface NodeSingular extends Singular, + interface NodeSingular extends Singular, NodeSingularMetadata, NodeSingularPosition, NodeSingularCompound { } /** @@ -1172,24 +1192,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 +1227,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 @@ -1229,6 +1253,15 @@ declare namespace cytoscape { on(events: EventNames, selector: string, data: any, handler: EventHandler): void; on(events: EventNames, selector: string, handler: EventHandler): void; on(events: EventNames, handler: EventHandler): void; + bind(events: EventNames, selector: string, data: any, handler: EventHandler): void; + bind(events: EventNames, selector: string, handler: EventHandler): void; + bind(events: EventNames, handler: EventHandler): void; + listen(events: EventNames, selector: string, data: any, handler: EventHandler): void; + listen(events: EventNames, selector: string, handler: EventHandler): void; + listen(events: EventNames, handler: EventHandler): void; + addListener(events: EventNames, selector: string, data: any, handler: EventHandler): void; + addListener(events: EventNames, selector: string, handler: EventHandler): void; + addListener(events: EventNames, handler: EventHandler): void; /** * http://js.cytoscape.org/#eles.promiseOn * alias: pon @@ -1258,11 +1291,15 @@ declare namespace cytoscape { * alias unbind, unlisten, removeListener */ off(events: EventNames, selector?: string, handler?: EventHandler): void; + unbind(events: EventNames, selector?: string, handler?: EventHandler): void; + unlisten(events: EventNames, selector?: string, handler?: EventHandler): void; + removeListener(events: EventNames, selector?: string, handler?: EventHandler): void; /** * http://js.cytoscape.org/#eles.trigger * alias: emit */ trigger(events: EventNames, extra?: string[]): void; + emit(events: EventNames, extra?: string[]): void; } /** @@ -1279,8 +1316,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 +1350,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 +1514,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 +1655,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 +1669,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 +1758,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 +1781,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 +1797,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 +1924,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 +2129,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 +2182,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 +2193,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 +2231,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 +2241,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 +2267,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 +2284,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 +2292,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 +2301,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 +2310,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 +2364,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 +2376,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 +2392,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 +2457,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 +2483,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 +2496,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 +2508,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 +2527,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 +2535,7 @@ declare namespace cytoscape { /** * The element that corresponds to the minimum value. */ - ele: CollectionElements + ele: CollectionArgument }; /** @@ -2321,7 +2549,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 +2557,7 @@ declare namespace cytoscape { /** * The element that corresponds to the maximum value. */ - ele: CollectionElements + ele: CollectionArgument }; } @@ -2351,7 +2579,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 +2590,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 +2600,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 +2726,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 +2734,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. @@ -2493,28 +2762,28 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - outgoers(selector?: Selector): EdgeCollection; + outgoers(selector?: Selector): CollectionReturnValue; /** * Recursively get edges (and their targets) coming out of the nodes in the collection (i.e. the outgoers, the outgoers' outgoers, ...). * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - successors(selector?: Selector): EdgeCollection; + successors(selector?: Selector): CollectionReturnValue; /** * Get edges (and their sources) coming into the nodes in the collection. * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - incomers(selector?: Selector): EdgeCollection; + incomers(selector?: Selector): CollectionReturnValue; /** * Recursively get edges (and their sources) coming into the nodes in the collection (i.e. the incomers, the incomers' incomers, ...). * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - predecessors(selector?: Selector): EdgeCollection; + predecessors(selector?: Selector): CollectionReturnValue; } /** @@ -2537,7 +2806,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 +2821,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 +2837,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 +2865,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 +2883,7 @@ declare namespace cytoscape { interface SearchAStarResult { found: boolean; distance: number; - path: Collection; + path: CollectionReturnValue; } /** @@ -2641,7 +2910,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 +2939,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 +4637,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/dat.gui/index.d.ts b/types/dat.gui/index.d.ts index 967b5ae13b..5c20fd51fe 100644 --- a/types/dat.gui/index.d.ts +++ b/types/dat.gui/index.d.ts @@ -51,8 +51,7 @@ export class GUI { __folders: GUI[]; domElement: HTMLElement; - add(target: Object, propName:string): GUIController; - add(target: Object, propName:string, min: number, max: number): GUIController; + add(target: Object, propName:string, min?: number, max?: number, step?: number): GUIController; add(target: Object, propName:string, status: boolean): GUIController; add(target: Object, propName:string, items:string[]): GUIController; add(target: Object, propName:string, items:number[]): GUIController; @@ -64,6 +63,7 @@ export class GUI { destroy(): void; addFolder(propName:string): GUI; + removeFolder(subFolder:GUI):void; open(): void; close(): void; diff --git a/types/datatables.net-scroller/datatables.net-scroller-tests.ts b/types/datatables.net-scroller/datatables.net-scroller-tests.ts new file mode 100644 index 0000000000..cb93306ba0 --- /dev/null +++ b/types/datatables.net-scroller/datatables.net-scroller-tests.ts @@ -0,0 +1,13 @@ +$(document).ready(() => { + const config: DataTables.Settings = { + // Scroller extension options + scroller: { + trace: true, + rowHeight: 30, + serverWait: 1000, + displayBuffer: 10, + boundaryScale: 0.6, + loadingIndicator: true + } + }; +}); diff --git a/types/datatables.net-scroller/index.d.ts b/types/datatables.net-scroller/index.d.ts new file mode 100644 index 0000000000..fe97507712 --- /dev/null +++ b/types/datatables.net-scroller/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for datatables.net-scroller 1.4 +// Project: https://datatables.net +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// + +declare namespace DataTables { + interface Settings { + /* + * Select extension options + */ + scroller?: boolean | ScrollerSettings; + } + + interface ScrollerSettings { + /* + * Indicate if Scroller show show trace information on the console or not. + */ + trace?: boolean; + + /* + * Scroller will attempt to automatically calculate the height of rows for it's internal + * calculations. However the height that is used can be overridden using this parameter. + */ + rowHeight?: number | string; + + /* + * When using server-side processing, Scroller will wait a small amount of time to allow + * the scrolling to finish before requesting more data from the server. + */ + serverWait?: number; + + /* + * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch + * for scrolling. + */ + displayBuffer?: number; + + /* + * Scroller uses the boundary scaling factor to decide when to redraw the table - which it + * typically does before you reach the end of the currently loaded data set (in order to + * allow the data to look continuous to a user scrolling through the data). + */ + boundaryScale?: number; + + /* + * Show (or not) the loading element in the background of the table. Note that you should + * include the dataTables.scroller.css file for this to be displayed correctly. + */ + loadingIndicator?: boolean; + } + + interface Api { + scroller: ScrollerMethodsModel; + } + + interface ScrollerMethodsModel { + /* + * Calculate and store information about how many rows are to be displayed + * in the scrolling viewport, based on current dimensions in the browser's + * rendering. + */ + measure(redraw?: boolean): Api; + /* + * Get information about current displayed record range. + */ + page(): PageInfo; + /* + * Get Scroller Api + */ + scroller(): ScrollerMethods; + } + + interface ScrollerMethods extends Api { + /* + * Calculate the pixel position from the top of the scrolling container for + * a given row + */ + rowToPixels(rowIdx: number, intParse?: boolean, virtual?: boolean): number; + /* + * Calculate the row number that will be found at the given pixel position + * (y-scroll). + */ + pixelsToRow(pixels: number, intParse?: boolean, virtual?: boolean): number; + scrollToRow(rowIdx: number, animate?: boolean): Api; + } + + /* + * start: {int}, // the 0-indexed record at the top of the viewport + * end: {int}, // the 0-indexed record at the bottom of the viewport + */ + interface PageInfo { + start: number; + end: number; + } + + interface RowMethods { + /** + * Scroll to a row + */ + scrollTo(animate?: boolean): Api; + } +} diff --git a/types/datatables.net-scroller/tsconfig.json b/types/datatables.net-scroller/tsconfig.json new file mode 100644 index 0000000000..29e1854557 --- /dev/null +++ b/types/datatables.net-scroller/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", + "datatables.net-scroller-tests.ts" + ] +} diff --git a/types/datatables.net-scroller/tslint.json b/types/datatables.net-scroller/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/datatables.net-scroller/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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/index.d.ts b/types/ember/index.d.ts index 56a0879ae5..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 diff --git a/types/emoji-regex/emoji-regex-tests.ts b/types/emoji-regex/emoji-regex-tests.ts new file mode 100644 index 0000000000..6d6b0d25d9 --- /dev/null +++ b/types/emoji-regex/emoji-regex-tests.ts @@ -0,0 +1,3 @@ +import emojiRegex from "emoji-regex"; + +emojiRegex(); // $ExpectType RegExp diff --git a/types/emoji-regex/index.d.ts b/types/emoji-regex/index.d.ts new file mode 100644 index 0000000000..edff690dc7 --- /dev/null +++ b/types/emoji-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for emoji-regex 7.0 +// Project: https://github.com/mathiasbynens/emoji-regex +// Definitions by: iKBAHT +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function createRegExp(): RegExp; +export = createRegExp; diff --git a/types/emoji-regex/tsconfig.json b/types/emoji-regex/tsconfig.json new file mode 100644 index 0000000000..1dfdf53dac --- /dev/null +++ b/types/emoji-regex/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "emoji-regex-tests.ts" + ] +} diff --git a/types/emoji-regex/tslint.json b/types/emoji-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/emoji-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ethereum-protocol/ethereum-protocol-tests.ts b/types/ethereum-protocol/ethereum-protocol-tests.ts new file mode 100644 index 0000000000..a30a691e87 --- /dev/null +++ b/types/ethereum-protocol/ethereum-protocol-tests.ts @@ -0,0 +1,4 @@ +import { CallData, BlockParamLiteral } from 'ethereum-protocol'; +BlockParamLiteral.Earliest; +BlockParamLiteral.Latest; +BlockParamLiteral.Pending; diff --git a/types/ethereum-protocol/index.d.ts b/types/ethereum-protocol/index.d.ts new file mode 100644 index 0000000000..9b967cfc83 --- /dev/null +++ b/types/ethereum-protocol/index.d.ts @@ -0,0 +1,293 @@ +// Type definitions for ethereum-protocol 1.0 +// Project: https://www.npmjs.com/package/ethereum-protocol +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import BigNumber from 'bignumber.js'; + +export type JSONRPCErrorCallback = (err: Error | null, result?: JSONRPCResponsePayload) => void; + +/** + * Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library + * Read more about Providers in the 0x wiki. + */ +export interface Provider { + sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; +} + +export type ContractAbi = AbiDefinition[]; + +export type AbiDefinition = FunctionAbi | EventAbi; + +export type FunctionAbi = MethodAbi | ConstructorAbi | FallbackAbi; + +export type ConstructorStateMutability = 'nonpayable' | 'payable'; +export type StateMutability = 'pure' | 'view' | ConstructorStateMutability; + +export enum AbiType { + Function = 'function', + Constructor = 'constructor', + Event = 'event', + Fallback = 'fallback', +} + +export interface MethodAbi { + type: AbiType.Function; + name: string; + inputs: DataItem[]; + outputs: DataItem[]; + constant: boolean; + stateMutability: StateMutability; + payable: boolean; +} + +export interface ConstructorAbi { + type: AbiType.Constructor; + inputs: DataItem[]; + payable: boolean; + stateMutability: ConstructorStateMutability; +} + +export interface FallbackAbi { + type: AbiType.Fallback; + payable: boolean; +} + +export interface EventParameter extends DataItem { + indexed: boolean; +} + +export interface EventAbi { + type: AbiType.Event; + name: string; + inputs: EventParameter[]; + anonymous: boolean; +} + +export interface DataItem { + name: string; + type: string; + components?: DataItem[]; +} + +export enum OpCode { + DelegateCall = 'DELEGATECALL', + Revert = 'REVERT', + Create = 'CREATE', + Stop = 'STOP', + Invalid = 'INVALID', + CallCode = 'CALLCODE', + StaticCall = 'STATICCALL', + Return = 'RETURN', + Call = 'CALL', + SelfDestruct = 'SELFDESTRUCT', +} + +export interface StructLog { + depth: number; + error: string; + gas: number; + gasCost: number; + memory: string[]; + op: OpCode; + pc: number; + stack: string[]; + storage: { [location: string]: string }; +} + +export interface TransactionTrace { + gas: number; + returnValue: any; + structLogs: StructLog[]; +} + +export type Unit = + | 'kwei' + | 'ada' + | 'mwei' + | 'babbage' + | 'gwei' + | 'shannon' + | 'szabo' + | 'finney' + | 'ether' + | 'kether' + | 'grand' + | 'einstein' + | 'mether' + | 'gether' + | 'tether'; + +export interface JSONRPCRequestPayload { + params: any[]; + method: string; + id: number; + jsonrpc: string; +} + +export interface JSONRPCResponsePayload { + result: any; + id: number; + jsonrpc: string; +} + +export interface AbstractBlock { + number: number | null; + hash: string | null; + parentHash: string; + nonce: string | null; + sha3Uncles: string; + logsBloom: string | null; + transactionsRoot: string; + stateRoot: string; + miner: string; + difficulty: BigNumber; + totalDifficulty: BigNumber; + extraData: string; + size: number; + gasLimit: number; + gasUsed: number; + timestamp: number; + uncles: string[]; +} + +export interface BlockWithoutTransactionData extends AbstractBlock { + transactions: string[]; +} + +export interface BlockWithTransactionData extends AbstractBlock { + transactions: Transaction[]; +} + +export interface Transaction { + hash: string; + nonce: number; + blockHash: string | null; + blockNumber: number | null; + transactionIndex: number | null; + from: string; + to: string | null; + value: BigNumber; + gasPrice: BigNumber; + gas: number; + input: string; +} + +export interface CallTxDataBase { + to?: string; + value?: number | string | BigNumber; + gas?: number | string | BigNumber; + gasPrice?: number | string | BigNumber; + data?: string; + nonce?: number; +} + +export interface TxData extends CallTxDataBase { + from: string; +} + +export interface CallData extends CallTxDataBase { + from?: string; +} + +export interface FilterObject { + fromBlock?: number | string; + toBlock?: number | string; + address?: string; + topics?: LogTopic[]; +} + +export type LogTopic = null | string | string[]; + +export interface DecodedLogEntry extends LogEntry { + event: string; + args: A; +} + +export interface DecodedLogEntryEvent extends DecodedLogEntry { + removed: boolean; +} + +export interface LogEntryEvent extends LogEntry { + removed: boolean; +} + +export interface LogEntry { + logIndex: number | null; + transactionIndex: number | null; + transactionHash: string; + blockHash: string | null; + blockNumber: number | null; + address: string; + data: string; + topics: string[]; +} + +export interface TxDataPayable extends TxData { + value?: BigNumber; +} + +export interface TransactionReceipt { + blockHash: string; + blockNumber: number; + transactionHash: string; + transactionIndex: number; + from: string; + to: string; + status: null | string | 0 | 1; + cumulativeGasUsed: number; + gasUsed: number; + contractAddress: string | null; + logs: LogEntry[]; +} + +export type ContractEventArg = string | BigNumber | number | boolean; + +export interface DecodedLogArgs { + [argName: string]: ContractEventArg; +} + +export interface LogWithDecodedArgs extends DecodedLogEntry {} +export type RawLog = LogEntry; + +export enum BlockParamLiteral { + Earliest = 'earliest', + Latest = 'latest', + Pending = 'pending', +} + +export type BlockParam = BlockParamLiteral | number; + +export interface RawLogEntry { + logIndex: string | null; + transactionIndex: string | null; + transactionHash: string; + blockHash: string | null; + blockNumber: string | null; + address: string; + data: string; + topics: string[]; +} + +export enum SolidityTypes { + Address = 'address', + Uint256 = 'uint256', + Uint8 = 'uint8', + Uint = 'uint', +} + +/** + * Contains the logs returned by a TransactionReceipt. We attempt to decode the + * logs using AbiDecoder. If we have the logs corresponding ABI, we decode it, + * otherwise we don't. + */ +export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt { + logs: Array | LogEntry>; +} + +export interface TraceParams { + disableMemory?: boolean; + disableStack?: boolean; + disableStorage?: boolean; +} diff --git a/types/ethereum-protocol/package.json b/types/ethereum-protocol/package.json new file mode 100644 index 0000000000..4eeb6b18c8 --- /dev/null +++ b/types/ethereum-protocol/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "dependencies": { "bignumber.js": "7.2.1" } +} diff --git a/types/ethereum-protocol/tsconfig.json b/types/ethereum-protocol/tsconfig.json new file mode 100644 index 0000000000..5f358a8dec --- /dev/null +++ b/types/ethereum-protocol/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "ethereum-protocol-tests.ts"] +} diff --git a/types/ethereum-protocol/tslint.json b/types/ethereum-protocol/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ethereum-protocol/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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-redis-cache/express-redis-cache-tests.ts b/types/express-redis-cache/express-redis-cache-tests.ts new file mode 100644 index 0000000000..3f8976c812 --- /dev/null +++ b/types/express-redis-cache/express-redis-cache-tests.ts @@ -0,0 +1,105 @@ +import express = require('express'); +import redis = require('redis'); +import expressRedisCache = require('express-redis-cache'); + +const app = express(); +const cache = expressRedisCache(); + +expressRedisCache({ host: 'localhsot', port: 6379, auth_pass: 'passw0rd' }); +expressRedisCache({ client: redis.createClient() }); + +cache.on('error', (error) => { + throw new Error('Cache error!'); +}); + +app.get('/', + cache.route(), // cache entry name is `cache.prefix + "/"` + (req, res, next) => { }); + +app.get('/', + cache.route('home'), // cache entry name is now `cache.prefix + "home"` + (req, res, next) => { }); + +app.get('/', + cache.route({ name: 'home' }), // cache entry name is `cache.prefix + "home"` + (req, res, next) => { }); + +app.get('/user/:userid', + // middleware to define cache name + (req, res, next) => { + // set cache name + res.express_redis_cache_name = 'user-' + req.params.userid; + next(); + }, + // cache middleware + cache.route(), + // content middleware + (req, res) => { + res.render('user'); + } +); + +app.get('/user', + // middleware to decide if using cache + (req, res, next) => { + // Use only cache if user not signed in + res.use_express_redis_cache = !req.signedCookies.user; + next(); + }, + cache.route(), // this will be skipped if user is signed in + (req, res) => { + res.render('user'); + } +); + +// Prefix +expressRedisCache({ prefix: 'test' }); + +// Expiration +expressRedisCache({ expire: 60 }); + +app.get('/index.html', + cache.route({ expire: 5000 }), // cache entry will live 5000 seconds + (req, res) => { } +); + +// You can also use the number sugar syntax +cache.route(5000); +// Or +cache.route('index', 5000); + +app.get('/index.html', + cache.route({ + expire: { + 200: 5000, + '4xx': 10, + 403: 5000, + '5xx': 10, + xxx: 1 + } + }), + (req, res) => { } +); + +cache.get((error, entries) => { + if (error) throw error; + entries.forEach(console.log); +}); + +cache.get('home', (error, entries) => {}); + +cache.add( + 'user:info', + JSON.stringify({ id: 1, email: 'john@doe.com' }), + { expire: 60 * 60 * 24, type: 'json' }, + (error, added) => {} +); + +cache.add( + 'user:info', + JSON.stringify({ id: 1, email: 'john@doe.com' }), + (error, added) => {} +); + +cache.del('home', (error, deleted) => {}); +cache.size((error, bytes) => {}); diff --git a/types/express-redis-cache/index.d.ts b/types/express-redis-cache/index.d.ts new file mode 100644 index 0000000000..ffd8c844a6 --- /dev/null +++ b/types/express-redis-cache/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for express-redis-cache 1.1 +// Project: https://github.com/rv-kip/express-redis-cache +// Definitions by: AJ Livingston +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import events = require('events'); +import express = require('express'); +import redis = require('redis'); + +declare module 'express-serve-static-core' { + interface Response { + express_redis_cache_name?: string; + use_express_redis_cache?: boolean; + } +} + +declare function expressRedisCache(options?: expressRedisCache.Options): expressRedisCache.ExpressRedisCache; +declare namespace expressRedisCache { + class ExpressRedisCache extends events.EventEmitter { + constructor(options?: Options); + static init(options?: Options): ExpressRedisCache; + readonly FOREVER: number; + options: Options; + host: string; + port: string | number; + prefix: string; + auth_pass: string; + connected: boolean; + expire: number; + client: redis.RedisClient; + add(name: string, body: string, options: AddOptions, callback: (error: any, added: Entry) => void): void; + add(name: string, body: string, callback: (error: any, added: Entry) => void): void; + del(name: string, callback: (error: any, deleted: number) => void): void; + get(name: string, callback: (error: any, entries: Entry[]) => void): void; + get(callback: (error: any, entries: Entry[]) => void): void; + route(nameOrOptions: string | RouteOptions, expire?: ExpireOption): express.RequestHandler; + route(expire?: number): express.RequestHandler; + size(callback: (error: any, bytes: number) => void): void; + } + + interface AddOptions { + type?: string; + expire?: number; + } + + interface Entry { + body: string; + touched: number; + expire: number; + type: string; + } + + interface ExpirationConfig { + [statusCode: string]: number; + } + + type ExpireOption = number | ExpirationConfig; + type ExpirationPolicy = (req: express.Request, res: express.Response) => number; + + interface Options { + auth_pass?: string; + client?: redis.RedisClient; + expire?: number; + host?: string; + port?: string | number; + prefix?: string; + } + + interface RouteOptions { + name?: string; + expire?: ExpireOption | ExpirationPolicy; + binary?: boolean; + } +} + +export = expressRedisCache; diff --git a/types/express-redis-cache/tsconfig.json b/types/express-redis-cache/tsconfig.json new file mode 100644 index 0000000000..7884be049e --- /dev/null +++ b/types/express-redis-cache/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-redis-cache-tests.ts" + ] +} diff --git a/types/express-redis-cache/tslint.json b/types/express-redis-cache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-redis-cache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/ffi/index.d.ts b/types/ffi/index.d.ts index 76e197e841..cf562cea06 100644 --- a/types/ffi/index.d.ts +++ b/types/ffi/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for node-ffi 0.1 +// Type definitions for node-ffi 0.2 // Project: https://github.com/rbranson/node-ffi -// Definitions by: Paul Loyd +// Definitions by: Paul Loyd , Waiting Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -135,12 +135,13 @@ export const DynamicLibrary: { * The function pointer may be used in other C functions that * accept C callback functions. */ -export const Callback: { +export interface Callback { new (retType: any, argTypes: any[], abi: number, fn: any): Buffer; new (retType: any, argTypes: any[], fn: any): Buffer; (retType: any, argTypes: any[], abi: number, fn: any): Buffer; (retType: any, argTypes: any[], fn: any): Buffer; -}; +} +export const Callback: Callback; export const ffiType: { /** Get a `ffi_type *` Buffer appropriate for the given type. */ 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..a8004536e2 --- /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 Socket 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..f558303870 --- /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 协议处理,模块别名:https + * @detail + */ +declare module "http" { + + + module http { + + + + /** + * + * @brief 创建一个 http 请求对象,参见 HttpRequest + * + * + */ + export class Request extends Class_HttpRequest {} + + + /** + * + * @brief 创建一个 http 响应对象,参见 HttpResponse + * + * + */ + export class Response extends Class_HttpResponse {} + + + /** + * + * @brief 创建一个 http cookie 对象,参见 HttpCookie + * + * + */ + export class Cookie extends Class_HttpCookie {} + + + /** + * + * @brief 创建一个 http 服务器,参见 HttpServer + * + * + */ + export class Server extends Class_HttpServer {} + + + /** + * + * @brief 创建一个 http 客户端,参见 HttpClient + * + * + */ + export class Client extends Class_HttpClient {} + + + /** + * + * @brief 创建一个 https 服务器,参见 HttpsServer + * + * + */ + export class HttpsServer extends Class_HttpsServer {} + + + /** + * + * @brief 创建一个 http 协议处理器对象,参见 HttpHandler + * + * + */ + export class Handler 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..f9d9c222c9 --- /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 Url 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..6fbdabd87c --- /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 模块,模块别名: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 Socket extends Class_SslSocket {} + + + /** + * + * @brief 创建一个 SslHandler 对象,参见 SslHandler + * + * + */ + export class Handler extends Class_SslHandler {} + + + /** + * + * @brief 创建一个 SslServer 对象,参见 SslServer + * + * + */ + export class Server 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..78ab282d97 --- /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 Message extends Class_WebSocketMessage {} + + + /** + * + * @brief WebSocket 对象,参见 WebSocket + * + * + */ + export class Socket 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..5526a84e5c --- /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 Document 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..e6ef8fde76 --- /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 Socket 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..0b4ef29975 --- /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: richardo2016 +// 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/gramps__rest-helpers/gramps__rest-helpers-tests.ts b/types/gramps__rest-helpers/gramps__rest-helpers-tests.ts new file mode 100644 index 0000000000..cbb74725ca --- /dev/null +++ b/types/gramps__rest-helpers/gramps__rest-helpers-tests.ts @@ -0,0 +1,16 @@ +import { GraphQLConnector, GraphQLModel } from '@gramps/rest-helpers'; + +const myConnector = new GraphQLConnector(); + +myConnector.apiBaseUri = "some uri"; +myConnector.headers = {}; +myConnector.cacheExpiry = 300; +myConnector.enableCache = true; +myConnector.redis = false; + +myConnector.get("someurl"); +myConnector.post("someendpoint", {}, {}).then(() => {}); +myConnector.put("someendpoint", {}, {}).then(() => {}); +myConnector.delete("someendpoint", {}).then(() => {}); + +const myModel = new GraphQLModel(myConnector); diff --git a/types/gramps__rest-helpers/index.d.ts b/types/gramps__rest-helpers/index.d.ts new file mode 100644 index 0000000000..4fb7e32a27 --- /dev/null +++ b/types/gramps__rest-helpers/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for @gramps/rest-helpers 1.1 +// Project: https://github.com/gramps-graphql/rest-helpers +// Definitions by: Claude Ciocan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export class GraphQLConnector { + constructor(); + + apiBaseUri: string; + headers: object; + request: any; + cacheExpiry: number; + enableCache: boolean; + redis: boolean; + get(endpoint: string): Promise; + post(endpoint: string, body: object, options: object): Promise; + put(endpoint: string, body: object, options: object): Promise; + delete(endpoint: string, options: object): Promise; +} + +export class GraphQLModel { + connector: GraphQLConnector; + + constructor({}); +} diff --git a/types/gramps__rest-helpers/tsconfig.json b/types/gramps__rest-helpers/tsconfig.json new file mode 100644 index 0000000000..03402cad31 --- /dev/null +++ b/types/gramps__rest-helpers/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": { + "@gramps/rest-helpers": [ + "gramps__rest-helpers" + ] + } + }, + "files": [ + "index.d.ts", + "gramps__rest-helpers-tests.ts" + ] +} \ No newline at end of file diff --git a/types/gramps__rest-helpers/tslint.json b/types/gramps__rest-helpers/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gramps__rest-helpers/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file 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/highcharts/index.d.ts b/types/highcharts/index.d.ts index 1434999411..6ef4ef4e2a 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -2354,7 +2354,7 @@ declare namespace Highcharts { * can be customized by defining a new array of items and assigning null to unwanted positions. * @since 2.0 */ - menuItems?: MenuItem[]; + menuItems?: string[] | MenuItem[]; /** * A click handler callback to use on the button directly instead of the popup menu. * @since 2.0 @@ -2661,6 +2661,12 @@ declare namespace Highcharts { * @default ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] */ shortMonths?: string[]; + /** + * Short week days, starting Sunday. If not specified, Highcharts uses the first three letters of the lang.weekdays option. + * @default undefined + * @since 4.2.4 + */ + shortWeekdays?: string[]; /** * The default thousands separator used in the Highcharts.numberFormat method unless otherwise specified in the * function arguments. Since Highcharts 4.1 it defaults to a single space character, which is compatible with ISO diff --git a/types/highcharts/modules/drilldown.d.ts b/types/highcharts/modules/drilldown.d.ts new file mode 100644 index 0000000000..adf9bae6f8 --- /dev/null +++ b/types/highcharts/modules/drilldown.d.ts @@ -0,0 +1,10 @@ +// Type definitions for Highcharts Drilldown 4.2.7 +// Project: http://www.highcharts.com/ +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Static } from "highcharts"; + +declare function HighchartsDrilldown(H: Static): Static; +export = HighchartsDrilldown; +export as namespace HighchartsDrilldown; diff --git a/types/highcharts/test/drilldown.ts b/types/highcharts/test/drilldown.ts new file mode 100644 index 0000000000..f4aa33ca4a --- /dev/null +++ b/types/highcharts/test/drilldown.ts @@ -0,0 +1 @@ +HighchartsDrilldown(Highcharts); diff --git a/types/highcharts/tsconfig.json b/types/highcharts/tsconfig.json index 24b0cf2dd7..e69f0eeb57 100644 --- a/types/highcharts/tsconfig.json +++ b/types/highcharts/tsconfig.json @@ -21,6 +21,7 @@ "index.d.ts", "modules/map/index.d.ts", "modules/boost.d.ts", + "modules/drilldown.d.ts", "modules/exporting.d.ts", "modules/no-data-to-display.d.ts", "modules/offline-exporting.d.ts", @@ -28,6 +29,7 @@ "highstock.d.ts", "js/highcharts/index.d.ts", "test/boost.ts", + "test/drilldown.ts", "test/exporting.ts", "test/highstock.ts", "test/index.ts", diff --git a/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts b/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts new file mode 100644 index 0000000000..17bc81ce1d --- /dev/null +++ b/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts @@ -0,0 +1,21 @@ +import GracefulShutdown = require('http-graceful-shutdown'); +import * as http from "http"; + +const opts: GracefulShutdown.Options = { + signals: "SIGINT SIGTERM", + timeout: 1337, + development: false, + onShutdown: () => { + console.log('fake shutdown handler'); + return Promise.resolve(); + }, + finally: () => { + console.log('fake finally handler'); + } +}; + +const server = http.createServer((req, res) => { + res.end(); +}); + +GracefulShutdown(server, opts); diff --git a/types/http-graceful-shutdown/index.d.ts b/types/http-graceful-shutdown/index.d.ts new file mode 100644 index 0000000000..f8269adea7 --- /dev/null +++ b/types/http-graceful-shutdown/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for http-graceful-shutdown 2.1 +// Project: https://github.com/sebhildebrandt/http-graceful-shutdown +// Definitions by: Dave Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Server } from "http"; + +declare function GracefulShutdown(server: Server, options?: GracefulShutdown.Options): void; + +declare namespace GracefulShutdown { + interface Options { + signals?: string; + timeout?: number; + development?: boolean; + onShutdown?: () => Promise; + finally?: () => void; + } +} + +export = GracefulShutdown; diff --git a/types/http-graceful-shutdown/tsconfig.json b/types/http-graceful-shutdown/tsconfig.json new file mode 100644 index 0000000000..a738609778 --- /dev/null +++ b/types/http-graceful-shutdown/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", + "http-graceful-shutdown-tests.ts" + ] +} diff --git a/types/http-graceful-shutdown/tslint.json b/types/http-graceful-shutdown/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-graceful-shutdown/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/i18next-ko/i18next-ko-tests.ts b/types/i18next-ko/i18next-ko-tests.ts new file mode 100644 index 0000000000..1b8cd90904 --- /dev/null +++ b/types/i18next-ko/i18next-ko-tests.ts @@ -0,0 +1,24 @@ +import * as i18next from 'i18next'; +import * as i18nextko from 'i18next-ko'; +import * as ko from 'knockout'; + +const resourceStore = { + en: { + translation: { + testTranslation: 'Test translation' + } + }, + + de: { + translation: { + testTranslation: 'Test-Übersetzung' + } + } +}; +i18nextko.init(resourceStore, 'en', ko); + +i18nextko.setLanguage('de'); + +i18nextko.i18n; + +i18nextko.t('testTranslation'); diff --git a/types/i18next-ko/index.d.ts b/types/i18next-ko/index.d.ts new file mode 100644 index 0000000000..e9d3c2c639 --- /dev/null +++ b/types/i18next-ko/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for i18next-ko 3.0 +// Project: https://github.com/leMaik/i18next-ko +// Definitions by: Daniel Waxweiler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as i18next from 'i18next'; + +export const i18n: i18next.i18n; + +export function init(resourceStore: i18nextkoResourceStore, language: string, ko: KnockoutStatic): void; + +export function setLanguage(language: string): void; + +export function t(key: string): KnockoutComputed; + +export interface i18nextkoResourceStore { + [language: string]: { + translation: { + [key: string]: string + } + }; +} diff --git a/types/i18next-ko/tsconfig.json b/types/i18next-ko/tsconfig.json new file mode 100644 index 0000000000..9509fa509e --- /dev/null +++ b/types/i18next-ko/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", + "i18next-ko-tests.ts" + ] +} diff --git a/types/i18next-ko/tslint.json b/types/i18next-ko/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/i18next-ko/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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/inboxsdk/tsconfig.json b/types/inboxsdk/tsconfig.json new file mode 100644 index 0000000000..846443ce68 --- /dev/null +++ b/types/inboxsdk/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", + "inboxsdk-tests.ts" + ] +} 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/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/jest/index.d.ts b/types/jest/index.d.ts index 2afe0eb750..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 @@ -12,9 +12,9 @@ // Douglas Duteil // Ahn // Josh Goldberg -// Bradley Ayers // Jeff Lau // Andrew Makarov +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -209,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 */ @@ -227,6 +235,7 @@ declare namespace jest { only: It; skip: It; concurrent: It; + each: Each; } interface Describe { @@ -234,6 +243,7 @@ declare namespace jest { (name: number | string | Function | FunctionLike, fn: EmptyFunction): void; only: Describe; skip: Describe; + each: Each; } interface MatcherUtils { @@ -873,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 e154561c86..7d10075262 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -1,762 +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'), - }); - - expect("foo").toStrictEqual("foo"); - expect({ a: "foo" }).toStrictEqual({ a: "foo" }); - - 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("spy call matchers", () => { - const spy = jest.fn(); +/* Jasmine equality testers */ - expect(spy).lastReturnedWith("foo"); - expect(spy).nthReturnedWith(3, "foo"); - expect(spy).toHaveBeenCalled(); - expect(spy).toHaveBeenCalledTimes(7); - expect(spy).toHaveBeenCalledWith("foo"); - expect(spy).toHaveBeenLastCalledWith("foo"); - expect(spy).toHaveBeenNthCalledWith(3, "foo"); - expect(spy).toHaveReturned(); - expect(spy).toHaveReturnedTimes(7); - expect(spy).toHaveReturnedWith("foo"); - expect(spy).toHaveLastReturnedWith("foo"); - expect(spy).toHaveNthReturnedWith(3, "foo"); - expect(spy).toReturn(); - expect(spy).toReturnTimes(3); - expect(spy).toReturnWith("foo"); -}); +const equalityTesterObject = (first: {}, second: {}) => false; +const equalityTesterString: jasmine.CustomEqualityTester = (first: string, second: string) => first === second; -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.addCustomEqualityTester(equalityTesterObject); +jasmine.addCustomEqualityTester(equalityTesterObject); - 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 - }; - } - }); - }); -}); - -describe('missing tests', () => { - it('creates closures', () => { - class Closure { - private arg: T; - - 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); }); -describe('toHaveBeenNthCalledWith', () => { - const fn = jest.fn(); +test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + expect(a + b).toBe(expected); + } +); - expect(fn).toHaveBeenNthCalledWith(3, "foo"); +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.fancytree/index.d.ts b/types/jquery.fancytree/index.d.ts index c13cd7f26f..d370b06f4d 100644 --- a/types/jquery.fancytree/index.d.ts +++ b/types/jquery.fancytree/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for jquery.fancytree 2.7.0 +// Type definitions for jquery.fancytree 2.28.2-0 // Project: https://github.com/mar10/fancytree // Definitions by: Peter Palotas // Mahdi Abedi +// Nikolai Ommundsen // Nitecube // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// @@ -95,10 +96,10 @@ declare namespace Fancytree { findNextNode(match: (node: FancytreeNode) => boolean, startNode?: FancytreeNode): FancytreeNode; /** Find all nodes that matches condition. - * + * * @returns array of nodes (may be empty) */ - findAll(match: string|((node: FancytreeNode) => boolean|undefined)): FancytreeNode[]; + findAll(match: string | ((node: FancytreeNode) => boolean | undefined)): FancytreeNode[]; /** Generate INPUT elements that can be submitted with html forms. In selectMode 3 only the topmost selected nodes are considered. */ generateFormElements(selected?: boolean, active?: boolean): void; @@ -315,7 +316,7 @@ declare namespace Fancytree { * @param map callback function(NodeData) that could modify the new node * @returns new node. */ - copyTo(node: FancytreeNode, mode?: string, map?: (node: NodeData) => void) : FancytreeNode; + copyTo(node: FancytreeNode, mode?: string, map?: (node: NodeData) => void): FancytreeNode; /** Count direct and indirect children. * @@ -545,7 +546,7 @@ declare namespace Fancytree { resetLazy(): void; /** Schedule activity for delayed execution (cancel any pending request). scheduleAction('cancel') will only cancel a pending request (if any). */ - scheduleAction(mode: string, ms: number) : void; + scheduleAction(mode: string, ms: number): void; /** * @param effects animation options. @@ -761,7 +762,20 @@ declare namespace Fancytree { /** Make sure that the active node is always visible, i.e. its parents are expanded (default: true). */ activeVisible?: boolean; /** Default options for ajax requests. */ - ajax?: Object; + ajax?: { + /** + * HTTP Method (default: 'GET') + */ + type: string; + /** + * false: Append random '_' argument to the request url to prevent caching. + */ + cache: boolean; + /** + * Default 'json' -> Expect json format and pass json object to callbacks. + */ + dataType: string; + }; /** (default: false) Add WAI-ARIA attributes to markup */ aria?: boolean; /** Activate a node when focused with the keyboard (default: true) */ @@ -771,24 +785,26 @@ declare namespace Fancytree { /** Scroll node into visible area, when focused by keyboard (default: false). */ autoScroll?: boolean; /** Display checkboxes to allow selection (default: false) */ - checkbox?: boolean|string|((event: JQueryEventObject, data: EventData) => boolean); + checkbox?: boolean | string | ((event: JQueryEventObject, data: EventData) => boolean); /** Defines what happens, when the user click a folder node. (default: activate_dblclick_expands) */ clickFolderMode?: FancytreeClickFolderMode; - /** 0..2 (null: use global setting $.ui.fancytree.debugInfo) */ - debugLevel?: number; + /** 0..4 (null: use global setting $.ui.fancytree.debugInfo) */ + debugLevel?: 0 | 1 | 2 | 3 | 4; /** callback(node) is called for new nodes without a key. Must return a new unique key. (default null: generates default keys like that: "_" + counter) */ defaultKey?: (node: FancytreeNode) => string; /** Accept passing ajax data in a property named `d` (default: true). */ enableAspx?: boolean; + /** Enable titles (default: false) */ + enableTitles?: boolean; /** List of active extensions (default: []) */ - extensions?: string[]; + extensions?: Array; /** Set focus when node is checked by a mouse click (default: false) */ focusOnSelect?: boolean; /** Add `id="..."` to node markup (default: true). */ generateIds?: boolean; - /** Display node icons (default: true) */ - icons?: boolean; - /** (default: "ft_") */ + /** Node icon url, if only filename, please use imagePath to set the path */ + icon?: boolean | string; + /** Prefix (default: "ft_") */ idPrefix?: string; /** Path to a folder containing icons (default: null, using 'skin/' subdirectory). */ imagePath?: string; @@ -800,36 +816,227 @@ declare namespace Fancytree { minExpandLevel?: number; /** navigate to next node by typing the first letters (default: false) */ quicksearch?: boolean; + /** Right to left mode (default: false) */ + rtl?: false; /** optional margins for node.scrollIntoView() (default: {top: 0, bottom: 0}) */ - scrollOfs?: Object; + scrollOfs?: { top: number, bottom: number }; /** scrollable container for node.scrollIntoView() (default: $container) */ - scrollParent?: JQuery; + scrollParent?: JQuery | null; /** default: multi_hier */ selectMode?: FancytreeSelectMode; /** Used to Initialize the tree. */ - source?: any; + source?: any[] | any; /** Translation table */ - strings?: Object; + strings?: TranslationTable; /** Add tabindex='0' to container, so tree can be reached using TAB */ tabbable?: boolean; /** Add tabindex='0' to node title span, so it can receive keyboard focus */ titlesTabbable?: boolean; /** Animation options, false:off (default: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }) */ toggleEffect?: JQueryUI.EffectOptions; + /** Tooltips */ + tooltip?: boolean; /** (dynamic Option)Prevent (de-)selection using mouse or keyboard. */ - unselectable?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectable?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); /** (dynamic Option)Ignore this node when calculating the partsel status of parent nodes in selectMode 3 propagation. */ - unselectableIgnore?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectableIgnore?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); /** (dynamic Option)Use this as constant selected value (overriding selectMode 3 propagation). */ - unselectableStatus?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectableStatus?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); + + //////////////// + // EXTENSIONS // + //////////////// + dnd5?: Extensions.DragAndDrop5; + filter?: Extensions.Filter; + table?: Extensions.Table; + + /** Options for misc extensions - see docs for typings */ + [extension: string]: any; } + interface TranslationTable { + /** + * "Loading..." // … would be escaped when escapeTitles is true + */ + loading: string; + /** + * "Load error!" + */ + loadError: string; + /** + * "More..." + */ + moreData: string; + /** + * "No data." + */ + noData: string; + } + + namespace Extensions { + interface List { + dnd5?: DragAndDrop5; + filter?: Filter; + table?: Table; + [extension: string]: any; + } + + interface DragAndDrop5 { + /** + * Expand nodes after n milliseconds of hovering. + */ + autoExpandMS?: number; + /** + * Absolute position offset for .fancytree-drop-marker + */ + dropMarkerOffsetX?: number; + /** + * Additional offset for drop-marker with hitMode = "before"/"after" + */ + dropMarkerInsertOffsetX?: number; + /** + * true: Drag multiple (i.e. selected) nodes. + */ + multiSource?: boolean; + /** + * Prevent dropping nodes from different Fancytrees + */ + preventForeignNodes?: boolean; + /** + * Prevent dropping items other than Fancytree nodes + */ + preventNonNodes?: boolean; + /** + * Prevent dropping nodes on own descendants + */ + preventRecursiveMoves?: boolean; + /** + * Prevent dropping nodes 'before self', etc. + */ + preventVoidMoves?: boolean; + /** + * Enable auto-scrolling while dragging + */ + scroll?: boolean; + /** + * Active top/bottom margin in pixel + */ + scrollSensitivity?: number; + /** + * Pixel per event + */ + scrollSpeed?: number; + /** + * Allow dragging of nodes to different IE windows, default: false + */ + setTextTypeJson?: boolean; + /** + * Callback(sourceNode, data), return true, to enable dnd drag + */ + dragStart?: (sourceNode: FancytreeNode, data: any) => void; + dragDrag?: (sourceNode: FancytreeNode, data: any) => void; + dragEnd?: (sourceNode: FancytreeNode, data: any) => void; + /** + * Callback(targetNode, data), return true, to enable dnd drop + */ + dragEnter?: (targetNode: FancytreeNode, data: any) => void; + /** + * Events (drag over) + */ + dragOver?: (targetNode: FancytreeNode, data: any) => void; + /** + * Callback(targetNode, data), return false to prevent autoExpand + */ + dragExpand?: (targetNode: FancytreeNode, data: any) => void; + /** + * Events (drag drop) + */ + dragDrop?: (node: FancytreeNode, data: any) => void; + dragLeave?: (targetNode: FancytreeNode, data: any) => void; + /** + * Support misc options + */ + [key: string]: any; + } + /** + * Define filter-extension options + */ + interface Filter { + /** + * Re-apply last filter if lazy data is loaded + */ + autoApply: boolean; + /** + * Expand all branches that contain matches while filtered + */ + autoExpand: boolean; + /** + * Show a badge with number of matching child nodes near parent icons + */ + counter: boolean; + /** + * Match single characters in order, e.g. 'fb' will match 'FooBar' + */ + fuzzy: boolean; + /** + * Hide counter badge if parent is expanded + */ + hideExpandedCounter: boolean; + /** + * Hide expanders if all child nodes are hidden by filter + */ + hideExpanders: boolean; + /** + * Highlight matches by wrapping inside tags + */ + highlight: boolean; + /** + * Match end nodes only + */ + leavesOnly: boolean; + /** + * Display a 'no data' status node if result is empty + */ + nodata: boolean; + /** + * Grayout unmatched nodes (pass "hide" to remove unmatched node instead); default 'dimm' + */ + mode: 'dimm' | 'string'; + /** + * Support misc options + */ + [key: string]: any; + } + /** + * Define table-extension options + */ + interface Table { + /** + * Render the checkboxes into the this column index (default: nodeColumnIdx) + */ + checkboxColumnIdx: any; + /** + * Indent every node level by 16px; default: 16 + */ + indentation: number; + /** + * Render node expander, icon, and title to this column (default: 0) + */ + nodeColumnIdx: number; + /** + * Support misc options + */ + [key: string]: any; + } + } + + /** Data object passed to FancytreeNode() constructor. Note: typically these attributes are accessed by meber methods, e.g. `node.isExpanded()` and `node.setSelected(false)`. */ interface NodeData { /** node text (may contain HTML tags) */ title: string; - icon?: boolean|string; + icon?: boolean | string; /** unique key for this node (auto-generated if omitted) */ key?: string; /** (reserved) */ diff --git a/types/jquery.fancytree/jquery.fancytree-tests.ts b/types/jquery.fancytree/jquery.fancytree-tests.ts index de1489de42..8f9707597e 100644 --- a/types/jquery.fancytree/jquery.fancytree-tests.ts +++ b/types/jquery.fancytree/jquery.fancytree-tests.ts @@ -1,4 +1,4 @@ -$("#tree").fancytree({ +$("#tree").fancytree({ source: [ { title: "Node 1", key: "1" }, { @@ -12,16 +12,20 @@ $("#tree").fancytree({ { title: "Node 1", key: "1" }, { title: "Folder 2", key: "2", folder: true, children: [ - { title: "Node 2.1", key: "3" }, - { title: "Node 2.2", key: "4" }, - { title: "NOde 2.3", key: "5", icon: "./icon.svg", checkbox: "radio"} - ] + { title: "Node 2.1", key: "3" }, + { title: "Node 2.2", key: "4" }, + { title: "NOde 2.3", key: "5", icon: "./icon.svg", checkbox: "radio" } + ] } ] } ] } ], + extensions: ['dnd5'], + dnd5: { + dragDrag: (node, data) => { } + }, click: (ev: JQueryEventObject, node: Fancytree.EventData) => { return true; }, @@ -51,9 +55,9 @@ $("#tree").fancytree({ //$("#tree").fancytree(); -var tree : Fancytree.Fancytree = $("#tree").fancytree("getTree"); +var tree: Fancytree.Fancytree = $("#tree").fancytree("getTree"); -var activeNode : Fancytree.FancytreeNode = tree.getRootNode(); +var activeNode: Fancytree.FancytreeNode = tree.getRootNode(); // Sort children of active node: activeNode.sortChildren(); @@ -72,15 +76,15 @@ activeNode.addChildren({ tree.loadKeyPath("/1/2", function (node, status) { if (status === "loaded") { console.log("loaded intermiediate node " + node); - } else if (status === "ok") { + } else if (status === "ok") { node.setActive(); } }); -var node = $.ui.fancytree.getNode($("#tree")); +var node = $.ui.fancytree.getNode($("#tree")); alert($.ui.fancytree.version); -var f = $.ui.fancytree.debounce(50, (a : number) => { console.log(a); }, true); -f(2); +var f = $.ui.fancytree.debounce(50, (a: number) => { console.log(a); }, true); +f(2); node = tree.getFirstChild(); node.setExpanded().done(function () { @@ -120,4 +124,4 @@ node.addChildren({ statusNodeType: "loading", unselectableIgnore: true, unselectableStatus: false, -}, 0); \ No newline at end of file +}, 0); 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/json-patch-gen/index.d.ts b/types/json-patch-gen/index.d.ts new file mode 100644 index 0000000000..46b9a7c029 --- /dev/null +++ b/types/json-patch-gen/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for json-patch-gen 1.0 +// Project: https://github.com/gregsexton/json-patch-gen +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare function diff(obj1: object | null, obj2: object | null): diff.JsonPatch[]; + +declare namespace diff { + type PatchOperation = "replace" | "add" | "remove"; + + interface JsonPatch { + op: PatchOperation; + path: string; + value: any; + } +} + +export = diff; +export as namespace diff; diff --git a/types/json-patch-gen/json-patch-gen-tests.ts b/types/json-patch-gen/json-patch-gen-tests.ts new file mode 100644 index 0000000000..6f45195f22 --- /dev/null +++ b/types/json-patch-gen/json-patch-gen-tests.ts @@ -0,0 +1,24 @@ +import diff = require("json-patch-gen"); + +const assertEqual = (a: object, b: object) => JSON.stringify(a) === JSON.stringify(b); +const assertLength = (a: any[], b: number) => a.length === b; + +assertLength(diff({a: "a"}, {a: "a", b: "b"}), 1); +assertEqual(diff({a: "a"}, {a: "a", b: "b"})[0], { + op: "add", + path: "/b", + value: "b" +}); + +assertLength(diff({a: "a", b: "b"}, {a: "a"}), 1); +assertEqual(diff({a: "a", b: "b"}, {a: "a"})[0], { + op: "remove", + path: "/b" +}); + +assertLength(diff({a: "a"}, {a: "b"}), 1); +assertEqual(diff({a: "a"}, {a: "b"})[0], { + op: "replace", + path: "/a", + value: "b" +}); diff --git a/types/json-patch-gen/tsconfig.json b/types/json-patch-gen/tsconfig.json new file mode 100644 index 0000000000..266cb4acae --- /dev/null +++ b/types/json-patch-gen/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", + "json-patch-gen-tests.ts" + ] +} diff --git a/types/json-patch-gen/tslint.json b/types/json-patch-gen/tslint.json new file mode 100644 index 0000000000..ece4c342d1 --- /dev/null +++ b/types/json-patch-gen/tslint.json @@ -0,0 +1,80 @@ +{ + "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-eval": 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 + } +} diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 5076a05231..5ac6943eb4 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -9,22 +9,18 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface KnockoutExtensionFunctions { - [key: string]: any; -} - -interface KnockoutSubscribableFunctions extends KnockoutExtensionFunctions { +interface KnockoutSubscribableFunctions { notifySubscribers(valueToWrite?: T, event?: string): void; } -interface KnockoutComputedFunctions extends KnockoutExtensionFunctions { +interface KnockoutComputedFunctions { } -interface KnockoutObservableFunctions extends KnockoutExtensionFunctions { +interface KnockoutObservableFunctions { equalityComparer(a: any, b: any): boolean; } -interface KnockoutObservableArrayFunctions extends KnockoutExtensionFunctions { +interface KnockoutObservableArrayFunctions { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; slice(start: number, end?: number): T[]; diff --git a/types/koa-bodyparser/index.d.ts b/types/koa-bodyparser/index.d.ts index 256a2fad0a..1664e86cac 100644 --- a/types/koa-bodyparser/index.d.ts +++ b/types/koa-bodyparser/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for koa-bodyparser 4.2 +// Type definitions for koa-bodyparser 5.0 // Project: https://github.com/koajs/bodyparser -// Definitions by: Jerry Chin +// Definitions by: Jerry Chin , Anup Kishore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -18,8 +18,8 @@ import * as Koa from "koa"; declare module "koa" { interface Request { - body: any; - rawBody: any; + body: {} | null | undefined; + rawBody: {} | null | undefined; } } diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 1ade4b135b..193efd25ae 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for koa-router v7.x -// Project: https://github.com/alexmingoia/koa-router/ -// Definitions by: Jerry Chin , Pavel Ivanov +// Project: https://github.com/alexmingoia/koa-router#readme +// Definitions by: Jerry Chin +// Pavel Ivanov +// JounQin // Definitions: https://github.com/hellopao/DefinitelyTyped // TypeScript Version: 2.3 @@ -20,18 +22,7 @@ declare module "koa" { } } -declare module Layer { - - export interface ILayerOptions { - name: string; - sensitive?: boolean; - strict?: boolean; - } - -} - -declare module Router { - +declare namespace Router { export interface IRouterOptions { /** * Prefix for all routes. @@ -85,68 +76,70 @@ declare module Router { methodNotAllowed?: () => any; } -} + export interface ILayerOptions { + name: string; + sensitive?: boolean; + strict?: boolean; + } -declare class ParamName { - asterisk: boolean; - delimiter: string; - name: string; - optional: boolean; - partial: boolean; - pattern: string; - prefix: string; - repeat: string; -} + export class ParamName { + asterisk: boolean; + delimiter: string; + name: string; + optional: boolean; + partial: boolean; + pattern: string; + prefix: string; + repeat: string; + } -declare class Layer { + export class Layer { + opts: ILayerOptions; + name: string; + methods: string[]; + paramNames: ParamName[]; + stack: Router.IMiddleware[]; + regexp: RegExp; + path: string; - opts: Layer.ILayerOptions; - name: string; - methods: string[]; - paramNames: ParamName[]; - stack: Router.IMiddleware[]; - regexp: RegExp; - path: string; + constructor(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: ILayerOptions); + constructor(path: string | RegExp, methods: string[], middleware: Array, opts?: ILayerOptions); - constructor(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); - constructor(path: string | RegExp, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); + /** + * Returns whether request `path` matches route. + */ + match(path: string): boolean; - /** - * Returns whether request `path` matches route. - */ - match(path: string): boolean; + /** + * Returns map of URL parameters for given `path` and `paramNames`. + */ + params(path: string | RegExp, captures: string[], existingParams?: Object): Object; - /** - * Returns map of URL parameters for given `path` and `paramNames`. - */ - params(path: string | RegExp, captures: string[], existingParams?: Object): Object; + /** + * Returns array of regexp url path captures. + */ + captures(path: string): string[]; - /** - * Returns array of regexp url path captures. - */ - captures(path: string): string[]; + /** + * Generate URL for route using given `params`. + */ + url(params: Object): string; - /** - * Generate URL for route using given `params`. - */ - url(params: Object): string; + /** + * Run validations on route named parameters. + */ + param(param: string, fn: Router.IMiddleware): Layer; - /** - * Run validations on route named parameters. - */ - param(param: string, fn: Router.IMiddleware): Layer; - - /** - * Prefix route path. - */ - setPrefix(prefix: string): Layer; + /** + * Prefix route path. + */ + setPrefix(prefix: string): Layer; + } } declare class Router { - params: Object; - - stack: Array; + stack: Array; /** * Create a new router. @@ -249,12 +242,12 @@ declare class Router { /** * Create and register a route. */ - register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Layer; + register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Router.Layer; /** * Lookup route with given `name`. */ - route(name: string): Layer; + route(name: string): Router.Layer; route(name: string): boolean; /** diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index bbd525897c..1325da0de0 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -28,6 +28,9 @@ router.get('user', '/users/:id', function (ctx) { ctx.body = "sdsd"; }); +let layer: Router.Layer +let layerOptions: Router.ILayerOptions + app.use(router.routes()); app.use(router.allowedMethods()); diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts index e7a6c39a7d..ebbfeee8f2 100644 --- a/types/koa-websocket/index.d.ts +++ b/types/koa-websocket/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for koa-websocket 2.1 +// Type definitions for koa-websocket 5.0 // Project: https://github.com/kudos/koa-websocket -// Definitions by: My Self +// Definitions by: Maël Lavault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -21,7 +21,7 @@ declare class KoaWebsocketServer { middleware: Koa.Middleware[]; constructor(app: Koa); - listen(server: http.Server | https.Server): ws.Server; + listen(options: ws.ServerOptions): ws.Server; onConnection(handler: KoaWebsocketConnectionHandler): void; use(middleware: KoaWebsocketMiddleware): this; } 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..75491e24f6 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 0.5 +// Type definitions for luxon 1.2 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang @@ -180,14 +180,14 @@ declare module 'luxon' { zoneName: string; diff( other: DateTime, - unit?: string | string[], + unit?: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; - diffNow(unit?: string | string[], options?: DiffOptions): Duration; - endOf(unit: string): DateTime; + diffNow(unit?: DurationUnit | DurationUnit[], options?: DiffOptions): Duration; + endOf(unit: DurationUnit): DateTime; equals(other: DateTime): boolean; - get(unit: string): number; - hasSame(other: DateTime, unit: string): boolean; + get(unit: keyof DateTime): number; + hasSame(other: DateTime, unit: DurationUnit): boolean; minus(duration: Duration | number | DurationObject): DateTime; plus(duration: Duration | number | DurationObject): DateTime; reconfigure(properties: LocaleOptions): DateTime; @@ -195,7 +195,8 @@ declare module 'luxon' { set(values: DateObjectUnits): DateTime; setLocale(locale: any): DateTime; setZone(zone: string | Zone, options?: ZoneOptions): DateTime; - startOf(unit: string): DateTime; + startOf(unit: DurationUnit): DateTime; + toBSON(): Date; toFormat(format: string, options?: ToFormatOptions): string; toHTTP(): string; toISO(options?: ISOTimeOptions): string; @@ -207,7 +208,9 @@ declare module 'luxon' { toLocal(): DateTime; toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; + toMillis(): number; toObject(options?: { includeConfig?: boolean }): DateObject; + toMillis(): number; toRFC2822(): string; toSQL(options?: Object): string; toSQLDate(): string; @@ -237,6 +240,9 @@ declare module 'luxon' { type DurationObject = DurationObjectUnits & DurationOptions; + type DurationUnit = 'year' | 'years' | 'quarter' | 'quarters' | 'month' | 'months' | 'week' | 'weeks' | 'day' | 'days' + | 'hour' | 'hours' | 'minute' | 'minutes' | 'second' | 'seconds' | 'millisecond' | 'milliseconds'; + class Duration { static fromISO(text: string, options?: DurationOptions): Duration; static fromMillis( @@ -260,16 +266,16 @@ declare module 'luxon' { seconds: number; weeks: number; years: number; - as(unit: string): number; + as(unit: DurationUnit): number; equals(other: Duration): boolean; - get(unit: string): number; + get(unit: DurationUnit): number; minus(duration: Duration | number | DurationObject): Duration; negate(): Duration; normalize(): Duration; plus(duration: Duration | number | DurationObject): Duration; reconfigure(objectPattern: DurationOptions): Duration; set(values: DurationObjectUnits): Duration; - shiftTo(...units: string[]): Duration; + shiftTo(...units: DurationUnit[]): Duration; toFormat(format: string, options?: ToFormatOptions): string; toISO(): string; toJSON(): string; @@ -277,6 +283,7 @@ declare module 'luxon' { includeConfig?: boolean; }): DurationObject; toString(): string; + valueOf(): number; } type EraLength = 'short' | 'long'; @@ -340,23 +347,23 @@ declare module 'luxon' { abutsEnd(other: Interval): boolean; abutsStart(other: Interval): boolean; contains(dateTime: DateTime): boolean; - count(unit?: string): number; + count(unit?: DurationUnit): number; difference(...intervals: Interval[]): Interval[]; divideEqually(numberOfParts?: number): Interval[]; engulfs(other: Interval): boolean; equals(other: Interval): boolean; - hasSame(unit: string): boolean; + hasSame(unit: DurationUnit): boolean; intersection(other: Interval): Interval; isAfter(dateTime: DateTime): boolean; isBefore(dateTime: DateTime): boolean; isEmpty(): boolean; - length(unit?: string): number; + length(unit?: DurationUnit): number; overlaps(other: Interval): boolean; set(values: IntervalObject): Interval; splitAt(...dateTimes: DateTime[]): Interval[]; splitBy(duration: Duration | DurationObject | number): Interval[]; toDuration( - unit: string | string[], + unit: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; toFormat( 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/merge-stream/index.d.ts b/types/merge-stream/index.d.ts index 5a5493b06e..6c6426b902 100644 --- a/types/merge-stream/index.d.ts +++ b/types/merge-stream/index.d.ts @@ -12,6 +12,5 @@ interface IMergedStream extends NodeJS.ReadWriteStream { isEmpty(): boolean; } -declare function merge(streams: T[]): IMergedStream; -declare function merge(...streams: T[]): IMergedStream; +declare function merge(...streams: (T | T[])[]): IMergedStream; export = merge; 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/index.d.ts b/types/mocha/index.d.ts index 1ada77c0a4..5f0aa3baf6 100644 --- a/types/mocha/index.d.ts +++ b/types/mocha/index.d.ts @@ -2846,7 +2846,7 @@ declare global { // #region Deprecations - /** @deprecated use `Mocha.DoneCallback` instead. */ + /** @deprecated use `Mocha.Done` instead. */ type MochaDone = Mocha.Done; /** @deprecated use `Mocha.ReporterConstructor` instead. */ 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..0c46add635 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"]; } /* @@ -791,6 +791,8 @@ declare module "mongoose" { methods: any; /** Object of currently defined statics on this schema. */ statics: any; + /** Object of currently defined query helpers on this schema. */ + query: any; /** The original object passed to the schema constructor */ obj: any; } @@ -854,6 +856,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 +2278,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 +2737,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/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index c680f3c980..a09aefa8e2 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -754,6 +754,8 @@ declare module "mongoose" { methods: any; /** Object of currently defined statics on this schema. */ statics: any; + /** Object of currently defined query helpers on this schema. */ + query: any; /** The original object passed to the schema constructor */ obj: any; } diff --git a/types/mosca/index.d.ts b/types/mosca/index.d.ts new file mode 100644 index 0000000000..178f150d05 --- /dev/null +++ b/types/mosca/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for mosca 2.8 +// Project: https://github.com/mcollina/mosca +// Definitions by: Joao Gabriel Gouveia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class Server { + opts: any; + modernOpts: any; + clients: any; + closed: boolean; + + constructor(opts: any, callback?: () => void); + + on(when: string, callback: (() => void) | ((client: Client) => void) | ((packet: Packet, client: Client) => void)): void; + once(when: string, callback: () => void): void; + toString(): string; + subscribe(topic: string, callback: () => void, done: () => void): void; + publish(message: Message, callback: (obj: any, packet: Packet) => void): void; + authenticate(client: Client, username: string, password: string, + callback: (obj: any, authenticated: boolean) => void): void; + published(packet: Packet, client: Client, callback: (obj: any) => void): void; + authorizePublish(client: Client, topic: string, payload: string, + callback: (obj: any, authorized: boolean) => void): void; + authorizeSubscribe(client: Client, topic: string, callback: (obj: any, authorized: boolean) => void): void; + authorizeForward(client: Client, packet: Packet, callback: (obj: any, authorized: boolean) => void): void; + storePacket(packet: Packet, callback: () => void): void; + deleteOfflinePacket(client: Client, messageId: number, callback: () => void): void; + forwardRetained(pattern: string, client: Client, callback: () => void): void; + restoreClientSubscriptions(client: Client, callback: () => void): void; + forwardOfflinePackets(client: Client, callback: () => void): void; + updateOfflinePacket(client: Client, originMessageId: number, packet: Packet, + callback: (obj: any, packet: Packet) => void): void; + persistClient(client: Client, callback: () => void): void; + close(callback?: () => void): void; + attachHttpServer(server: any, path?: any): void; +} + +export class Client { + id: string; + connection: any; + server: Server; + logger: any; + subscriptions: any; + nextId: number; + inflight: any; + inflightCounter: number; + + constructor(connection: any, server: Server); + + close(callback?: () => void, reason?: string): void; +} + +export class Stats { + maxConnectedClients: number; + connectedClients: number; + lastIntervalConnectedClients: number; + publishedMessages: number; + lastIntervalPublishedMessages: number; + started: Date; + load: any; + + wire(server: Server): void; +} + +export class Authorizer { + users: any; + + addUser(username: string, password: string, authorizePublish: string, + authorizeSubscribe: string, callback: (func: any) => void): void; +} + +export interface Packet { + topic: string; + payload: any; + messageId: string; + qos: number; + retain: boolean; +} + +export interface Message { + topic: string; + payload: any; + qos: number; + retain: boolean; +} diff --git a/types/mosca/mosca-tests.ts b/types/mosca/mosca-tests.ts new file mode 100644 index 0000000000..e03b664b1b --- /dev/null +++ b/types/mosca/mosca-tests.ts @@ -0,0 +1,16 @@ +import { Server, Client, Packet } from 'mosca'; + +const settings = { + port: 1883, + host: '0.0.0.0' +}; + +const server = new Server(settings); + +server.on('ready', () => {}); + +server.on('clientConnected', (client: Client) => {}); + +server.on('clientDisconnected', (client: Client) => {}); + +server.on('published', (packet: Packet, client: Client) => {}); diff --git a/types/mosca/tsconfig.json b/types/mosca/tsconfig.json new file mode 100644 index 0000000000..58b3dcaaf8 --- /dev/null +++ b/types/mosca/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mosca-tests.ts" + ] +} diff --git a/types/mosca/tslint.json b/types/mosca/tslint.json new file mode 100644 index 0000000000..6746359dda --- /dev/null +++ b/types/mosca/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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/mustache/index.d.ts b/types/mustache/index.d.ts index 26a00fc796..2b0ab91cd0 100644 --- a/types/mustache/index.d.ts +++ b/types/mustache/index.d.ts @@ -1,53 +1,247 @@ -// Type definitions for Mustache 0.8.2 +// Type definitions for Mustache 0.8.3 // Project: https://github.com/janl/mustache.js -// Definitions by: Mark Ashley Bell +// Definitions by: Mark Ashley Bell , Manuel Thalmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Provides the functionality to render templates with `{{mustaches}}`. + */ +interface MustacheStatic { + /** + * The name of the module. + */ + name: string; -interface MustacheScanner { + /** + * The version of the module. + */ + version: string; + + /** + * The opening and closing tags to parse. + */ + tags: string; + + /** + * A simple string scanner that is used by the template parser to find tokens in template strings. + */ + Scanner: typeof MustacheScanner + + /** + * Represents a rendering context by wrapping a view object and maintaining a reference to the parent context. + */ + Context: typeof MustacheContext; + + /** + * A Writer knows how to take a stream of tokens and render them to a `string`, given a context. + * + * It also maintains a cache of templates to avoid the need to parse the same template twice. + */ + Writer: typeof MustacheWriter; + + /** + * Escapes HTML-characters. + * + * @param value + * The string to escape. + */ + escape: (value: string) => string; + + /** + * Clears all cached templates in this writer. + */ + clearCache(): void; + + /** + * Parses and caches the given template in the default writer and returns the array of tokens it contains. + * + * Doing this ahead of time avoids the need to parse templates on the fly as they are rendered. + * + * @param template + * The template to parse. + * + * @param tags + * The tags to use. + */ + parse(template: string, tags?: string[]): any; + + /** + * Renders the `template` with the given `view` and `partials` using the default writer. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + render(template: string, view: any | MustacheContext, partials?: any): string; + + /** + * Renders the `template` with the given `view` and `partials` using the default writer. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + to_html(template: string, view: any | MustacheContext, partials?: any, send?: any): any; +} + +/** + * A simple string scanner that is used by the template parser to find tokens in template strings. + */ +declare class MustacheScanner { string: string; tail: string; pos: number; + /** + * Initializes a new instance of the `MustacheScanner` class. + */ + constructor(string: string); + + /** + * Returns `true` if the tail is empty (end of string). + */ eos(): boolean; + + /** + * Tries to match the given regular expression at the current position. + * + * @param re + * The regex-pattern to match. + * + * @returns + * The matched text if it can match, the empty string otherwise. + */ scan(re: RegExp): string; + + /** + * Skips all text until the given regular expression can be matched. + * + * @param re + * The regex-pattern to match. + * + * @returns + * Returns the skipped string, which is the entire tail if no match can be made. + */ scanUntil(re: RegExp): string; } -interface MustacheContext { +/** + * Represents a rendering context by wrapping a view object and maintaining a reference to the parent context. + */ +declare class MustacheContext { view: any; parentContext: MustacheContext; + /** + * Initializes a new instance of the `MustacheContenxt` class. + */ + constructor(view: any, parentContext: MustacheContext); + + /** + * Initializes a new instance of the `MustacheContenxt` class. + */ + constructor(view: any); + + /** + * Creates a new context using the given view with this context as the parent. + * + * @param view + * The view to create the new context with. + */ push(view: any): MustacheContext; + + /** + * Returns the value of the given name in this context, traversing up the context hierarchy if the value is absent in this context's view. + * + * @param name + * The name to look up. + */ lookup(name: string): any; } -interface MustacheWriter { - (view: any): string; +/** + * A Writer knows how to take a stream of tokens and render them to a `string`, given a context. + * + * It also maintains a cache of templates to avoid the need to parse the same template twice. + */ +declare class MustacheWriter { + /** + * Initializes a new instance of the `MustacheWriter` class. + */ + constructor(); + /** + * Clears all cached templates in this writer. + */ clearCache(): void; + + /** + * Parses and caches the given `template` and returns the array of tokens that is generated from the parse. + * + * @param template + * The template to parse. + */ parse(template: string, tags?: any): any; - render(template: string, view: any, partials: any): string; + + /** + * High-level method that is used to render the given `template` with the given `view`. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + render(template: string, view: any | MustacheContext, partials: any): string; + + /** + * Low-level method that renders the given array of `tokens` using the given `context` and `partials`. + * + * @param tokens + * The tokens to render. + * + * @param context + * The context to use for rendering the tokens. + * + * @param partials + * The partials to use for rendering the tokens. + * + * @param originalTemplate + * An object used to extract the portion of the original template that was contained in a higher-order section. + * + * If the template doesn't use higher-order sections, this argument may be omitted. + */ renderTokens(tokens: string[], context: MustacheContext, partials: any, originalTemplate: any): string; } -interface MustacheStatic { - name: string; - version: string; - tags: string; - Scanner: MustacheScanner; - Context: MustacheContext; - Writer: MustacheWriter; - escape: any; - - clearCache(): MustacheWriter; - parse(template: string, tags?: any): any; - render(template: string, view: any, partials?: any): string; - to_html(template: string, view: any, partials?: any, send?: any): any; -} - +/** + * Provides the functionality to render templates with `{{mustaches}}`. + */ declare var Mustache: MustacheStatic; - -declare module 'mustache' { - export = Mustache; -} +export = Mustache; +export as namespace Mustache; diff --git a/types/mustache/mustache-tests.ts b/types/mustache/mustache-tests.ts index ad9c410d76..30c920a30a 100644 --- a/types/mustache/mustache-tests.ts +++ b/types/mustache/mustache-tests.ts @@ -12,3 +12,18 @@ var output2 = Mustache.render(template2, view2); var view3 = { firstName: "John", lastName: "Smith", blogURL: "http://testblog.com" }; var template3 = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; var html = Mustache.to_html(template3, view3); + +var view4 = new class extends Mustache.Context +{ + constructor() + { + super({}); + } + + public lookup(name: string) + { + return name.toUpperCase(); + } +}; +var template4 = "Hello, {{firstName}} {{lastName}}"; +var html4 = Mustache.render(template4, view4); \ No newline at end of file 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..581d6efb52 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 { /** @@ -15,7 +13,7 @@ declare namespace NewRelic { * @param releaseId The ID or version of this release; for example, a version number, build number * from your CI environment, GitHub SHA, GUID, or a hash of the contents. Since New Relic converts this * value into a string, you can also use null or undefined if necessary - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addRelease + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/add-release */ addRelease(releaseName: string, releaseId: string): void; @@ -25,9 +23,9 @@ declare namespace NewRelic { * @param name Name or category of the action. Reports to Insights as the actionName attribute. * @param attributes JSON object with one or more key/value pairs. * The key will report to Insights as its own PageAction attribute with the specified values. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addPageAction + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/add-page-action */ - addPageAction(name: string, attributes: { [key: string]: string }): void; + addPageAction(name: string, attributes: { [key: string]: string | number }): void; /** * Adds a JavaScript object with a custom name, start time, etc. to an in-progress session trace. @@ -53,7 +51,7 @@ declare namespace NewRelic { * * @param Provide a meaningful error message that you can use when analyzing data on * New Relic Browser's JavaScript errors page. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/noticeError + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/notice-error */ noticeError(error: any): void; @@ -65,7 +63,7 @@ declare namespace NewRelic { * @param value Value of the attribute. Appears as the value in the named attribute column in the * PageView event. It will appear as a column in the PageAction event if you are using it. Custom attribute * values cannot be complex objects, only simple types such as strings and numbers. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setCustomAttribute + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-custom-attribute */ setCustomAttribute(name: string, value: string): void; @@ -74,7 +72,7 @@ declare namespace NewRelic { * * @param filterCallback The callback will be called with each error, so it is not * specific to one error. `err` will usually be an error object, but it can be other data types. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setErrorHandler + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-error-handler */ setErrorHandler(filterCallback: (err: any) => boolean): void; @@ -86,7 +84,7 @@ declare namespace NewRelic { * To further group these custom transactions, provide a custom host. Otherwise, the page views will be * assigned the default domain custom.transaction. Segments within the name must be explicitly added to * the Whitelist segments in your URL whitelist settings if they do not already appear. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setPageViewName + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-pageview-name */ setPageViewName(name: string, host?: string): void; @@ -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..b593f335e1 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 ---------------------------------------------- @@ -7,6 +9,7 @@ newrelic.addRelease('checkout page', 'a818994'); // addPageAction() newrelic.addPageAction('copy-text-button', { result: 'success' }); +newrelic.addPageAction('async-action', { duration: 3000 }); // addToTrace() newrelic.addToTrace({ 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..0955877d61 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,35 +1,43 @@ 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; +import { NextContext } from "."; - renderPage( - enhancer?: (page: React.Component) => React.ComponentType - ): { - html?: string; - head: Array>; - errorHtml: string; +export interface RenderPageResponse { + buildManifest: { [key: string]: any }; + chunks: { + names: string[]; + filenames: string[]; }; + html?: string; + head: Array>; + errorHtml: string; +} + +export interface PageProps { + url: string; +} + +export interface AnyPageProps extends PageProps { + [key: string]: any; +} + +export type Enhancer = (page: React.ComponentType

) => React.ComponentType; + +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage(enhancer?: Enhancer): RenderPageResponse; // tslint:disable-line:no-unnecessary-generics } export interface DocumentProps { __NEXT_DATA__?: any; dev?: boolean; - chunks?: string[]; + chunks?: { + names: string[]; + filenames: string[]; + }; html?: string; head?: Array>; errorHtml?: string; @@ -42,5 +50,5 @@ 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: NextDocumentContext): Promise | DocumentProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index fe44537f5f..95395bc2b8 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for next 2.4 +// Type definitions for next 6.0 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Brice BERNARD +// James Hegedus +// Resi Respati // Scott Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -11,7 +13,44 @@ import * as http from "http"; import * as url from "url"; +import { Response as NodeResponse } from "node-fetch"; + declare namespace next { + /** + * Context object used in methods like `getInitialProps()` + * <> + */ + interface NextContext { + /** path section of URL */ + pathname: string; + /** query string section of URL parsed as an object */ + query: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + /** String of the actual path (including the query) shows in the browser */ + asPath: string; + /** HTTP request object (server only) */ + req?: http.IncomingMessage; + /** HTTP response object (server only) */ + res?: http.ServerResponse; + /** Fetch Response object (client only) - from https://developer.mozilla.org/en-US/docs/Web/API/Response */ + jsonPageRes?: NodeResponse; + /** Error object if any error is encountered during the rendering */ + err?: Error; + } + + type NextSFC = NextStatelessComponent; + interface NextStatelessComponent + extends React.StatelessComponent { + getInitialProps?: (ctx: NextContext) => Promise; + } + type UrlLike = url.UrlObject | url.Url; interface ServerConfig { @@ -41,12 +80,12 @@ declare namespace next { handleRequest( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; getRequestHandler(): ( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ) => Promise; prepare(): Promise; close(): Promise; @@ -55,7 +94,7 @@ declare namespace next { run( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; render( @@ -71,7 +110,7 @@ declare namespace next { | string | string[]; }, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; renderError( err: any, @@ -86,12 +125,12 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; render404( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; renderToHTML( req: http.IncomingMessage, @@ -105,7 +144,7 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; renderErrorToHTML( err: any, @@ -120,13 +159,13 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; serveStatic( req: http.IncomingMessage, res: http.ServerResponse, - path: string, + path: string ): Promise; isServeableUrl(path: string): boolean; isInternalUrl(req: http.IncomingMessage): boolean; @@ -135,12 +174,12 @@ declare namespace next { getCompilationError( page: string, req: http.IncomingMessage, - res: http.ServerResponse, + res: http.ServerResponse ): Promise; handleBuildHash( filename: string, hash: string, - res: http.ServerResponse, + res: http.ServerResponse ): void; send404(res: http.ServerResponse): void; } diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 544c29bc7e..4eb24dc3ff 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -8,12 +8,11 @@ export interface EventChangeOptions { [key: string]: any; } +export type PopStateCallback = (state: any) => boolean | undefined; + export type RouterCallback = () => void; export interface RouterProps { - // router properties - readonly components: { - [key: string]: { Component: React.ComponentType; err: any }; - }; + // url property fields readonly pathname: string; readonly route: string; readonly asPath?: string; @@ -27,39 +26,50 @@ export interface RouterProps { | 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 { - router: RouterProps; +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 type ImperativeRouter = RouterProps; -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..f727262b0e 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,79 @@ -import Document, * as document from "next/document"; +import Document, { DocumentProps, Enhancer, Head, Main, NextScript, NextDocumentContext, PageProps } from 'next/document'; import * as React from "react"; -const results = ( +const basicResults = ( - + - - - + +
+ ); + +class MyDoc extends Document { + static async getInitialProps({ renderPage }: NextDocumentContext) { + // without callback + const _page = renderPage(); + + // with callback + const enhancer: Enhancer = (App) => (props) => (); + const { html, head, errorHtml, chunks, buildManifest } = renderPage(enhancer); + + const style = {}; + + return { html, head, errorHtml, chunks, buildManifest, style }; + } + + render() { + return ( + + + My page +