diff --git a/types/angular-agility/tslint.json b/types/angular-agility/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-agility/tslint.json +++ b/types/angular-agility/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-locker/tslint.json b/types/angular-locker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-locker/tslint.json +++ b/types/angular-locker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-odata-resources/tslint.json b/types/angular-odata-resources/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-odata-resources/tslint.json +++ b/types/angular-odata-resources/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-ui-tree/tslint.json b/types/angular-ui-tree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-ui-tree/tslint.json +++ b/types/angular-ui-tree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular/test/jquery3-merging-tests.ts b/types/angular/test/jquery3-merging-tests.ts index 507c58b67e..da61a6f0bc 100644 --- a/types/angular/test/jquery3-merging-tests.ts +++ b/types/angular/test/jquery3-merging-tests.ts @@ -94,8 +94,6 @@ function JQuery() { } function bind() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -104,14 +102,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -120,14 +110,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', false); @@ -139,12 +121,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); @@ -164,27 +140,15 @@ function JQuery() { } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQueryEventObject) { } + function defaultData(this: HTMLElement, event: JQueryEventObject) { } - function defaultContext_customData(this: HTMLElement, event: JQueryEventObject) { } - - function customContext_defaultData(this: I1, event: JQueryEventObject) { } - - function customContext_customData(this: I1, event: JQueryEventObject) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQueryEventObject) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -193,16 +157,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -213,19 +171,15 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -236,8 +190,6 @@ function JQuery() { } function on() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -246,14 +198,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -262,14 +206,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -278,14 +214,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', false); @@ -297,14 +225,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -313,14 +233,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', false); @@ -332,12 +244,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -349,12 +255,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -366,12 +266,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -383,12 +277,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -400,19 +288,11 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } function one() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -421,14 +301,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -437,14 +309,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -453,14 +317,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', false); @@ -472,14 +328,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -488,14 +336,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', false); @@ -507,12 +347,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -524,12 +358,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -541,12 +369,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -558,12 +380,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -575,12 +391,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } diff --git a/types/angularfire/tslint.json b/types/angularfire/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angularfire/tslint.json +++ b/types/angularfire/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index ca36541735..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -92,7 +92,7 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } export const Events: Events; diff --git a/types/bootstrap-slider/bootstrap-slider-tests.ts b/types/bootstrap-slider/bootstrap-slider-tests.ts index 9b2a1a2014..d3ffdeedeb 100644 --- a/types/bootstrap-slider/bootstrap-slider-tests.ts +++ b/types/bootstrap-slider/bootstrap-slider-tests.ts @@ -42,7 +42,7 @@ $(() => { $('#ex7').slider(); - $('#ex7-enabled').click(function(this: HTMLInputElement) { + $('#ex7-enabled').click(function() { if (this.checked) { // With JQuery $('#ex7').slider('enable'); diff --git a/types/bootstrap-slider/tslint.json b/types/bootstrap-slider/tslint.json index f93cf8562a..1c36270d47 100644 --- a/types/bootstrap-slider/tslint.json +++ b/types/bootstrap-slider/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } } diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 8a815bccd5..9744731237 100755 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -322,7 +322,7 @@ export interface TooltipOption { // Events // -------------------------------------------------------------------------------------- -export interface CarouselEventHandler extends JQuery.Event { +export interface CarouselEventHandler extends JQuery.TriggeredEvent { /** * The direction in which the carousel is sliding. */ @@ -339,6 +339,10 @@ export interface CarouselEventHandler extends JQuery.Event extends JQuery.TriggeredEvent { + relatedTarget: HTMLElement; +} + export type AlertEvent = "close.bs.alert" | "closed.bs.alert"; export type CarouselEvent = "slide.bs.carousel" | "slid.bs.carousel"; export type CollapseEvent = "show.bs.collapse" | "shown.bs.collapse" | "hide.bs.collapse" | "hidden.bs.collapse"; @@ -383,9 +387,10 @@ declare global { tooltip(options?: TooltipOption): this; on(events: CarouselEvent, handler: JQuery.EventHandlerBase>): this; + on(events: TapEvent, handler: JQuery.EventHandlerBase>): this; on(events: AlertEvent | CollapseEvent | DropdownEvent | ModalEvent | - PopoverEvent | ScrollspyEvent | TapEvent | TooltipEvent, + PopoverEvent | ScrollspyEvent | TooltipEvent, handler: JQuery.EventHandler): this; } } diff --git a/types/cropperjs/index.d.ts b/types/cropperjs/index.d.ts index 30556e11fc..d444c20705 100644 --- a/types/cropperjs/index.d.ts +++ b/types/cropperjs/index.d.ts @@ -426,8 +426,9 @@ declare class cropperjs { /** * Replace the image's src and rebuild the cropper. * @param url A new image url + * @param hasSameSize If the new image has the same size with the old one, then it will not rebuilt the cropper and only update the urls of all related images. (Default: false) */ - replace(url: string): void; + replace(url: string, hasSameSize?: boolean): void; /** * Enable (unfreeze) the cropper. diff --git a/types/datatables.net/tslint.json b/types/datatables.net/tslint.json index 3db14f85ea..2b6ccb9109 100644 --- a/types/datatables.net/tslint.json +++ b/types/datatables.net/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} \ No newline at end of file diff --git a/types/devexpress-web/v172/tslint.json b/types/devexpress-web/v172/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v172/tslint.json +++ b/types/devexpress-web/v172/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/devexpress-web/v181/tslint.json b/types/devexpress-web/v181/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v181/tslint.json +++ b/types/devexpress-web/v181/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/dialogflow/index.d.ts b/types/dialogflow/index.d.ts index c421c47f68..8329021bb8 100644 --- a/types/dialogflow/index.d.ts +++ b/types/dialogflow/index.d.ts @@ -23,12 +23,7 @@ export namespace v2 { searchAgents( request: SearchAgentRequest, options?: gax.CallOptions, - cb?: ( - err: Error, - agents: Agent[], - arg3: any, - response: any - ) => void + cb?: (err: Error, agents: Agent[], arg3: any, response: any) => void ): Promise; searchAgentsStream( request: SearchAgentRequest, @@ -213,7 +208,28 @@ export namespace v2 { getProjectId(): Promise; getProjectId(callback?: (error: Error, id: string) => string): void; - // TODO: add Session Entity Types service methods + // TODO: add streaming calls + + listSessionEntityTypes( + request: ListSessionEntityTypesRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType[]]>; + getSessionEntityType( + request: GetSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + createSessionEntityType( + request: CreateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + updateSessionEntityType( + request: UpdateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + deleteSessionEntityType( + request: DeleteSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise; } class SessionsClient { @@ -504,6 +520,30 @@ export interface DeleteEntityTypeRequest { name: string; } +export interface ListSessionEntityTypesRequest { + parent: string; + pageSize?: number; +} + +export interface GetSessionEntityTypeRequest { + name: string; +} + +export interface CreateSessionEntityTypeRequest { + parent: string; + sessionEntityType: SessionEntityType; +} + +export interface UpdateSessionEntityTypeRequest { + sessionEntityType: SessionEntityType; + /** @link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto */ + updateMask: any; +} + +export interface DeleteSessionEntityTypeRequest { + name: string; +} + export interface ListIntentsRequest { parent: string; languageCode?: string; diff --git a/types/ej.web.all/tslint.json b/types/ej.web.all/tslint.json index 35e3f27cc8..0615bdcb0e 100644 --- a/types/ej.web.all/tslint.json +++ b/types/ej.web.all/tslint.json @@ -37,6 +37,7 @@ "radix": false, "prefer-for-of": false, "one-line": false, - "no-unnecessary-type-assertion": false + "no-unnecessary-type-assertion": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/expirymanager/expirymanager-tests.ts b/types/expirymanager/expirymanager-tests.ts new file mode 100644 index 0000000000..2206b2673e --- /dev/null +++ b/types/expirymanager/expirymanager-tests.ts @@ -0,0 +1,19 @@ +import { ExpiryManager } from "expirymanager"; + +const expiryManager = new ExpiryManager(); + +const keys = ['1', '2']; + +expiryManager.expire(keys, 1); + +expiryManager.unexpire(keys); + +const expiry: number = expiryManager.getExpiry(keys[0]); + +let expiredKeys = expiryManager.getExpiredKeys(); +expiredKeys = expiryManager.getExpiredKeys(expiryManager.now()); + +expiredKeys = expiryManager.extractExpiredKeys(); +expiredKeys = expiryManager.extractExpiredKeys(expiryManager.now()); + +expiryManager.clear(); diff --git a/types/expirymanager/index.d.ts b/types/expirymanager/index.d.ts new file mode 100644 index 0000000000..c192da7af7 --- /dev/null +++ b/types/expirymanager/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for expirymanager 0.9 +// Project: https://github.com/SocketCluster/expirymanager +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Key = any; +export type Keys = Key[]; + +export class ExpiryManager { + constructor(); + + now(): number; + + expire(keys: Keys, seconds: number): void; + unexpire(keys: Keys): void; + + getExpiry(key: Key): number; + + getKeysByExpiry(expiry: number): Keys; + + getExpiredKeys(time?: number): Keys; + extractExpiredKeys(time?: number): Keys; + + clear(): void; +} diff --git a/types/expirymanager/tsconfig.json b/types/expirymanager/tsconfig.json new file mode 100644 index 0000000000..094c4e8c8d --- /dev/null +++ b/types/expirymanager/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", + "expirymanager-tests.ts" + ] +} diff --git a/types/expirymanager/tslint.json b/types/expirymanager/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/expirymanager/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/feathersjs__feathers/feathersjs__feathers-tests.ts b/types/feathersjs__feathers/feathersjs__feathers-tests.ts index 7d0e961700..bf1cdf8aa7 100644 --- a/types/feathersjs__feathers/feathersjs__feathers-tests.ts +++ b/types/feathersjs__feathers/feathersjs__feathers-tests.ts @@ -9,7 +9,7 @@ interface Services { users: User; } -const app = feathers() as Application; +const app = feathers(); app.service('users').get(0).then(u => { const user: User = u; diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 5948eadc27..4746b29ff7 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -12,7 +12,8 @@ import { EventEmitter } from 'events'; import * as self from '@feathersjs/feathers'; -declare const feathers: (() => Application) & typeof self; +// tslint:disable-next-line no-unnecessary-generics +declare const feathers: (() => Application) & typeof self; export default feathers; export const version: string; diff --git a/types/fleximap/fleximap-tests.ts b/types/fleximap/fleximap-tests.ts new file mode 100644 index 0000000000..4ca0181662 --- /dev/null +++ b/types/fleximap/fleximap-tests.ts @@ -0,0 +1,27 @@ +import { FlexiMap } from "fleximap"; + +let flexiMap = new FlexiMap(); +flexiMap = new FlexiMap({ arr: [] }); +flexiMap = new FlexiMap([{ arr: [] }, { obj: {} }]); + +flexiMap.set('keyA', {arr: [], obj: {}}); +let result = flexiMap.get(['keyA', 'arr']); + +flexiMap.add(['keyB1', 'keyB2', 'keyB3'], 123); +result = flexiMap.get(['keyB1', 'keyB2']); + +const arr = []; +arr[5] = 'Hello world'; + +flexiMap.set(['keyC1', 'keyC2'], arr); +result = flexiMap.get(['keyC1', 'keyC2']); + +flexiMap.set(['itemsA', 0], 'hello'); +flexiMap.set(['itemsA', 2], 'world'); +flexiMap.remove(['itemsA', 0]); + +flexiMap.set(['itemsB', 0], 'a'); +flexiMap.set(['itemsB', 1], 'b'); +flexiMap.set(['itemsB', 2], 'c'); +let splicedItems = flexiMap.splice(['itemsB'], 1, 1); +splicedItems = flexiMap.splice(['itemsB'], 1, 0, 'b2'); diff --git a/types/fleximap/index.d.ts b/types/fleximap/index.d.ts new file mode 100644 index 0000000000..8481134ffe --- /dev/null +++ b/types/fleximap/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for fleximap 0.9 +// Project: https://github.com/SocketCluster/fleximap +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export type KeyChain = any; + +export class FlexiMap { + constructor(object?: any[] | object); + + get(keyChain: KeyChain): any; + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any; + getRaw(keyChain: KeyChain): any; + getAll(): any[] | object; + + count(keyChain: KeyChain): number; + + hasImmediateKey(key: string): boolean; + hasKey(keyChain: KeyChain): boolean; + hasType(keyChain: KeyChain, type: any): boolean; + hasValue(keyChain: KeyChain, value: any): boolean; + hasObject(keyChain: KeyChain, object: object): boolean; + + set(keyChain: KeyChain, value: any): any; + + add(keyChain: KeyChain, value: any): number; + + concat(keyChain: KeyChain, value: any): any; + + remove(keyChain: KeyChain): any; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any[]; + removeAll(): void; + + splice(keyChain: KeyChain, index: number, count: number, ...items: any[]): any[]; + + pop(keyChain: KeyChain): any[]; +} diff --git a/types/fleximap/tsconfig.json b/types/fleximap/tsconfig.json new file mode 100644 index 0000000000..710fa81c96 --- /dev/null +++ b/types/fleximap/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", + "fleximap-tests.ts" + ] +} diff --git a/types/fleximap/tslint.json b/types/fleximap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/fleximap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gridstack/tslint.json b/types/gridstack/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/gridstack/tslint.json +++ b/types/gridstack/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index d6b6fde9be..113c45ef94 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -7,6 +7,7 @@ "no-declare-current-package": false, "no-object-literal-type-assertion": false, "no-self-import": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index 218a7f71cd..2f459c16a7 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,9 +1,9 @@ -import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer"; +import iframeResizer = require("iframe-resizer"); function testOne(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const options: IFrameOptions = {log: true}; - const components: IFrameComponent[] = iframeResizer(options, iframe); + const options: iframeResizer.IFrameOptions = {log: true}; + const components: iframeResizer.IFrameComponent[] = iframeResizer(options, iframe); if (components) { components.forEach(component => console.log(component.iFrameResizer)); } else { @@ -13,7 +13,7 @@ function testOne(): void { function testTwo(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const components: IFrameComponent[] = iframeResizer({ + const components: iframeResizer.IFrameComponent[] = iframeResizer({ initCallback: () => { console.log('Init'); }, diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 6e67a5b592..5f3cb19c7d 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -3,275 +3,315 @@ // Definitions by: Armin Baljic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// tslint:disable-next-line:interface-name -export interface IFrameObject { - close(): void; - moveToAnchor(anchor: string): void; - resize(): void; - sendMessage(message: any, targetOrigin?: string): void; +declare namespace iframeResizer { + // tslint:disable-next-line:interface-name + interface IFrameObject { + close(): void; + + moveToAnchor(anchor: string): void; + + resize(): void; + + sendMessage( + message: any, + targetOrigin?: string + ): void; + } + + // tslint:disable-next-line:interface-name + interface IFrameComponent extends HTMLIFrameElement { + iFrameResizer: IFrameObject; + } + + // tslint:disable-next-line:interface-name + interface IFrameOptions { + /** + * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. + * Disable if using size method with custom dimensions. + */ + autoResize?: boolean; + /** + * Override the body background style in the iFrame. + */ + bodyBackground?: string; + /** + * Override the default body margin 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. + */ + 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 + * provide an array of URLs or disable this option. + */ + checkOrigin?: boolean | string[]; + /** + * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. + */ + inPageLinks?: boolean; + /** + * Height calculation method. + */ + heightCalculationMethod?: HeightCalculationMethod; + /** + * Set iFrame Id + */ + id?: string; + /** + * In browsers that don't support mutationObserver, such as IE10, the library falls back to using + * setInterval, to check for changes to the page size. + */ + interval?: number; + /** + * Setting the log option to true will make the scripts in both the host page and the iFrame output + * everything they do to the JavaScript console so you can see the communication between the two scripts. + */ + log?: boolean; + /** + * Set maximum height of iFrame. + */ + maxHeight?: number; + /** + * Set maximum width of iFrame. + */ + maxWidth?: number; + /** + * Set minimum height of iFrame. + */ + minHeight?: number; + /** + * Set minimum width of iFrame. + */ + minWidth?: number; + /** + * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame + * can be resized independently of the browser window. Selecting this value can cause issues with some + * height calculation methods on mobile devices. + */ + resizeFrom?: 'parent' | 'child'; + /** + * Enable scroll bars in iFrame. + */ + scrolling?: boolean | 'auto'; + /** + * Resize iFrame to content height. + */ + sizeHeight?: boolean; + /** + * Resize iFrame to content width. + */ + sizeWidth?: boolean; + /** + * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. + */ + tolerance?: number; + /** + * Width calculation method. + */ + widthCalculationMethod?: WidthCalculationMethod; + + /** + * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. + */ + closedCallback?(iframeId: string): void; + + /** + * Initial setup callback function. + */ + initCallback?(iframe: IFrameComponent): void; + + /** + * Receive message posted from iFrame with the parentIFrame.sendMessage() method. + */ + messageCallback?(data: IFrameMessageData): void; + + /** + * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width + * and the type of event that triggered the iFrame to resize. + */ + resizedCallback?(data: IFrameResizedData): void; + + /** + * Called before the page is repositioned after a request from the iFrame, due to either an in page link, + * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). + * If this callback function returns false, it will stop the library from repositioning the page, so that + * you can implement your own animated page scrolling instead. + */ + scrollCallback?(data: IFrameScrollData): boolean; + } + + // tslint:disable-next-line:interface-name + interface IFramePageOptions { + /** + * This option allows you to restrict the domain of the parent page, + * to prevent other sites mimicking your parent page. + */ + targetOrigin?: string; + + /** + * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. + */ + messageCallback?(message: any): void; + + /** + * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. + */ + readyCallback?(): void; + + /** + * These option can be used to override the option set in the parent page + */ + heightCalculationMethod?: HeightCalculationMethod | (() => number); + /** + * These option can be used to override the option set in the parent page + */ + widthCalculationMethod?: WidthCalculationMethod | (() => number); + } + + type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; + + type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; + + // tslint:disable-next-line:interface-name + interface IFramePage { + /** + * Turn autoResizing of the iFrame on and off. Returns bool of current state. + */ + autoResize(resize?: boolean): boolean; + + /** + * Remove the iFrame from the parent page. + */ + close(): void; + + /** + * Returns the ID of the iFrame that the page is contained in. + */ + getId(): string; + + /** + * Ask the containing page for its positioning coordinates. + * + * Your callback function will be recalled when the parent page is scrolled or resized. + * + * Pass false to disable the callback. + */ + getPageInfo(callback: ((data: PageInfo) => void) | false): void; + + /** + * Scroll the parent page to the coordinates x and y + */ + scrollTo( + x: number, + y: number + ): void; + + /** + * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. + */ + scrollToOffset( + x: number, + y: number + ): void; + + /** + * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` + * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. + * See the MDN documentation on postMessage for more details. + */ + sendMessage( + message: any, + targetOrigin?: string + ): void; + + /** + * Change the method use to workout the height of the iFrame. + */ + setHeightCalculationMethod(method: HeightCalculationMethod): void; + + /** + * Change the method use to workout the width of the iFrame. + */ + setWidthCalculationMethod(method: WidthCalculationMethod): void; + + /** + * Set default target origin. + */ + setTargetOrigin(targetOrigin: string): void; + + /** + * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to + * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. + */ + size( + customHeight?: string, + customWidth?: string + ): void; + } + + interface PageInfo { + /** + * The height of the iframe in pixels + */ + iframeHeight: number; + /** + * The width of the iframe in pixels + */ + iframeWidth: number; + /** + * The height of the viewport in pixels + */ + clientHeight: number; + /** + * The width of the viewport in pixels + */ + clientWidth: number; + /** + * The number of pixels between the left edge of the containing page and the left edge of the iframe + */ + offsetLeft: number; + /** + * The number of pixels between the top edge of the containing page and the top edge of the iframe + */ + offsetTop: number; + /** + * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport + */ + scrollLeft: number; + /** + * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport + */ + scrollTop: number; + } + + // tslint:disable-next-line:interface-name + interface IFrameResizedData { + iframe: IFrameComponent; + height: number; + width: number; + type: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameMessageData { + iframe: IFrameComponent; + message: any; + } + + // tslint:disable-next-line:interface-name + interface IFrameScrollData { + x: number; + y: number; + } } -// tslint:disable-next-line:interface-name -export interface IFrameComponent extends HTMLIFrameElement { - iFrameResizer: IFrameObject; -} - -// tslint:disable-next-line:interface-name -export interface IFrameOptions { - /** - * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. - * Disable if using size method with custom dimensions. - */ - autoResize?: boolean; - /** - * Override the body background style in the iFrame. - */ - bodyBackground?: string; - /** - * Override the default body margin 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. - */ - 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 - * provide an array of URLs or disable this option. - */ - checkOrigin?: boolean | string[]; - /** - * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. - */ - inPageLinks?: boolean; - /** - * Height calculation method. - */ - heightCalculationMethod?: HeightCalculationMethod; - /** - * Set iFrame Id - */ - id?: string; - /** - * In browsers that don't support mutationObserver, such as IE10, the library falls back to using - * setInterval, to check for changes to the page size. - */ - interval?: number; - /** - * Setting the log option to true will make the scripts in both the host page and the iFrame output - * everything they do to the JavaScript console so you can see the communication between the two scripts. - */ - log?: boolean; - /** - * Set maximum height of iFrame. - */ - maxHeight?: number; - /** - * Set maximum width of iFrame. - */ - maxWidth?: number; - /** - * Set minimum height of iFrame. - */ - minHeight?: number; - /** - * Set minimum width of iFrame. - */ - minWidth?: number; - /** - * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame - * can be resized independently of the browser window. Selecting this value can cause issues with some - * height calculation methods on mobile devices. - */ - resizeFrom?: 'parent' | 'child'; - /** - * Enable scroll bars in iFrame. - */ - scrolling?: boolean | 'auto'; - /** - * Resize iFrame to content height. - */ - sizeHeight?: boolean; - /** - * Resize iFrame to content width. - */ - sizeWidth?: boolean; - /** - * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. - */ - tolerance?: number; - /** - * Width calculation method. - */ - widthCalculationMethod?: WidthCalculationMethod; - /** - * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. - */ - closedCallback?(iframeId: string): void; - /** - * Initial setup callback function. - */ - initCallback?(iframe: IFrameComponent): void; - /** - * Receive message posted from iFrame with the parentIFrame.sendMessage() method. - */ - messageCallback?(data: IFrameMessageData): void; - /** - * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width - * and the type of event that triggered the iFrame to resize. - */ - resizedCallback?(data: IFrameResizedData): void; - /** - * Called before the page is repositioned after a request from the iFrame, due to either an in page link, - * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). - * If this callback function returns false, it will stop the library from repositioning the page, so that - * you can implement your own animated page scrolling instead. - */ - scrollCallback?(data: IFrameScrollData): boolean; -} - -// tslint:disable-next-line:interface-name -export interface IFramePageOptions { - /** - * This option allows you to restrict the domain of the parent page, - * to prevent other sites mimicking your parent page. - */ - targetOrigin?: string; - /** - * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. - */ - messageCallback?(message: any): void; - /** - * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. - */ - readyCallback?(): void; - /** - * These option can be used to override the option set in the parent page - */ - heightCalculationMethod?: HeightCalculationMethod | (() => number); - /** - * These option can be used to override the option set in the parent page - */ - widthCalculationMethod?: WidthCalculationMethod | (() => number); -} - -export type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; - - export type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; - -// tslint:disable-next-line:interface-name -export interface IFramePage { - /** - * Turn autoResizing of the iFrame on and off. Returns bool of current state. - */ - autoResize(resize?: boolean): boolean; - /** - * Remove the iFrame from the parent page. - */ - close(): void; - /** - * Returns the ID of the iFrame that the page is contained in. - */ - getId(): string; - /** - * Ask the containing page for its positioning coordinates. - * - * Your callback function will be recalled when the parent page is scrolled or resized. - * - * Pass false to disable the callback. - */ - getPageInfo(callback: ((data: PageInfo) => void) | false): void; - /** - * Scroll the parent page to the coordinates x and y - */ - scrollTo(x: number, y: number): void; - /** - * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. - */ - scrollToOffset(x: number, y: number): void; - /** - * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` - * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. - * See the MDN documentation on postMessage for more details. - */ - sendMessage(message: any, targetOrigin?: string): void; - /** - * Change the method use to workout the height of the iFrame. - */ - setHeightCalculationMethod(method: HeightCalculationMethod): void; - /** - * Change the method use to workout the width of the iFrame. - */ - setWidthCalculationMethod(method: WidthCalculationMethod): void; - /** - * Set default target origin. - */ - setTargetOrigin(targetOrigin: string): void; - /** - * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to - * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. - */ - size(customHeight?: string, customWidth?: string): void; -} - -export interface PageInfo { - /** - * The height of the iframe in pixels - */ - iframeHeight: number; - /** - * The width of the iframe in pixels - */ - iframeWidth: number; - /** - * The height of the viewport in pixels - */ - clientHeight: number; - /** - * The width of the viewport in pixels - */ - clientWidth: number; - /** - * The number of pixels between the left edge of the containing page and the left edge of the iframe - */ - offsetLeft: number; - /** - * The number of pixels between the top edge of the containing page and the top edge of the iframe - */ - offsetTop: number; - /** - * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport - */ - scrollLeft: number; - /** - * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport - */ - scrollTop: number; -} - -// tslint:disable-next-line:interface-name -export interface IFrameResizedData { - iframe: IFrameComponent; - height: number; - width: number; - type: string; -} - -// tslint:disable-next-line:interface-name -export interface IFrameMessageData { - iframe: IFrameComponent; - message: any; -} - -// tslint:disable-next-line:interface-name -export interface IFrameScrollData { - x: number; - y: number; -} - -export function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; +declare function iframeResizer(options: iframeResizer.IFrameOptions, target: string | HTMLElement): iframeResizer.IFrameComponent[]; +export = iframeResizer; +export as namespace iframeResizer; diff --git a/types/intercom-client/Lead.d.ts b/types/intercom-client/Lead.d.ts new file mode 100644 index 0000000000..aa4e4a2cfa --- /dev/null +++ b/types/intercom-client/Lead.d.ts @@ -0,0 +1,49 @@ +import { Company } from "./Company"; +import { Avatar, LocationData, Segment, SocialProfile, Tag } from './User'; + +export type LeadIdentifier = { "id": string } | { "user_id": string }; + +export interface Lead { + "type": "contact", + readonly "id": string, + "user_id": string | null, + "email": string | null, + "phone": string | null, + "name": string | null, + readonly "updated_at": number, + "last_seen_ip": string | null, + "unsubscribed_from_emails": boolean, + "last_request_at": number | null, + readonly "created_at": number, + "user_agent_data": string | null, + "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[] + }, + "referrer": string | null, +} + +export interface List { + "type": "user.list", + "total_count": number, + "contacts": Lead[], + "pages": { "next"?: string, "page": number, "per_page": number, "total_pages": number } +} diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts index b776165c55..8c81fd989c 100644 --- a/types/intercom-client/index.d.ts +++ b/types/intercom-client/index.d.ts @@ -6,6 +6,7 @@ /// import { List as UserList, User, UserIdentifier } from './User'; +import { List as LeadList, Lead, LeadIdentifier } from './Lead'; import { CompanyIdentifier, List as CompanyList, Company } from './Company'; import { TagIdentifier, List as TagList, Tag, TagOper } from './Tag'; import { List as EventList, Event, ListParam as EventListParam } from './Event'; @@ -33,6 +34,8 @@ export class Client { companies: Companies; tags: Tags; events: Events; + contacts: Leads; + leads: Leads; } export class ApiResponse extends IncomingMessage { @@ -51,17 +54,46 @@ export class Users { find(identifier: UserIdentifier): Promise>; find(identifier: UserIdentifier, cb: callback>): void; - list(): Promise>; - list(cb: callback>): void; + list(): Promise>; + list(cb: callback>): void; listBy(params: {tag_id?: string, segment_id?: string}): Promise>; listBy(params: {tag_id?: string, segment_id?: string}, cb: callback>): void; scroll: Scroll; - archive(): Promise; + archive(identifier: UserIdentifier): Promise>; + archive(identifier: UserIdentifier, cb: callback>): void; + + requestPermanentDeletion(id: string): Promise<{ id: number }>; + requestPermanentDeletion(id: string, cb: callback<{ id: number }>): void; + + requestPermanentDeletionByParams(identifier: UserIdentifier): Promise<{ id: number }>; + requestPermanentDeletionByParams(identifier: UserIdentifier, cb: callback<{ id: number }>): void; +} + +export class Leads { + create(lead: Partial): Promise>; + create(lead: Partial, cb: callback>): void; + + update(lead: UserIdentifier & Partial): Promise>; + update(lead: UserIdentifier & Partial, cb: callback>): void; + + list(): Promise>; + list(cb: callback>): void; + + listBy(params: { email?: string, tag_id?: string, segment_id?: string }): Promise>; + listBy(params: { email?: string, tag_id?: string, segment_id?: string }, cb: callback>): void; + + find(identifier: LeadIdentifier): Promise> + find(identifier: LeadIdentifier, cb: callback>): void; + + delete(id: string): Promise>; + delete(id: string, cb: callback>): void; + + convert(params: { contact: LeadIdentifier, user: UserIdentifier }): Promise>; + convert(params: { contact: LeadIdentifier, user: UserIdentifier }, cb: callback>): void; - requestPermanentDeletion(): Promise<{id: number}>; } export class Companies { diff --git a/types/intl-tel-input/v13/tslint.json b/types/intl-tel-input/v13/tslint.json index b6afb8acee..d2632b3e92 100644 --- a/types/intl-tel-input/v13/tslint.json +++ b/types/intl-tel-input/v13/tslint.json @@ -75,6 +75,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts index af62a95830..f484502f4d 100644 --- a/types/jest-when/index.d.ts +++ b/types/jest-when/index.d.ts @@ -8,6 +8,11 @@ export interface PartialMockInstance { mockReturnValue: jest.MockInstance['mockReturnValue']; + mockReturnValueOnce: jest.MockInstance['mockReturnValueOnce']; + mockResolvedValue: jest.MockInstance['mockResolvedValue']; + mockResolvedValueOnce: jest.MockInstance['mockResolvedValueOnce']; + mockRejectedValue: jest.MockInstance['mockRejectedValue']; + mockRejectedValueOnce: jest.MockInstance['mockRejectedValueOnce']; } export interface When { diff --git a/types/jquery-focus-exit/index.d.ts b/types/jquery-focus-exit/index.d.ts index 8787136a4e..d4da0a1f18 100644 --- a/types/jquery-focus-exit/index.d.ts +++ b/types/jquery-focus-exit/index.d.ts @@ -14,7 +14,7 @@ export interface FocusElements { declare global { interface JQuery { focusExit(options?: { debug: boolean }): JQuery; - on(event: 'focusExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; - one(event: 'focusin', handler: ((event: JQuery.Event) => void)): JQuery; + on(event: 'focusExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; + one(event: 'focusin', handler: ((event: JQuery.TriggeredEvent) => void)): JQuery; } } diff --git a/types/jquery-mouse-exit/index.d.ts b/types/jquery-mouse-exit/index.d.ts index f0ba17996e..651a7b3f85 100644 --- a/types/jquery-mouse-exit/index.d.ts +++ b/types/jquery-mouse-exit/index.d.ts @@ -18,6 +18,6 @@ export type FocusElements = Partial<{ declare global { interface JQuery { mouseExit(options?: Options): JQuery; - on(event: 'mouseExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + on(event: 'mouseExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; } } diff --git a/types/jquery.colorpicker/tslint.json b/types/jquery.colorpicker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.colorpicker/tslint.json +++ b/types/jquery.colorpicker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.fancytree/tslint.json b/types/jquery.fancytree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.fancytree/tslint.json +++ b/types/jquery.fancytree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.pjax/tslint.json b/types/jquery.pjax/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.pjax/tslint.json +++ b/types/jquery.pjax/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index 7453457953..123fad3b34 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -530,7 +530,10 @@ $( document ).ajaxComplete(function( event, request, settings ) { }); ``` */ - ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxComplete(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * 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. @@ -543,7 +546,11 @@ $( document ).ajaxError(function( event, request, settings ) { }); ``` */ - ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; + ajaxError(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxSettings: JQuery.AjaxSettings, + thrownError: string) => void | false): this; /** * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. * @param handler The function to be invoked. @@ -556,7 +563,10 @@ $( document ).ajaxSend(function( event, request, settings ) { }); ``` */ - ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxSend(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. * @param handler The function to be invoked. @@ -595,7 +605,11 @@ $( document ).ajaxSuccess(function( event, request, settings ) { }); ``` */ - ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; + ajaxSuccess(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings, + data: JQuery.PlainObject) => void | false): this; /** * Perform a custom animation of a set of CSS properties. * @param properties An object of CSS properties and values that the animation will move toward. @@ -1329,9 +1343,12 @@ $( "p" ).before( $( "b" ) ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - bind(eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + bind( + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -1458,8 +1475,13 @@ $( "button" ).click(function() { ``` */ - bind(eventType: string, - handler_preventBubble: JQuery.EventHandler | JQuery.EventHandlerBase> | false | null | undefined): this; + bind( + eventType: TType, + handler_preventBubble: JQuery.TypeEventHandler | + false | + null | + undefined + ): this; /** * 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. @@ -1485,7 +1507,7 @@ $( "div.test" ).bind({ }); ``` */ - bind(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + bind(events: JQuery.TypeEventHandlers): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1499,7 +1521,7 @@ $( "div.test" ).bind({ * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ blur(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -1515,7 +1537,8 @@ $( "div.test" ).bind({ $( "p" ).blur(); ``` */ - blur(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + blur(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1529,7 +1552,7 @@ $( "p" ).blur(); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ change(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -1588,7 +1611,8 @@ $( "input[type='text']" ).change(function() { }); ``` */ - change(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + change(handler?: JQuery.TypeEventHandler | + 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. @@ -1841,7 +1865,7 @@ $( "#stop" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ click(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -1891,7 +1915,8 @@ $( "p" ).click(function() { $( "p" ).click(); ``` */ - click(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + click(handler?: JQuery.TypeEventHandler | + false): this; /** * Create a deep copy of the set of matched elements. * @param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The @@ -2079,7 +2104,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ contextmenu(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -2133,7 +2158,8 @@ div.contextmenu(function() { ``` */ - contextmenu(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + contextmenu(handler?: JQuery.TypeEventHandler | + false): this; /** * Set one or more CSS properties for the set of matched elements. * @param propertyName A CSS property name. @@ -2594,7 +2620,7 @@ $( "button" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ dblclick(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -2648,7 +2674,8 @@ divdbl.dblclick(function() { ``` */ - dblclick(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + dblclick(handler?: JQuery.TypeEventHandler | + false): this; /** * Set a timer to delay execution of subsequent items in the queue. * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. @@ -2713,10 +2740,13 @@ $( "button" ).click(function() { * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - delegate(selector: JQuery.Selector, - eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2828,9 +2858,12 @@ $( "button" ).click(function() { ``` */ - delegate(selector: JQuery.Selector, - eventType: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2844,7 +2877,8 @@ $( "button" ).click(function() { * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ delegate(selector: JQuery.Selector, - events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + events: JQuery.TypeEventHandlers + ): this; /** * 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. @@ -4264,7 +4298,7 @@ $( "p span" ).first().addClass( "highlight" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focus(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -4316,7 +4350,8 @@ $( document ).ready(function() { }); ``` */ - focus(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focus(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusin" event. * @param eventData An object containing data that will be passed to the event handler. @@ -4330,7 +4365,7 @@ $( document ).ready(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusin(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusin" event. * @param handler A function to execute each time the event is triggered. @@ -4370,7 +4405,8 @@ $( "p" ).focusin(function() { ``` */ - focusin(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusin(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param eventData An object containing data that will be passed to the event handler. @@ -4384,7 +4420,7 @@ $( "p" ).focusin(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param handler A function to execute each time the event is triggered. @@ -4445,7 +4481,8 @@ $( "p" ) ``` */ - focusout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusout(handler?: JQuery.TypeEventHandler | + false): this; /** * Retrieve one of the elements matched by the jQuery object. * @param index A zero-based integer indicating which element to retrieve. @@ -4888,12 +4925,11 @@ $( "button" ).click(function() { */ hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; /** - * Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. * @see \`{@link https://api.jquery.com/hover/ }\` * @since 1.0 - * @since 1.4 * @deprecated ​ Deprecated. * * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. @@ -4961,6 +4997,21 @@ $( "td" ).hover( ```javascript $( "td" ).off( "mouseenter mouseleave" ); ``` + */ + hover(handlerIn: JQuery.TypeEventHandler | + false, + handlerOut: JQuery.TypeEventHandler | + false): this; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * @see \`{@link https://api.jquery.com/hover/ }\` + * @since 1.4 + * @deprecated ​ Deprecated. + * + * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. + * + * **Solution**: Review uses of `.hover()` to determine if they are appropriate, and consider use of plugins such as `hoverIntent` as an alternative. The direct replacement for `.hover(fn1, fn2)`, is `.on("mouseenter", fn1).on("mouseleave", fn2)`. * @example ​ ````Slide the next sibling LI up or down on hover, and toggle a class. ```html @@ -5016,10 +5067,8 @@ $( "li" ) ``` */ - // 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; + hover(handlerInOut: JQuery.TypeEventHandler | + false): this; /** * Set the HTML contents of each element in the set of matched elements. * @param htmlString_function _@param_ `htmlString_function` @@ -5833,7 +5882,7 @@ $( "li" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keydown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -5905,7 +5954,8 @@ $( "#other" ).click(function() { ``` */ - keydown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keydown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -5919,7 +5969,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keypress(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -5991,7 +6041,8 @@ $( "#other" ).click(function() { ``` */ - keypress(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keypress(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6005,7 +6056,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keyup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6078,7 +6129,8 @@ $( "#other").click(function() { ``` */ - keyup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keyup(handler?: JQuery.TypeEventHandler | + false): this; /** * Reduce the set of matched elements to the final one in the set. * @see \`{@link https://api.jquery.com/last/ }\` @@ -6367,7 +6419,7 @@ $( "input" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousedown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6405,7 +6457,8 @@ $( "p" ) ``` */ - mousedown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousedown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6419,7 +6472,7 @@ $( "p" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseenter(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6500,7 +6553,8 @@ $( "div.enterleave" ) ``` */ - mouseenter(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseenter(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6514,7 +6568,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseleave(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6593,7 +6647,8 @@ $( "div.enterleave" ) ``` */ - mouseleave(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseleave(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6607,7 +6662,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousemove(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6671,7 +6726,8 @@ $( "div" ).mousemove(function( event ) { ``` */ - mousemove(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousemove(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6685,7 +6741,7 @@ $( "div" ).mousemove(function( event ) { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6766,7 +6822,8 @@ $( "div.enterleave" ) ``` */ - mouseout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseout(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6780,7 +6837,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseover(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6861,7 +6918,8 @@ $( "div.enterleave" ) ``` */ - mouseover(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseover(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6875,7 +6933,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -6913,7 +6971,8 @@ $( "p" ) ``` */ - mouseup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseup(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector 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. @@ -7245,7 +7304,10 @@ $( "body" ).on( "click", "p", foo ); $( "body" ).off( "click", "p", foo ); ``` */ - off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; + off(events: string, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false): this; /** * Remove an event handler. * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as @@ -7275,7 +7337,10 @@ $( "form" ).on( "keypress.validator", "input[type='text']", validate ); $( "form" ).off( ".validator" ); ``` */ - off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; + off(events: string, + selector_handler?: JQuery.Selector | + JQuery.TypeEventHandler | + false): this; /** * Remove an event handler. * @param events An object where the string keys represent one or more space-separated event types and optional @@ -7284,7 +7349,8 @@ $( "form" ).off( ".validator" ); * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ - off(events: JQuery.PlainObject> | false>, selector?: JQuery.Selector): this; + off(events: JQuery.TypeEventHandlers, + selector?: JQuery.Selector): this; /** * Remove an event handler. * @param event A jQuery.Event object. @@ -7295,7 +7361,7 @@ $( "form" ).off( ".validator" ); $( "p" ).off(); ``` */ - off(event?: JQuery.Event): this; + off(event?: JQuery.TriggeredEvent): this; /** * Set the current coordinates of every element in the set of matched elements, relative to the document. * @param coordinates_function _@param_ `coordinates_function` @@ -7468,10 +7534,30 @@ $( "*", document.body ).click(function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + on( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): 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 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 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/ }\` + * @since 1.7 + */ + on( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): 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". @@ -7484,7 +7570,7 @@ $( "*", document.body ).click(function( event ) { * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. */ on(events: string, - selector: JQuery.Selector | null, + selector: JQuery.Selector | null | undefined, data: any, handler: ((event: JQueryEventObject) => void)): this; /** @@ -7547,14 +7633,41 @@ $( "body" ).on( "click", "a", function( event ) { }); ``` */ - on(events: string, - selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false + ): 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 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 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/ }\` + * @since 1.7 + * @example ​ ````Pass data to the event handler, which is specified here by name: +```javascript +function myHandler( event ) { + alert( event.data.foo ); +} +$( "p" ).on( "click", { foo: "bar" }, myHandler ); +``` + */ + on( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): 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 selector_data _@param_ `selector_data` + *
+ * * `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.
+ * * `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/ }\` * @since 1.7 @@ -7609,37 +7722,6 @@ $( "body" ).on( "click", "a", function( event ) { event.preventDefault(); }); ``` - */ - on(events: string, - selector: JQuery.Selector, - // tslint:disable-next-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 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/ }\` - * @since 1.7 - * @example ​ ````Pass data to the event handler, which is specified here by name: -```javascript -function myHandler( event ) { - alert( event.data.foo ); -} -$( "p" ).on( "click", { foo: "bar" }, myHandler ); -``` - */ - on(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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 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/ }\` - * @since 1.7 - * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. * @example ​ ````Pass data to the event handler, which is specified here by name: ```javascript function myHandler( event ) { @@ -7649,8 +7731,7 @@ $( "p" ).on( "click", { foo: "bar" }, myHandler ); ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures - data: any, + selector_data: any, handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7743,8 +7824,11 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { }); ``` */ - on(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + handler: JQuery.TypeEventHandler | + false + ): 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". @@ -7837,7 +7921,6 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7849,9 +7932,26 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @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 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/ }\` + * @since 1.7 + */ + on( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7861,9 +7961,9 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures - selector: JQuery.Selector): this; + on(events: JQuery.TypeEventHandlers, + selector: JQuery.Selector + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7872,8 +7972,10 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7922,7 +8024,7 @@ $( "div.test" ).on({ ``` */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + on(events: JQuery.TypeEventHandlers): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7933,10 +8035,30 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @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 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/ }\` + * @since 1.7 + */ + one( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7947,9 +8069,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, + one( + events: TType, selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7958,9 +8083,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -8049,8 +8177,11 @@ $(".target").one("click mouseenter", function() { ``` */ - one(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + one( + events: TType, + handler: JQuery.TypeEventHandler| + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8061,9 +8192,26 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @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 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/ }\` + * @since 1.7 + */ + one( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8073,8 +8221,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures + one(events: JQuery.TypeEventHandlers, selector: JQuery.Selector): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8084,8 +8231,10 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8093,7 +8242,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + one(events: JQuery.TypeEventHandlers): this; /** * Set the CSS outer height of each element in the set of matched elements. * @param value_function _@param_ `value_function` @@ -9851,7 +10000,7 @@ $( "button" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ resize(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -9869,7 +10018,8 @@ $( window ).resize(function() { }); ``` */ - resize(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + resize(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -9883,7 +10033,7 @@ $( window ).resize(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ scroll(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -9933,7 +10083,8 @@ $( window ).scroll(function() { ``` */ - scroll(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + scroll(handler?: JQuery.TypeEventHandler | + 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. @@ -10107,7 +10258,7 @@ $( "p:last" ).text( "scrollTop:" + p.scrollTop() ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ select(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -10156,7 +10307,8 @@ $( ":input" ).select(function() { $( "input" ).select(); ``` */ - select(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + select(handler?: JQuery.TypeEventHandler | + false): this; /** * Encode a set of form elements as a string for submission. * @see \`{@link https://api.jquery.com/serialize/ }\` @@ -11127,7 +11279,7 @@ $( "#toggle" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ submit(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * 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. @@ -11196,7 +11348,8 @@ $( "form" ).submit(function() { $( "form:first" ).submit(); ``` */ - submit(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + submit(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the content of each element in the set of matched elements to the specified text. * @param text_function _@param_ `text_function` @@ -11704,7 +11857,7 @@ $( "body" ).trigger({ }); ``` */ - trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; + trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; /** * Execute all handlers attached to an element for an event. * @param eventType_event _@param_ `eventType_event` @@ -11747,7 +11900,7 @@ $( "input" ).focus(function() { ``` */ - triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; + triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11815,7 +11968,10 @@ $( "p" ).bind( "click", foo ); // ... Now foo will be called when paragraphs are $( "p" ).unbind( "click", foo ); // ... foo will no longer be called. ``` */ - unbind(event: string, handler: JQuery.EventHandlerBase> | false): this; + unbind(event: string, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11836,7 +11992,7 @@ $( "p" ).unbind(); $( "p" ).unbind( "click" ); ``` */ - unbind(event?: string | JQuery.Event): this; + unbind(event?: string | JQuery.TriggeredEvent): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param selector A selector which will be used to filter the event results. @@ -11906,12 +12062,18 @@ $( "body" ).delegate( "p", "click", foo ); $( "body" ).undelegate( "p", "click", foo ); ``` */ - undelegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandlerBase> | false): this; + undelegate(selector: JQuery.Selector, + eventType: string, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @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. + * @param eventType_events _@param_ `eventType_events` + *
+ * * `eventType` — A string containing a JavaScript event type, such as "click" or "keydown"
+ * * `events` — An object of one or more event types and previously bound functions to unbind from them. * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 * @since 1.4.3 @@ -11921,7 +12083,9 @@ $( "body" ).undelegate( "p", "click", foo ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - undelegate(selector: JQuery.Selector, eventTypes: string | JQuery.PlainObject> | false>): this; + undelegate(selector: JQuery.Selector, + eventType_events: string | + JQuery.TypeEventHandlers): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param namespace A selector which will be used to filter the event results. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 515715bf14..c533f1b235 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -2430,7 +2430,7 @@ function JQuery() { $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2446,7 +2446,7 @@ function JQuery() { $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2464,7 +2464,7 @@ function JQuery() { $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2500,7 +2500,7 @@ function JQuery() { $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -3883,21 +3883,11 @@ function JQuery() { function events() { // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 function bind() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3905,77 +3895,51 @@ function JQuery() { $('p').bind('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('p').bind('myEvent', false); + // $ExpectType JQuery + $('p').bind('myEvent', null); + + // $ExpectType JQuery + $('p').bind('myEvent', undefined); + // $ExpectType JQuery $('p').bind({ myEvent1: false, myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); - - // $ExpectType JQuery - $('p').bind('myEvent', null); - - // $ExpectType JQuery - $('p').bind('myEvent', undefined); - } + } function delegate() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').delegate('td', 'myEvent', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').delegate('td', 'myEvent', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3984,44 +3948,32 @@ function JQuery() { // $ExpectType JQuery $('table').delegate('td', { - myEvent1(event) { - // $ExpectType HTMLElement + myEvent1: false, + myEvent2(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent2: false, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -4030,16 +3982,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -4050,52 +3996,30 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('table').off($.Event('myEvent')); + $('table').off(ev); // $ExpectType JQuery $('table').off(); } function on() { - interface J1 { kind: 'J1'; } - - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4103,12 +4027,29 @@ function JQuery() { $('table').on('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. // $ExpectType HTMLElement this; // $ExpectType JQueryEventObject @@ -4116,34 +4057,19 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', undefined, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4154,7 +4080,15 @@ function JQuery() { $('table').on('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); @@ -4167,20 +4101,15 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').on('myEvent', function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }); + $('table').on('myEvent', false); // $ExpectType JQuery $('table').on('myEvent', function(event: JQueryEventObject) { @@ -4214,30 +4143,19 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', false); - // $ExpectType JQuery $('table').on({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4248,13 +4166,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4265,13 +4183,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').on({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4282,13 +4217,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4299,34 +4234,24 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); } function one() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4334,31 +4259,23 @@ function JQuery() { $('table').one('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').one('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4369,15 +4286,7 @@ function JQuery() { $('table').one('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4385,15 +4294,7 @@ function JQuery() { $('table').one('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4404,15 +4305,15 @@ function JQuery() { $('table').one({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4423,13 +4324,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4440,13 +4341,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').one({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4457,13 +4375,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4474,13 +4392,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); @@ -4551,27 +4469,15 @@ function JQuery() { } function unbind() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_defaultData); + $('p').unbind('myEvent', defaultData); // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_customData); + $('p').unbind('myEvent', customData); // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4579,35 +4485,24 @@ function JQuery() { // $ExpectType JQuery $('p').unbind('myEvent'); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('p').unbind($.Event('myEvent')); + $('p').unbind(ev); // $ExpectType JQuery $('p').unbind(); } function undelegate() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_defaultData); + $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_customData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_defaultData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_customData); + $('table').undelegate('td', 'click', customData); // $ExpectType JQuery $('table').undelegate('td', 'click', false); @@ -4618,10 +4513,8 @@ function JQuery() { // $ExpectType JQuery $('table').undelegate('td', { myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -4632,21 +4525,11 @@ function JQuery() { } function blur() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').blur('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4654,15 +4537,7 @@ function JQuery() { $('p').blur(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4674,21 +4549,11 @@ function JQuery() { } function change() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').change('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4696,15 +4561,7 @@ function JQuery() { $('p').change(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4716,21 +4573,11 @@ function JQuery() { } function click() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').click('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4738,15 +4585,7 @@ function JQuery() { $('p').click(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4758,21 +4597,11 @@ function JQuery() { } function contextmenu() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').contextmenu('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4780,15 +4609,7 @@ function JQuery() { $('p').contextmenu(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4800,21 +4621,11 @@ function JQuery() { } function dblclick() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').dblclick('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4822,15 +4633,7 @@ function JQuery() { $('p').dblclick(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4842,21 +4645,11 @@ function JQuery() { } function focus() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focus('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4864,15 +4657,7 @@ function JQuery() { $('p').focus(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4884,21 +4669,11 @@ function JQuery() { } function focusin() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusin('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4906,15 +4681,7 @@ function JQuery() { $('p').focusin(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4926,21 +4693,11 @@ function JQuery() { } function focusout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4948,15 +4705,7 @@ function JQuery() { $('p').focusout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4968,21 +4717,11 @@ function JQuery() { } function keydown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keydown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4990,15 +4729,7 @@ function JQuery() { $('p').keydown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -5010,21 +4741,11 @@ function JQuery() { } function keypress() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keypress('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5032,15 +4753,7 @@ function JQuery() { $('p').keypress(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5052,21 +4765,11 @@ function JQuery() { } function keyup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keyup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5074,15 +4777,7 @@ function JQuery() { $('p').keyup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5094,21 +4789,11 @@ function JQuery() { } function mousedown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousedown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5116,15 +4801,7 @@ function JQuery() { $('p').mousedown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5136,21 +4813,11 @@ function JQuery() { } function mouseenter() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseenter('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5158,15 +4825,7 @@ function JQuery() { $('p').mouseenter(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5178,21 +4837,11 @@ function JQuery() { } function mouseleave() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseleave('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5200,15 +4849,7 @@ function JQuery() { $('p').mouseleave(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5220,21 +4861,11 @@ function JQuery() { } function mousemove() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousemove('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5242,15 +4873,7 @@ function JQuery() { $('p').mousemove(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5262,21 +4885,11 @@ function JQuery() { } function mouseout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5284,15 +4897,7 @@ function JQuery() { $('p').mouseout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5304,21 +4909,11 @@ function JQuery() { } function mouseover() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseover('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5326,15 +4921,7 @@ function JQuery() { $('p').mouseover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5346,21 +4933,11 @@ function JQuery() { } function mouseup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5368,15 +4945,7 @@ function JQuery() { $('p').mouseup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5388,21 +4957,11 @@ function JQuery() { } function resize() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').resize('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5410,15 +4969,7 @@ function JQuery() { $('p').resize(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5430,21 +4981,11 @@ function JQuery() { } function scroll() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').scroll('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5452,15 +4993,7 @@ function JQuery() { $('p').scroll(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5472,21 +5005,11 @@ function JQuery() { } function select() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').select('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5494,15 +5017,7 @@ function JQuery() { $('p').select(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5514,21 +5029,11 @@ function JQuery() { } function submit() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').submit('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5536,15 +5041,7 @@ function JQuery() { $('p').submit(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5556,32 +5053,16 @@ function JQuery() { } function hover() { - interface J1 { kind: 'J1'; } - interface J2 { kind: 'J2'; } - // $ExpectType JQuery $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5589,41 +5070,7 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(this: J2, event) { - // $ExpectType J2 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, false); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, false); @@ -5631,15 +5078,7 @@ function JQuery() { $('p').hover(false, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(false, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5650,16 +5089,23 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent | MouseLeaveEvent event; - }); - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; + switch (event.type) { + case 'mouseover': + // $ExpectType MouseEnterEvent + event; + break; + case 'mouseout': + // $ExpectType MouseLeaveEvent + event; + break; + default: + // $ExpectType never + event; + break; + } }); // $ExpectType JQuery @@ -8398,51 +7844,186 @@ function JQuery_Effects() { function JQuery_Event() { function call_signature() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - $.Event({ - type: 'keydown' - }); } function constructor() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates new $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - new $.Event({ - type: 'keydown' - }); } // https://stackoverflow.com/questions/49892574/trigger-a-jquery-3-event-with-ctrlkey-set function stackoverflow_49892574() { - const event = $.Event("keydown"); + const event = $.Event("keydown"); event.which = 77; event.ctrlKey = true; $(window).trigger(event); } } +function JQuery_TypeEventHandlers() { + const events: JQuery.TypeEventHandlers = { + change(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ChangeEvent + event; + }, + resize(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ResizeEvent + event; + }, + scroll(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ScrollEvent + event; + }, + select(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SelectEvent + event; + }, + submit(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SubmitEvent + event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; + }, + contextmenu(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ContextMenuEvent + event; + }, + dblclick(event) { + // $ExpectType HTMLElement + this; + // $ExpectType DoubleClickEvent + event; + }, + mousedown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseDownEvent + event; + }, + mouseenter(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseEnterEvent + event; + }, + mouseleave(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseLeaveEvent + event; + }, + mousemove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseMoveEvent + event; + }, + mouseout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOutEvent + event; + }, + mouseover(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOverEvent + event; + }, + mouseup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseUpEvent + event; + }, + keydown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyDownEvent + event; + }, + keypress(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyPressEvent + event; + }, + keyup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyUpEvent + event; + }, + touchcancel(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchCancelEvent + event; + }, + touchend(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchEndEvent + event; + }, + touchmove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchMoveEvent + event; + }, + touchstart(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchStartEvent + event; + }, + blur(event) { + // $ExpectType HTMLElement + this; + // $ExpectType BlurEvent + event; + }, + focus(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusEvent + event; + }, + focusin(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusInEvent + event; + }, + focusout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusOutEvent + event; + } + }; +} + function JQuery_EventExtensions() { - function fixHooks() { - jQuery.event.fixHooks.drop = { - props: ['dataTransfer'], - filter(event, originalEvent) { - // $ExpectType Event - event; - // $ExpectType Event - originalEvent; - }, - }; - - // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. - // $ExpectError - jQuery.event.fixHooks.drop = ['dataTransfer']; - } - function special() { jQuery.event.special.multiclick = { noBubble: true, @@ -8455,7 +8036,7 @@ function JQuery_EventExtensions() { data; // $ExpectType string namespaces; - // $ExpectType EventHandler + // $ExpectType EventHandlerBase> eventHandle; return false; @@ -8481,7 +8062,7 @@ function JQuery_EventExtensions() { trigger(event, data) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; // $ExpectType any data; @@ -8489,7 +8070,7 @@ function JQuery_EventExtensions() { return false; }, _default(event, data) { - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType any data; @@ -8497,7 +8078,7 @@ function JQuery_EventExtensions() { return false; }, handle(event, data) { - // $ExpectType Event & { handleObj: HandleObject; } + // $ExpectType TriggeredEvent & { handleObj: HandleObject; } event; // $ExpectType any data; @@ -8505,7 +8086,7 @@ function JQuery_EventExtensions() { preDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; return false; @@ -8513,7 +8094,7 @@ function JQuery_EventExtensions() { postDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; } }; diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index 7b09b6a4dc..481b79e037 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -3981,49 +3981,97 @@ $( "input" ).click(function() { // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. - // Static members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + */ 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; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + (event: string, properties?: T): Event & T; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + new (event: string, properties?: T): Event & T; } - // Instance members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @see \`{@link TriggeredEvent }\` + */ interface Event { // region Copied properties // #region Copied properties - // region Event - // #region Event + // Event - bubbles?: boolean; - cancelable?: boolean; - eventPhase?: number; + bubbles: boolean | undefined; + cancelable: boolean | undefined; + eventPhase: number | undefined; - // #endregion + // UIEvent - // region UIEvent - // #region UIEvent + detail: number | undefined; + view: Window | undefined; - detail?: number; - view?: Window; + // MouseEvent - // #endregion - - // region MouseEvent - // #region MouseEvent - - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - offsetX?: number; - offsetY?: number; + button: number | undefined; + buttons: number | undefined; + clientX: number | undefined; + clientY: number | undefined; + offsetX: number | undefined; + offsetY: number | undefined; /** * The mouse position relative to the left edge of the document. * @see \`{@link https://api.jquery.com/event.pageX/ }\` @@ -4059,7 +4107,7 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageX: number; + pageX: number | undefined; /** * The mouse position relative to the top edge of the document. * @see \`{@link https://api.jquery.com/event.pageY/ }\` @@ -4095,49 +4143,93 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageY: number; - screenX?: number; - screenY?: number; + pageY: number | undefined; + screenX: number | undefined; + screenY: number | undefined; /** @deprecated */ - toElement?: Element; + toElement: Element | undefined; - // #endregion + // PointerEvent - // region PointerEvent - // #region PointerEvent + pointerId: number | undefined; + pointerType: string | undefined; - pointerId?: number; - pointerType?: string; - - // #endregion - - // region KeyboardEvent - // #region KeyboardEvent + // KeyboardEvent /** @deprecated */ - char?: string; + char: string | undefined; /** @deprecated */ - charCode?: number; - key?: string; + charCode: number | undefined; + key: string | undefined; /** @deprecated */ - keyCode?: number; + keyCode: number | undefined; - // #endregion + // TouchEvent - // region TouchEvent - // #region TouchEvent + changedTouches: TouchList | undefined; + targetTouches: TouchList | undefined; + touches: TouchList | undefined; - changedTouches?: TouchList; - targetTouches?: TouchList; - touches?: TouchList; + // MouseEvent, KeyboardEvent - // #endregion + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number | undefined; - // region MouseEvent, KeyboardEvent, TouchEvent - // #region MouseEvent, KeyboardEvent, TouchEvent + // MouseEvent, KeyboardEvent, TouchEvent - altKey?: boolean; - ctrlKey?: boolean; + altKey: boolean | undefined; + ctrlKey: boolean | undefined; /** * Indicates whether the META key was pressed when the event fired. * @see \`{@link https://api.jquery.com/event.metaKey/ }\` @@ -4174,77 +4266,11 @@ $( "#checkMetaKey" ).click(function( event ) { ``` */ - metaKey: boolean; - shiftKey?: boolean; + metaKey: boolean | undefined; + shiftKey: boolean | undefined; // #endregion - // #endregion - - /** - * The namespace specified when the event was triggered. - * @see \`{@link https://api.jquery.com/event.namespace/ }\` - * @since 1.4.3 - * @example ​ ````Determine the event namespace used. -```html - - - - - event.namespace demo - - - -​ - -

-​ - -​ - - -``` - */ - namespace: string; - /** - * 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/ }\` - * @since 1.3 - * @example ​ ````Display previous handler's return value -```html - - - - - event.result demo - - - -​ - -

-​ - -​ - - -``` - */ - 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/ }\` @@ -4301,58 +4327,6 @@ $( "a" ).click(function( event ) { ``` */ 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/ }\` - * @since 1.1.3 - * @example ​ ````Log which key was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - * @example ​ ````Log which mouse button was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - */ - which: number; /** * Returns whether event.preventDefault() was ever called on this event object. * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` @@ -4545,11 +4519,17 @@ $( "p" ).click(function( event ) { stopPropagation(): void; } - // Generic members - interface Event< - TTarget = EventTarget, - TData = null - > { + // #endregion + + /** + * Base type for jQuery events that have been triggered (including events triggered on plain objects). + */ + interface TriggeredEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends Event { /** * The current DOM element within the event bubbling phase. * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` @@ -4560,51 +4540,8 @@ $( "p" ).click(function( event ) { alert( event.currentTarget === this ); // true }); ``` - */ - 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/ }\` - * @since 1.1 - * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. -```html - - - - - event.data demo - - - -​ - - - - - -​ -
-​ - -​ - - -``` - */ - data: TData; + */ + currentTarget: TCurrentTarget; /** * The element where the currently-called jQuery event handler was attached. * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` @@ -4615,21 +4552,8 @@ $( ".box" ).on( "click", "button", function( event ) { $( event.delegateTarget ).css( "background-color", "red" ); }); ``` - */ - delegateTarget: TTarget; - originalEvent: _Event; - /** - * The other DOM element involved in the event, if any. - * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` - * @since 1.1.4 - * @example ​ ````On mouseout of anchors, alert the element type being entered. -```javascript -$( "a" ).mouseout(function( event ) { - alert( event.relatedTarget.nodeName ); // "DIV" -}); -``` - */ - relatedTarget: TTarget | null; + */ + delegateTarget: TDelegateTarget; /** * The DOM element that initiated the event. * @see \`{@link https://api.jquery.com/event.target/ }\` @@ -4707,37 +4631,1727 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); ``` - */ + */ target: 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/ }\` + * @since 1.1 + * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. +```html + + + + + event.data demo + + + +​ + + + + + +​ +
+​ + +​ + + +``` + */ + data: TData; + + /** + * The namespace specified when the event was triggered. + * @see \`{@link https://api.jquery.com/event.namespace/ }\` + * @since 1.4.3 + * @example ​ ````Determine the event namespace used. +```html + + + + + event.namespace demo + + + +​ + +

+​ + +​ + + +``` + */ + namespace?: string; + /** + * 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/ }\` + * @since 1.3 + * @example ​ ````Display previous handler's return value +```html + + + + + event.result demo + + + +​ + +

+​ + +​ + + +``` + */ + result?: any; } - interface EventLike { - type: string; + // region Event + // #region Event + + interface EventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: undefined; + view: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _Event; + } + + interface ChangeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'change'; + } + + interface ResizeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'resize'; + } + + interface ScrollEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'scroll'; + } + + interface SelectEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'select'; + } + + interface SubmitEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'submit'; } // #endregion - interface EventHandler extends EventHandlerBase> { } + // region UIEvent + // #region UIEvent + + interface UIEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: number; + view: Window; + + originalEvent?: _UIEvent; + } + + // region MouseEvent + // #region MouseEvent + + interface MouseEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: number; + buttons: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: number; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: number; + screenX: number; + screenY: number; + /** @deprecated */ + toElement: Element; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _MouseEvent; + } + + interface ClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'click'; + } + + interface ContextMenuEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'contextmenu'; + } + + interface DoubleClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'dblclick'; + } + + interface MouseDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousedown'; + } + + interface MouseEnterEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseover'; + } + + interface MouseLeaveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseout'; + } + + interface MouseMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousemove'; + } + + interface MouseOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseout'; + } + + interface MouseOverEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseover'; + } + + interface MouseUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mouseup'; + } + + // #endregion + + // region KeyboardEvent + // #region KeyboardEvent + + interface KeyboardEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: string | undefined; + /** @deprecated */ + charCode: number; + key: string; + /** @deprecated */ + keyCode: number; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _KeyboardEvent; + } + + interface KeyDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keydown'; + } + + interface KeyPressEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keypress'; + } + + interface KeyUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keyup'; + } + + // #endregion + + // region TouchEvent + // #region TouchEvent + + interface TouchEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: TouchList; + targetTouches: TouchList; + touches: TouchList; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _TouchEvent; + } + + interface TouchCancelEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchcancel'; + } + + interface TouchEndEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchend'; + } + + interface TouchMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchmove'; + } + + interface TouchStartEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchstart'; + } + + // #endregion + + // region FocusEvent + // #region FocusEvent + + interface FocusEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _FocusEvent; + } + + interface BlurEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'blur'; + } + + interface FocusEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focus'; + } + + interface FocusInEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusin'; + } + + interface FocusOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusout'; + } + + // #endregion + + // #endregion + + interface TypeToTriggeredEventMap< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > { + // Event + + change: ChangeEvent; + resize: ResizeEvent; + scroll: ScrollEvent; + select: SelectEvent; + submit: SubmitEvent; + + // UIEvent + + // MouseEvent + + click: ClickEvent; + contextmenu: ContextMenuEvent; + dblclick: DoubleClickEvent; + mousedown: MouseDownEvent; + mouseenter: MouseEnterEvent; + mouseleave: MouseLeaveEvent; + mousemove: MouseMoveEvent; + mouseout: MouseOutEvent; + mouseover: MouseOverEvent; + mouseup: MouseUpEvent; + + // KeyboardEvent + + keydown: KeyDownEvent; + keypress: KeyPressEvent; + keyup: KeyUpEvent; + + // TouchEvent + + touchcancel: TouchCancelEvent; + touchend: TouchEndEvent; + touchmove: TouchMoveEvent; + touchstart: TouchStartEvent; + + // FocusEvent + + blur: BlurEvent; + focus: FocusEvent; + focusin: FocusInEvent; + focusout: FocusOutEvent; + + [type: string]: TriggeredEvent; + } // Extra parameters can be passed from trigger() type EventHandlerBase = (this: TContext, t: T, ...args: any[]) => any; + type EventHandler< + TCurrentTarget, + TData = undefined + > = EventHandlerBase>; + + type TypeEventHandler< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TType extends keyof TypeToTriggeredEventMap + > = EventHandlerBase[TType]>; + + interface TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > extends _TypeEventHandlers { + // No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that + // derived types of Event are not assignable to Event. + [type: string]: TypeEventHandler | + false | + undefined | + object; + } + + type _TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > = { + [TType in keyof TypeToTriggeredEventMap]?: + TypeEventHandler | + false | + object; + }; + // region Event extensions // #region Event extensions interface EventExtensions { - /** - * jQuery defines an \`{@link https://api.jquery.com/category/events/event-object/ Event object}\` that represents a cross-browser subset of the information available when an event occurs. The `jQuery.event.props` property is an array of string names for properties that are always copied when jQuery processes a native browser event. (Events fired in code by `.trigger()` do not use this list, since the code can construct a `jQuery.Event` object with the needed values and trigger using that object.) - * - * To add a property name to this list, use `jQuery.event.props.push( "newPropertyName" )`. However, be aware that every event processed by jQuery will now attempt to copy this property name from the native browser event to jQuery's constructed event. If the property does not exist for that event type, it will get an undefined value. Adding many properties to this list can significantly reduce event delivery performance, so for infrequently-needed properties it is more efficient to use the value directly from `event.originalEvent` instead. If properties must be copied, you are strongly advised to use `jQuery.event.fixHooks` as of version 1.7. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-props-array }\` - */ - props: string[]; - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - fixHooks: FixHooks; /** * The jQuery special event hooks are a set of per-event-name functions and properties that allow code to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the name of the special event. Event names are case sensitive. * @@ -4747,75 +6361,6 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); special: SpecialEventHooks; } - // region Fix hooks - // #region Fix hooks - - // Workaround for TypeScript 2.3 which does not have support for weak types handling. - type FixHook = { - /** - * Strings representing properties that should be copied from the browser's event object to the jQuery event object. If omitted, no additional properties are copied beyond the standard ones that jQuery copies and normalizes (e.g. `event.target` and `event.relatedTarget`). - */ - props: string[]; - } | { - /** - * jQuery calls this function after it constructs the `jQuery.Event` object, copies standard properties from `jQuery.event.props`, and copies the `fixHooks`-specific props (if any) specified above. The function can create new properties on the event object or modify existing ones. The second argument is the browser's native event object, which is also available in `event.originalEvent`. - * - * Note that for all events, the browser's native event object is available in `event.originalEvent`; if the jQuery event handler examines the properties there instead of jQuery's normalized `event` object, there is no need to create a `fixHooks` entry to copy or modify the properties. - * @example ​ ````For example, to set a hook for the "drop" event that copies the `dataTransfer` property, assign an object to `jQuery.event.fixHooks.drop`: -```javascript -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -Since fixHooks is an advanced feature and rarely used externally, jQuery does not include code or -interfaces to deal with conflict resolution. If there is a chance that some other code may be assigning -`fixHooks` to the same events, the code should check for an existing hook and take appropriate measures. -A simple solution might look like this: - -```javascript -if ( jQuery.event.fixHooks.drop ) { - throw new Error( "Someone else took the jQuery.event.fixHooks.drop hook!" ); -} - -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -When there are known cases of different plugins wanting to attach to the drop hook, this solution might be more appropriate: - -```javascript -var existingHook = jQuery.event.fixHooks.drop; - -if ( !existingHook ) { - jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] - }; -} else { - if ( existingHook.props ) { - existingHook.props.push( "dataTransfer" ); - } else { - existingHook.props = [ "dataTransfer" ]; - } -} -``` - */ - filter(event: Event, originalEvent: _Event): void; - } | { - [key: string]: never; - }; - - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - interface FixHooks { - [event: string]: FixHook; - } - - // #endregion - // region Special event hooks // #region Special event hooks @@ -4879,13 +6424,13 @@ if ( !existingHook ) { * The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` object is constructed and before any handlers have been called. It can process the triggered event in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before returning. If the hook returns `false`, jQuery does not perform any further event triggering actions and returns immediately. Otherwise, it performs the normal trigger processing, calling any event handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` was specified for the special event) to call event handlers attached to parent elements. * @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\` */ - trigger(this: TTarget, event: Event, data: TData): void | false; + trigger(this: TTarget, event: Event, data: TData): void | false; } | { /** * When the `.trigger()` method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a `_default` hook is specified, the hook is called just prior to checking for and executing the element's default method. If this hook returns the value `false` the element's default method will be called; otherwise it is not. * @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\` */ - _default(event: Event, data: TData): void | false; + _default(event: TriggeredEvent, data: TData): void | false; } | { /** * jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` property has the detailed event information. @@ -4893,11 +6438,11 @@ if ( !existingHook ) { * Based in the information it has, the handle hook should decide whether to call the original handler function which is in `event.handleObj.handler`. It can modify information in the event object before calling the original handler, but _must restore_ that data before returning or subsequent unrelated event handlers may act unpredictably. In most cases, the handle hook should return the result of the original handler, but that is at the discretion of the hook. The handle hook is unique in that it is the only special event function hook that is called under its original special event name when the type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to have anything other than a handle hook present if the special event defines a `bindType` and `delegateType`, since those other hooks will never be called. * @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\` */ - handle(this: TTarget, event: Event & { handleObj: HandleObject; }, ...data: TData[]): void; + handle(this: TTarget, event: TriggeredEvent & { handleObj: HandleObject; }, ...data: TData[]): void; } | { - preDispatch(this: TTarget, event: Event): false | void; + preDispatch(this: TTarget, event: Event): false | void; } | { - postDispatch(this: TTarget, event: Event): void; + postDispatch(this: TTarget, event: Event): void; } | { [key: string]: never; }; @@ -4989,8 +6534,12 @@ if ( !existingHook ) { declare const jQuery: JQueryStatic; declare const $: JQueryStatic; -// Used by JQuery.Event type _Event = Event; +type _UIEvent = UIEvent; +type _MouseEvent = MouseEvent; +type _KeyboardEvent = KeyboardEvent; +type _TouchEvent = TouchEvent; +type _FocusEvent = FocusEvent; // region ES5 compatibility // #region ES5 compatibility diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 7ecb1733a7..77d412f8e1 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -384,7 +384,7 @@ function examples() { } function bind_2() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } @@ -830,7 +830,7 @@ function examples() { var len = kids.addClass('hilite').length; $('#results span:first').text(len); - $('#results span:last').text(event.target.tagName); + $('#results span:last').text((event.target as Element).tagName); event.preventDefault(); }); @@ -1578,7 +1578,7 @@ function examples() { function event_related_target_0() { $('a').mouseout(function(event) { - alert(( event.relatedTarget).nodeName); // "DIV" + alert((event.relatedTarget as HTMLElement).nodeName); // "DIV" }); } @@ -1614,12 +1614,12 @@ function examples() { function event_target_0() { $('body').click(function(event) { - $('#log').html('clicked: ' + event.target.nodeName); + $('#log').html('clicked: ' + (event.target as Node).nodeName); }); } function event_target_1() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { var target = $(event.target); if (target.is('li')) { target.children().toggle(); @@ -3018,10 +3018,10 @@ function examples() { function jQuery_proxy_0() { var me = { type: 'zombie', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { // Without proxy, `this` would refer to the event target // use event.target to reference that element. - var element = event.target; + var element = event.target as Element; $(element).css('background-color', 'red'); // With proxy, `this` refers to the me object encapsulating @@ -3033,7 +3033,7 @@ function examples() { var you = { type: 'person', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { $('#log').append(this.type + ' '); }, }; @@ -3075,7 +3075,7 @@ function examples() { type: 'dog', // Note that event comes *after* one and two - test: function(one: typeof you, two: typeof they, event: JQuery.Event) { + test: function(one: typeof you, two: typeof they, event: JQuery.TriggeredEvent) { $('#log') // `one` maps to `you`, the 1st additional @@ -3796,7 +3796,7 @@ function examples() { } function on_1() { - function myHandler(event: JQuery.Event) { + function myHandler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 8ef5eb2cfa..b1a0353b4e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -21,24 +21,6 @@ jQuery("a").greenify(); // Makes all the links green. // Events -function fixHooks() { - function setHook() { - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } - - function conflictResolution() { - if (jQuery.event.fixHooks.drop) { - throw new Error("Someone else took the jQuery.event.fixHooks.drop hook!"); - } - - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } -} - function special() { function defineSpecialEvent() { jQuery.event.special.pushy = { @@ -53,7 +35,7 @@ function special() { bindType: "click", handle(event) { const handleObj = event.handleObj; - const targetData = jQuery.data(event.target); + const targetData = jQuery.data(event.target as Element); let ret = null; // If a multiple of the click count, run the handler diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index bb3bb4c83c..e1ee36a575 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -538,7 +538,7 @@ function longdesc() { $('#foo').slideUp(300).delay(800).fadeIn(400); } - function delegate_0(elements: HTMLElement[], selector: string, events: any, data: any, handler: JQuery.EventHandler) { + function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { // jQuery 1.4.3+ $(elements).delegate(selector, events, data, handler); // jQuery 1.7+ @@ -886,7 +886,7 @@ function longdesc() { var currentRequests: JQuery.PlainObject = {}; $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - if (( options).abortOnRetry) { + if ((options as any).abortOnRetry) { if (currentRequests[options.url!]) { currentRequests[options.url!].abort(); } @@ -1297,7 +1297,7 @@ function longdesc() { return $.css(elem, borderRadius!); }, set: function(elem, value) { - ( elem.style)[borderRadius!] = value; + (elem.style as any)[borderRadius!] = value; }, }; } @@ -2016,7 +2016,7 @@ function longdesc() { } function on_3() { - function greet(event: JQuery.Event) { + function greet(event: JQuery.TriggeredEvent) { alert('Hello ' + event.data.name); } diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index 4e0982ca24..c712187559 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -41,6 +41,8 @@ export class Request implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + thenCall(callback?: (err: Error, records: T) => void): Query; readonly [Symbol.toStringTag]: 'Promise'; diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index 15f0fe249e..c6aec12e7e 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -124,6 +124,8 @@ export class AsyncResultLocator extends EventEmitter implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + readonly [Symbol.toStringTag]: "Promise"; } diff --git a/types/kendo-ui/tslint.json b/types/kendo-ui/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/kendo-ui/tslint.json +++ b/types/kendo-ui/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/koa-log/index.d.ts b/types/koa-log/index.d.ts new file mode 100644 index 0000000000..3e97ea155f --- /dev/null +++ b/types/koa-log/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for koa-log 2.1 +// Project: https://github.com/vicanso/koa-log#readme +// Definitions by: Uladzimir Havenchyk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from 'koa'; + +declare function koaLog(type: string): Koa.Middleware; + +declare namespace koaLog { + namespace morgan { + function cookie(ctx: Koa.BaseContext, key: string): string; + + function date(ctx: Koa.BaseContext, format: string): string; + + function format(name: string): string; + + function length(ctx: Koa.BaseContext): number | undefined; + + function method(ctx: Koa.BaseContext): string; + + function referrer(ctx: Koa.BaseContext): string; + + function status(ctx: Koa.BaseContext): number; + + function token(name: string, fn: (ctx: Koa.BaseContext) => string): void; + + function url(ctx: Koa.BaseContext): string; + } +} + +export = koaLog; diff --git a/types/koa-log/koa-log-tests.ts b/types/koa-log/koa-log-tests.ts new file mode 100644 index 0000000000..070ceabfe9 --- /dev/null +++ b/types/koa-log/koa-log-tests.ts @@ -0,0 +1,10 @@ +import Koa = require('koa'); +import koaLogger = require('koa-log'); + +koaLogger.morgan.token('request-body', (ctx: Koa.BaseContext) => JSON.stringify(ctx.request.body)); +koaLogger.morgan.token('response-body', (ctx: Koa.BaseContext) => JSON.stringify(ctx.body)); + +const app = new Koa(); +app.use( + koaLogger(':status :method :url took :response-time ms :request-body :response-body') +); diff --git a/types/koa-log/tsconfig.json b/types/koa-log/tsconfig.json new file mode 100644 index 0000000000..2e32dbc373 --- /dev/null +++ b/types/koa-log/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", + "koa-log-tests.ts" + ] +} diff --git a/types/koa-log/tslint.json b/types/koa-log/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-log/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts new file mode 100644 index 0000000000..2b3fd1da28 --- /dev/null +++ b/types/list-stream/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for list-stream 1.0 +// Project: https://github.com/rvagg/list-stream +// Definitions by: Christian Sporer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +import { Duplex, DuplexOptions } from "stream"; + +interface ListStreamMethod { + (callback?: (err: Error, data: any[]) => void): ListStream; + (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; +} + +interface ListStreamConstructor extends ListStreamMethod { + new(callback?: (err: Error, data: any[]) => void): ListStream; + new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + + obj: ListStreamMethod; +} + +declare let ListStream: ListStreamConstructor; + +interface ListStream extends Duplex { + append(chunk: any): void; + duplicate(): ListStream; + end(): void; + get(index: number): any; + length: number; +} + +export = ListStream; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts new file mode 100644 index 0000000000..8b6ae25435 --- /dev/null +++ b/types/list-stream/list-stream-tests.ts @@ -0,0 +1,2 @@ +import "./test/import-tests"; +import "./test/require-tests"; diff --git a/types/list-stream/test/import-tests.ts b/types/list-stream/test/import-tests.ts new file mode 100644 index 0000000000..3648097ad6 --- /dev/null +++ b/types/list-stream/test/import-tests.ts @@ -0,0 +1,54 @@ +import ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/test/require-tests.ts b/types/list-stream/test/require-tests.ts new file mode 100644 index 0000000000..8966e1e5a3 --- /dev/null +++ b/types/list-stream/test/require-tests.ts @@ -0,0 +1,54 @@ +import ListStream = require("list-stream"); + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json new file mode 100644 index 0000000000..00fe9a2e23 --- /dev/null +++ b/types/list-stream/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "test/import-tests.ts", + "test/require-tests.ts", + "index.d.ts", + "list-stream-tests.ts" + ] +} diff --git a/types/list-stream/tslint.json b/types/list-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/list-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ng-cordova/tslint.json b/types/ng-cordova/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-cordova/tslint.json +++ b/types/ng-cordova/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-flow/tslint.json b/types/ng-flow/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-flow/tslint.json +++ b/types/ng-flow/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-grid/tslint.json b/types/ng-grid/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-grid/tslint.json +++ b/types/ng-grid/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/oauth2orize/index.d.ts b/types/oauth2orize/index.d.ts index 798030c7d2..b3a62d01e4 100644 --- a/types/oauth2orize/index.d.ts +++ b/types/oauth2orize/index.d.ts @@ -99,6 +99,7 @@ export class OAuth2Server { decision(options: DecisionOptions, parse: DecisionParseFunction): MiddlewareFunction; decision(parse: DecisionParseFunction): MiddlewareFunction; + decision(): MiddlewareFunction; token(options?: any): MiddlewareFunction; diff --git a/types/openui5/tslint.json b/types/openui5/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/openui5/tslint.json +++ b/types/openui5/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/puppeteer/DeviceDescriptors.d.ts b/types/puppeteer/DeviceDescriptors.d.ts new file mode 100644 index 0000000000..e457748fda --- /dev/null +++ b/types/puppeteer/DeviceDescriptors.d.ts @@ -0,0 +1,22 @@ +declare namespace devices { + interface Viewport { + width: number; + height: number; + deviceScaleFactor: number; + isMobile: boolean; + hasTouch: boolean; + isLandscape: boolean; + } + + interface Device { + name: string; + userAgent: string; + viewport: Viewport; + } +} + +declare const devices: { + [key: string]: devices.Device; +}; + +export = devices; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index ff05cc4de0..2051603f69 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -2044,7 +2044,7 @@ export interface BrowserOptions { * @default false */ isLandscape?: boolean; - }; + } | null; /** * Slows down Puppeteer operations by the specified amount of milliseconds. * Useful so that you can see what is going on. diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index b708f1bc0c..e2a559d8e6 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -1,5 +1,6 @@ import * as puppeteer from "puppeteer"; import { TimeoutError } from "puppeteer/Errors"; +import * as Devices from "puppeteer/DeviceDescriptors"; // Accessibility @@ -118,6 +119,7 @@ puppeteer.launch().then(async browser => { }); await page.emulateMedia("screen"); + await page.emulate(Devices['test']); await page.pdf({ path: "page.pdf" }); await page.setRequestInterception(true); @@ -200,6 +202,13 @@ puppeteer.launch().then(async browser => { browser.close(); })(); +// Launching with default viewport disabled +(async () => { + await puppeteer.launch({ + defaultViewport: null + }); +})(); + // Test v0.12 features (async () => { const browser = await puppeteer.launch({ diff --git a/types/puppeteer/tsconfig.json b/types/puppeteer/tsconfig.json index f253604e14..57b57e65aa 100644 --- a/types/puppeteer/tsconfig.json +++ b/types/puppeteer/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "Errors.d.ts", + "DeviceDescriptors.d.ts", "index.d.ts", "puppeteer-tests.ts" ] diff --git a/types/q/tslint.json b/types/q/tslint.json index 0bded8e292..4af8abbc8d 100644 --- a/types/q/tslint.json +++ b/types/q/tslint.json @@ -7,6 +7,7 @@ "no-unnecessary-type-assertion": false, "prefer-declare-function": false, "strict-export-declare-modifiers": false, - "unified-signatures": false + "unified-signatures": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/q/v0/tslint.json b/types/q/v0/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/q/v0/tslint.json +++ b/types/q/v0/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/qtip2/tslint.json b/types/qtip2/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/qtip2/tslint.json +++ b/types/qtip2/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/rabbitmq-schema/index.d.ts b/types/rabbitmq-schema/index.d.ts new file mode 100644 index 0000000000..3c607115ab --- /dev/null +++ b/types/rabbitmq-schema/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for rabbitmq-schema 2.0 +// Project: https://github.com/tjmehta/rabbitmq-schema +// Definitions by: Alex Duka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface Binding { + destination: Exchange | Queue; + source: Exchange; + args?: object; + routingPattern?: string; +} + +interface TopicBinding extends Binding { + routingPattern: string; +} + +interface DirectBinding extends Binding { + routingPattern: string; +} + +interface Topology { + options?: object; +} + +interface Exchange extends Topology { + exchange: string; + type: string; + bindings: Binding[]; +} + +interface FanoutExchange extends Exchange { + type: 'fanout'; +} + +interface TopicExchange extends Exchange { + type: 'topic'; + bindings: TopicBinding[]; +} + +interface DirectExchange extends Exchange { + type: 'direct'; + bindings: DirectBinding[]; +} + +interface Queue extends Topology { + queue: string; + messageSchema: object; +} + +declare class RabbitMQSchema { + constructor(schema: Topology | Topology[], parentPath?: string); + + getExchanges(): Exchange[]; + + getBindings(): Binding[]; + + getQueues(): Queue[]; + + getDirectBindings(): DirectBinding[]; + + validate(schema: Topology | Topology[], parentPath?: string): void; + + validateMessage(exchangeName: string, routingPattern: string, message: T): T; + + getQueueByName(name: string): Queue | void; + + getExchangeByName(name: string): Exchange | void; +} + +export = RabbitMQSchema; diff --git a/types/rabbitmq-schema/rabbitmq-schema-tests.ts b/types/rabbitmq-schema/rabbitmq-schema-tests.ts new file mode 100644 index 0000000000..067c9c3c5a --- /dev/null +++ b/types/rabbitmq-schema/rabbitmq-schema-tests.ts @@ -0,0 +1,16 @@ +import RabbitMqSchema = require('rabbitmq-schema'); + +const topology = {}; + +const rabbitSchema = new RabbitMqSchema({}, ''); + +rabbitSchema.getExchanges(); +rabbitSchema.getBindings(); +rabbitSchema.getQueues(); +rabbitSchema.getDirectBindings(); + +rabbitSchema.getQueueByName('images.jpeg.get'); +rabbitSchema.getExchangeByName('images'); + +rabbitSchema.validate(topology); +rabbitSchema.validateMessage('images', 'images.jpeg.get', {testMsg: 'ok'}); diff --git a/types/rabbitmq-schema/tsconfig.json b/types/rabbitmq-schema/tsconfig.json new file mode 100644 index 0000000000..81e519bb47 --- /dev/null +++ b/types/rabbitmq-schema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rabbitmq-schema-tests.ts" + ] +} diff --git a/types/rabbitmq-schema/tslint.json b/types/rabbitmq-schema/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rabbitmq-schema/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-facebook-login/index.d.ts b/types/react-facebook-login/index.d.ts index 82672660a8..419761974e 100644 --- a/types/react-facebook-login/index.d.ts +++ b/types/react-facebook-login/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-facebook-login 3.6 +// Type definitions for react-facebook-login 4.1 // Project: https://github.com/keppelen/react-facebook-login // Definitions by: Alexandre Paré , Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ import * as React from "react"; -interface ReactFacebookLoginProps { +export interface ReactFacebookLoginProps { appId: string; callback(userInfo: ReactFacebookLoginInfo): void; onFailure?(response: ReactFacebookFailureResponse): void; @@ -18,7 +18,7 @@ interface ReactFacebookLoginProps { cssClass?: string; disableMobileRedirect?: boolean; fields?: string; - icon?: string | React.ReactNode; + icon?: React.ReactNode; isDisabled?: boolean; language?: string; onClick?(event: React.MouseEvent): void; @@ -32,6 +32,10 @@ interface ReactFacebookLoginProps { xfbml?: boolean; isMobile?: boolean; tag?: Node | React.Component; + returnScopes?: boolean; + state?: string; + authType?: string; + responseType?: string; } export interface ReactFacebookFailureResponse { @@ -45,14 +49,12 @@ export interface ReactFacebookLoginInfo { email?: string; } -interface ReactFacebookLoginState { +export interface ReactFacebookLoginState { isSdkLoaded?: boolean; isProcessing?: boolean; } -declare class ReactFacebookLogin extends React.Component< +export default class ReactFacebookLogin extends React.Component< ReactFacebookLoginProps, ReactFacebookLoginState > {} - -export default ReactFacebookLogin; diff --git a/types/react-facebook-login/react-facebook-login-tests.tsx b/types/react-facebook-login/react-facebook-login-tests.tsx index d7b2ebcde8..a52c955596 100644 --- a/types/react-facebook-login/react-facebook-login-tests.tsx +++ b/types/react-facebook-login/react-facebook-login-tests.tsx @@ -1,7 +1,6 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; - -import FacebookLogin, { ReactFacebookLoginInfo, ReactFacebookFailureResponse } from 'react-facebook-login'; +import FacebookLogin, { ReactFacebookFailureResponse, ReactFacebookLoginInfo, ReactFacebookLoginProps } from 'react-facebook-login'; const responseFacebook = (response: ReactFacebookLoginInfo) => { console.log(response); @@ -106,3 +105,9 @@ class MyComponent2 extends React.Component { ); } } + +type FacebookLoginWrapperProps = ReactFacebookLoginProps & { className?: string }; + +export const FacebookLoginWrapper = ({ className, ...props }: FacebookLoginWrapperProps) => ( + +); diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 34e3cbcb88..9a8957b56b 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -11,6 +11,7 @@ // Paul Melnikow // Harry Cruse // Andrew Palugniok +// Robert Stigsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -45,6 +46,7 @@ export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouett export type LineType = 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type IfOverflowType = 'hidden' | 'visible' | 'discard' | 'extendDomain'; export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; export type PickedCSSStyleDeclarationKeys = @@ -363,6 +365,7 @@ export interface LegendPayload { value: any; id: any; type: LegendType; + color?: string; } export type BBoxUpdateCallback = (box: { width: number; height: number; }) => void; @@ -634,6 +637,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; + ifOverflow?: IfOverflowType; x1?: number | string; x2?: number | string; y1?: number | string; @@ -657,6 +661,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; diff --git a/types/rechoir/index.d.ts b/types/rechoir/index.d.ts new file mode 100644 index 0000000000..2cb3bbb7ab --- /dev/null +++ b/types/rechoir/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rechoir 0.6 +// Project: https://github.com/tkellen/node-rechoir +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Extensions } from 'interpret'; + +export function prepare( + config: Extensions, + filepath: string, + requireFrom?: string +): true | Attempt[]; + +export interface Attempt { + moduleName: string; + module: any; + error: Error | null; +} diff --git a/types/rechoir/rechoir-tests.ts b/types/rechoir/rechoir-tests.ts new file mode 100644 index 0000000000..de4b18c74f --- /dev/null +++ b/types/rechoir/rechoir-tests.ts @@ -0,0 +1,6 @@ +import { extensions as config } from 'interpret'; +import { prepare } from 'rechoir'; + +// $ExpectType true | Attempt[] +prepare(config, './test/fixtures/test.coffee'); +prepare(config, './test/fixtures/test.coffee', './'); diff --git a/types/rechoir/tsconfig.json b/types/rechoir/tsconfig.json new file mode 100644 index 0000000000..03a006d997 --- /dev/null +++ b/types/rechoir/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", + "rechoir-tests.ts" + ] +} diff --git a/types/rechoir/tslint.json b/types/rechoir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rechoir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sammy/tslint.json b/types/sammy/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/sammy/tslint.json +++ b/types/sammy/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/sc-auth/index.d.ts b/types/sc-auth/index.d.ts new file mode 100644 index 0000000000..84f92bf674 --- /dev/null +++ b/types/sc-auth/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for sc-auth 5.0 +// Project: https://github.com/SocketCluster/sc-auth +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { VerifyOptions, VerifyCallback, Secret, SignCallback, SignOptions } from "jsonwebtoken"; + +export interface SCAuthEngine { + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} + +export class AuthEngine implements SCAuthEngine { + constructor(); + + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} diff --git a/types/sc-auth/sc-auth-tests.ts b/types/sc-auth/sc-auth-tests.ts new file mode 100644 index 0000000000..4fa57d3391 --- /dev/null +++ b/types/sc-auth/sc-auth-tests.ts @@ -0,0 +1,102 @@ +/** + * This mostly delegates to jwt, so using its tests as base + */ + +import scAuth = require("sc-auth"); +import fs = require("fs"); + +let signedToken = ""; +let cert: Buffer; + +interface TestObject { + foo: string; +} + +const testObject = { foo: "bar" }; + +const authEngine = new scAuth.AuthEngine(); + +// sign with default (HMAC SHA256) +authEngine.signToken(testObject, "shhhhh"); + +// sign with default (HMAC SHA256) and single audience +authEngine.signToken(testObject, "shhhhh", { audience: "theAudience" }); + +// sign with default (HMAC SHA256) and multiple audiences +authEngine.signToken(testObject, "shhhhh", { + audience: ["audience1", "audience2"] +}); + +// sign with default (HMAC SHA256) and a keyid +authEngine.signToken(testObject, "shhhhh", { keyid: "theKeyId" }); + +// sign with RSA SHA256 +cert = fs.readFileSync("private.key"); // get private key +authEngine.signToken(testObject, cert, { algorithm: "RS256" }); + +// sign with encrypted RSA SHA256 private key (only PEM encoding is supported) +const privKey: Buffer = fs.readFileSync("encrypted_private.key"); // get private key +const secret = { key: privKey.toString(), passphrase: "keypwd" }; +authEngine.signToken(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case + +// sign asynchronously +authEngine.signToken(testObject, cert, { algorithm: "RS256" }, (err, token) => { + signedToken = token; +}); + +// verify a token symmetric +authEngine.verifyToken(signedToken, "shhhhh", {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// use external time for verifying +authEngine.verifyToken(signedToken, "shhhhh", { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// invalid token +authEngine.verifyToken(signedToken, "wrong-secret", {}, (err, decoded) => { + console.log(err); + + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify audience +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo" }, (err, decoded) => { + // if audience mismatch, err == invalid audience + console.log(err); +}); + +// verify issuer +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo", issuer: "urn:issuer" }, (err, decoded) => { + // if issuer mismatch, err == invalid issuer + console.log(err); +}); + +// verify algorithm +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { algorithms: ["RS256"] }, (err, decoded) => { + // if algorithm mismatch, err == invalid algorithm + console.log(err); +}); + +// verify without expiration check +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { ignoreExpiration: true }, (err, decoded) => { + // if ignoreExpration == false and token is expired, err == expired token + console.log(err); +}); diff --git a/types/sc-auth/tsconfig.json b/types/sc-auth/tsconfig.json new file mode 100644 index 0000000000..5c8e3a1e19 --- /dev/null +++ b/types/sc-auth/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", + "sc-auth-tests.ts" + ] +} diff --git a/types/sc-auth/tslint.json b/types/sc-auth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sc-auth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-broker-cluster/clientcluster.d.ts b/types/sc-broker-cluster/clientcluster.d.ts new file mode 100644 index 0000000000..f2234df6ab --- /dev/null +++ b/types/sc-broker-cluster/clientcluster.d.ts @@ -0,0 +1,10 @@ +import { EventEmitter } from "events"; +import { SCBrokerClient } from "sc-broker"; +import { mapperFunction } from "."; + +export class ClientCluster extends EventEmitter { + constructor(clients: SCBrokerClient[]); + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; +} diff --git a/types/sc-broker-cluster/index.d.ts b/types/sc-broker-cluster/index.d.ts new file mode 100644 index 0000000000..9314acda82 --- /dev/null +++ b/types/sc-broker-cluster/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for sc-broker-cluster 6.1 +// Project: https://github.com/SocketCluster/sc-broker-cluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServerSocket, SCServer } from "socketcluster-server"; +import { BrokerStartInfo, BrokerExitInfo } from "socketcluster"; +import { SpliceOptions, QueryOptions } from "sc-broker"; +import { SCChannel } from "sc-channel"; +import { EventEmitter } from "events"; +import { AsyncResultArrayCallback } from "async"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys } from "expirymanager"; +import { ClientCluster } from "./clientcluster"; + +export class AbstractDataClient extends EventEmitter { + constructor(dataClient: ClientCluster); + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; +} + +export type handlerFunction = (data: any) => void; + +export type mapperFunction = (keyChain: KeyChain, method: string, clientIds: number[]) => number | number[]; + +/** + * The exchange object is a top-level SCBrokerClient which lets you publish events and manipulate data within your brokers - It represents a cluster of 1 or more brokers. + */ +export class SCExchange extends AbstractDataClient { + constructor(privateClientCluster: ClientCluster, publicClientCluster: ClientCluster, ioClusterClient: Client); + + send(data: any, mapIndex: number | string | string[] | null, callback?: (err?: Error) => void): void; + + publish(channelName: string, data: any, callback: (err?: Error) => void): void; + + subscribe(channelName: string): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string): SCChannel; + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + watch(channelName: string, handler: handlerFunction): void; + unwatch(channelName: string, handler?: handlerFunction): void; + watchers(channelName: string): handlerFunction[]; + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; + + map(keyChain: KeyChain, method: string): { type: string; targets: Client[] }; + + destroy(): void; +} + +export interface SCBrokerClusterServerOptions { + brokers: string[]; + debug?: boolean; + inspect?: boolean; + instanceId?: string; + secretKey?: string; + expiryAccuracy?: number; + downgradeToUser: number | string; + appBrokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + brokerOptions?: SCServer.SCServerOptions; +} + +export class Server extends EventEmitter { + constructor(options: SCBrokerClusterServerOptions); + + on(event: "brokerStart", listener: (brokerInfo: BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: BrokerExitInfo) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err?: Error) => void): this; + + sendToBroker(brokerId: string, data: any, callback: (err: Error | null, data: any) => void): void; + killBrokers(): void; + destroy(): void; +} + +export interface SCBrokerClusterClientOptions { + brokers: string[]; + secretKey?: string; + pubSubBatchDuration?: number; + connectRetryErrorThreshold: number; +} + +export interface MessagePacket { + channel: string; + data: any; +} + +export class Client extends EventEmitter { + constructor(options: SCBrokerClusterClientOptions); + + exchange(): SCExchange; + + options: SCBrokerClusterClientOptions; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "message", listener: (packet: MessagePacket) => void): this; + + destroy(callback: AsyncResultArrayCallback): void; + + subscribe(channel: string, callback: (err?: Error) => void): void; + unsubscribe(channel: string, callback: () => void): void; + unsubscribeAll(callback: () => void): void; + isSubscribed(channel: string, includePending: boolean): boolean; + + subscribeSocket(socket: SCServerSocket, channel: string, callback?: (err?: Error) => void): void; + unsubscribeSocket(socket: SCServerSocket, channel: string, callback?: () => void): void; + + setSCServer(scServer: SCServer): void; +} diff --git a/types/sc-broker-cluster/sc-broker-cluster-tests.ts b/types/sc-broker-cluster/sc-broker-cluster-tests.ts new file mode 100644 index 0000000000..0f5c274248 --- /dev/null +++ b/types/sc-broker-cluster/sc-broker-cluster-tests.ts @@ -0,0 +1,29 @@ +import { Client } from "sc-broker-cluster"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import WebSocket = require("ws"); + +const client = new Client({ + brokers: [], + secretKey: "secretKey", + pubSubBatchDuration: 100, + connectRetryErrorThreshold: 5 +}); + +client.on("error", err => {}); +client.on("warning", err => {}); + +const exchange = client.exchange(); + +const scServer = new SCServer(); +client.setSCServer(scServer); + +client.once("ready", () => {}); + +const wsSocket = new WebSocket("address"); +const socket = new SCServerSocket("id", scServer, wsSocket); +client.subscribeSocket(socket, "channelName", err => {}); + +client.unsubscribeSocket(socket, "channelName"); + +const data: any = {}; +exchange.publish("channelName", data, err => {}); diff --git a/types/sc-broker-cluster/scbroker.d.ts b/types/sc-broker-cluster/scbroker.d.ts new file mode 100644 index 0000000000..a7ddb7db87 --- /dev/null +++ b/types/sc-broker-cluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker/scbroker"); + +export = SCBroker; diff --git a/types/sc-broker-cluster/tsconfig.json b/types/sc-broker-cluster/tsconfig.json new file mode 100644 index 0000000000..8ace8fc9dc --- /dev/null +++ b/types/sc-broker-cluster/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clientcluster.d.ts", + "scbroker.d.ts", + "sc-broker-cluster-tests.ts" + ] +} diff --git a/types/sc-broker-cluster/tslint.json b/types/sc-broker-cluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker-cluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-broker/index.d.ts b/types/sc-broker/index.d.ts new file mode 100644 index 0000000000..ccb83e880e --- /dev/null +++ b/types/sc-broker/index.d.ts @@ -0,0 +1,165 @@ +// Type definitions for sc-broker 5.1 +// Project: https://github.com/SocketCluster/sc-broker +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServer } from "socketcluster-server"; +import { WorkerExitInfo } from "socketcluster"; +import { EventEmitter } from "events"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys, Key } from "expirymanager"; + +export interface SCBrokerServerOptions { + id?: string; + instanceId?: string; + debug?: boolean; + inspect?: boolean; + socketPath?: string; + port?: number; + expiryAccuracy?: number; + downgradeToUser: number | string; + brokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + secretKey?: string; + brokerOptions?: SCServer.SCServerOptions; +} + +export interface SCBrokerServer extends EventEmitter { + options: SCBrokerServerOptions; + socketPath?: string; + port?: number; + ipcAckTimeout: number; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "exit", listener: (data: WorkerExitInfo) => void): this; + + sendToBroker(data: any, callback?: (err: Error | null, data: any, brokerId: string) => void): void; +} + +export function createServer(options?: SCBrokerServerOptions): SCBrokerServer; + +export interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; +} + +export interface SCBrokerClientOptions { + secretKey?: string; + timeout?: number; + socketPath?: string; + port?: number; + host?: string; + autoReconnect?: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold?: number; + pubSubBatchDuration?: number; +} + +export interface QueryOptions { + baseKey?: KeyChain; + noAck?: boolean; + data?: any; +} + +export interface SpliceOptions { + index?: number; + count?: number; + items?: any[]; + getValue?: boolean; + noAck?: boolean; +} + +export interface SCBrokerClient extends EventEmitter { + readonly CONNECTED: "connected"; + readonly CONNECTING: "connecting"; + readonly DISCONNECTED: "disconnected"; + + socketPath?: string; + port?: number; + host?: string; + autoReconnect: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold: number; + state: "connected" | "connecting" | "disconnected"; + connectAttempts: number; + pendingReconnect: boolean; + pendingReconnectTimeout: number | null; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "message", listener: (channel: string, data: any) => void): this; + on(event: "subscribeFail", listener: (err: Error | null, channel: string) => void): this; + on(event: "subscribe", listener: (channel: string) => void): this; + on(event: "unsubscribe", listener: () => void): this; + + isConnected(): boolean; + + subscribe(channel: string, ackCallback: (err?: Error) => void, force?: boolean): void; + unsubscribe(channel: string, ackCallback: (err?: Error) => void): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channel: string, includePending?: boolean): boolean; + + publish(channel: string, data: any, callback: (err?: Error) => void): void; + + send(data: any, callback: (err?: Error) => void): void; + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + getExpiry(key: Key, callback?: (err?: Error) => void): number; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + concat(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + concat(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + query(query: (datamap: FlexiMap) => void, data?: any, callback?: (err: Error | null, data: any) => void): void; + query(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + end(callback: (err?: Error) => void): void; +} + +export function createClient(options?: SCBrokerClientOptions): SCBrokerClient; diff --git a/types/sc-broker/sc-broker-tests.ts b/types/sc-broker/sc-broker-tests.ts new file mode 100644 index 0000000000..201ff10a27 --- /dev/null +++ b/types/sc-broker/sc-broker-tests.ts @@ -0,0 +1,58 @@ +import { SCServer, SCServerSocket } from "socketcluster-server"; +import SCBroker = require("sc-broker/scbroker"); +import { FlexiMap } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +//////////////////////////////////////////////////// +/// SCBroker tests +//////////////////////////////////////////////////// + +const options: SCServer.SCServerOptions = { port: 80 }; + +let scBroker = new SCBroker(); +scBroker = new SCBroker(options); +scBroker.options = { environment: "prod" }; + +const id: number = scBroker.id; +const instanceId: number = scBroker.instanceId; +const dataMap: FlexiMap = scBroker.dataMap; +const dataExpirer: ExpiryManager = scBroker.dataExpirer; +const subscriptions = scBroker.subscriptions; + +const socket: SCServerSocket = subscriptions[1]["test"]; + +scBroker.on("subscribe", channel => { + const subscribeChannel: string = channel; +}); +scBroker.on("unsubscribe", channel => { + const unsubscribeChannel: string = channel; +}); +scBroker.on("publish", (channel, data) => { + const publishChannel: string = channel; + const publishData: any = data; +}); +scBroker.on("masterMessage", (data, masterMessageResponse) => { + const masterMessageData: any = data; + masterMessageResponse(null, "test"); + masterMessageResponse(new Error(), null); +}); + +scBroker.publish("testChannel", 123); + +scBroker.exec(dataMap => { + dataMap.set(["main", "message"], "Message"); + return dataMap.get(["main"]); +}); + +scBroker.sendToMaster("data"); +scBroker.sendToMaster(123, (err, response) => { + if (!err) { + const answer = response; + } +}); + +class MyBroker extends SCBroker { + run() { + this.on("subscribe", channel => {}); + } +} diff --git a/types/sc-broker/scbroker.d.ts b/types/sc-broker/scbroker.d.ts new file mode 100644 index 0000000000..057b983adf --- /dev/null +++ b/types/sc-broker/scbroker.d.ts @@ -0,0 +1,32 @@ +import { EventEmitter } from "events"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { FlexiMap, KeyChain } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +export = SCBroker; + +interface Subscriptions { + [socketId: number]: { + [channel: string]: SCServerSocket; + }; +} + +declare class SCBroker extends EventEmitter { + id: number; + options: SCServer.SCServerOptions; + instanceId: number; + dataMap: FlexiMap; + dataExpirer: ExpiryManager; + subscriptions: Subscriptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "subscribe" | "unsubscribe", listener: (channel: string) => void): this; + on(event: "publish", listener: (channel: string, data: any) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; + + publish(channel: string, message: any): void; + run(): void; + exec(query: (dataMap: FlexiMap, dataExpirer: ExpiryManager, subscriptions: Subscriptions) => any, baseKey?: KeyChain): any; + sendToMaster(data: any, callback?: (err: Error | null, responseData: any) => void): void; +} diff --git a/types/sc-broker/tsconfig.json b/types/sc-broker/tsconfig.json new file mode 100644 index 0000000000..6adfe07a5b --- /dev/null +++ b/types/sc-broker/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scbroker.d.ts", + "sc-broker-tests.ts" + ] +} diff --git a/types/sc-broker/tslint.json b/types/sc-broker/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-channel/index.d.ts b/types/sc-channel/index.d.ts new file mode 100644 index 0000000000..034723c0ba --- /dev/null +++ b/types/sc-channel/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for sc-channel 1.2 +// Project: https://github.com/SocketCluster/sc-channel +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Emitter = require("component-emitter"); +import { SCExchange, handlerFunction } from "sc-broker-cluster"; + +export interface SCChannelOptions { + waitForAuth?: boolean; + batch?: boolean; + data?: any; +} + +export class SCChannel extends Emitter { + readonly PENDING: "pending"; + readonly SUBSCRIBED: "subscribed"; + readonly UNSUBSCRIBED: "unsubscribed"; + + name: string; + state: ChannelState; + waitForAuth: boolean; + batch: boolean; + data: any; + + constructor(name: string, client: SCExchange, options?: SCChannelOptions); + + setOptions(options?: SCChannelOptions): void; + getState(): "pending" | "subscribed" | "unsubscribed"; + + subscribe(options?: any): void; + unsubscribe(): void; + isSubscribed(includePending?: boolean): boolean; + + publish(data: any, callback?: (err?: Error) => void): void; + + watch(handler: handlerFunction): void; + unwatch(handler?: handlerFunction): void; + watchers(): handlerFunction[]; + + destroy(): void; +} + +export type ChannelState = "pending" | "subscribed" | "unsubscribed"; diff --git a/types/sc-channel/sc-channel-tests.ts b/types/sc-channel/sc-channel-tests.ts new file mode 100644 index 0000000000..bfc90cee12 --- /dev/null +++ b/types/sc-channel/sc-channel-tests.ts @@ -0,0 +1,33 @@ +import { SCChannel, SCChannelOptions } from "sc-channel"; +import { handlerFunction, Client, SCBrokerClusterClientOptions } from "sc-broker-cluster"; + +const clientOptions: SCBrokerClusterClientOptions = { brokers: [], connectRetryErrorThreshold: 0 }; +const client = new Client(clientOptions); + +let channel = new SCChannel("channelName", client.exchange()); +const channelOptions: SCChannelOptions = {}; +channel = new SCChannel("channelName", client.exchange(), channelOptions); + +channel.state = channel.PENDING; +channel.state = channel.SUBSCRIBED; +channel.state = channel.UNSUBSCRIBED; + +const channelName: string = channel.name; + +const handler: handlerFunction = () => { }; + +channel.watch(handler); +channel.unwatch(); + +channel.subscribe(); +channel.subscribe(channelOptions); +channel.unsubscribe(); + +const data: any = channel.data; + +channel.emit("subscribe", channelName); +channel.emit("unsubscribe", channelName); + +channel.setOptions(channelOptions); + +channel.publish(data); diff --git a/types/sc-channel/tsconfig.json b/types/sc-channel/tsconfig.json new file mode 100644 index 0000000000..c5c5ce5f14 --- /dev/null +++ b/types/sc-channel/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", + "sc-channel-tests.ts" + ] +} diff --git a/types/sc-channel/tslint.json b/types/sc-channel/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-channel/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/segment-analytics/tslint.json b/types/segment-analytics/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/segment-analytics/tslint.json +++ b/types/segment-analytics/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/selectize/tslint.json b/types/selectize/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/selectize/tslint.json +++ b/types/selectize/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts index 8e5b2c20b8..1f3294c8d6 100644 --- a/types/semantic-ui-form/global.d.ts +++ b/types/semantic-ui-form/global.d.ts @@ -212,7 +212,7 @@ declare namespace SemanticUI { /** * Callback if a form is all valid */ - onSuccess(this: JQuery, event: JQuery.Event, fields: any): void; + onSuccess(this: JQuery, event: JQuery.TriggeredEvent, fields: any): void; /** * Callback if any form field is invalid */ diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts index f17ca33112..d481cb00ad 100644 --- a/types/semantic-ui-form/semantic-ui-form-tests.ts +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -144,7 +144,7 @@ function test_form() { }, onSuccess(event, fields) { this; // $ExpectType JQuery - event; // $ExpectType Event + event; // $ExpectType TriggeredEvent fields; // $ExpectType any }, onFailure(formErrors, fields) { diff --git a/types/sharepoint/sharepoint-tests.ts b/types/sharepoint/sharepoint-tests.ts index e76536cd18..d3bbe1f808 100644 --- a/types/sharepoint/sharepoint-tests.ts +++ b/types/sharepoint/sharepoint-tests.ts @@ -2038,7 +2038,7 @@ namespace _ { // do is retrieve a reference to the term set with the same ID as the div, and // then add the term that belong to that term set under the div that was clicked. - function showTerms(event: JQuery.Event, groupID: SP.Guid, termSetID: SP.Guid) { + function showTerms(event: JQuery.ClickEvent, groupID: SP.Guid, termSetID: SP.Guid) { // First, cancel the bubble so that the group div click handler does not also fire // because that removes all term set divs and we don't want that here. event.originalEvent.cancelBubble = true; diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts index 65466ee840..7ca7c2eb98 100644 --- a/types/sip.js/index.d.ts +++ b/types/sip.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sip.js 0.8 +// Type definitions for sip.js 0.9 // Project: http://sipjs.com // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -75,6 +75,8 @@ export namespace C { export type DescriptionModifier = (description: RTCSessionDescription) => Promise; export interface SessionDescriptionHandler { + peerConnection: any; + getDescription(options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; setDescription(sessionDescription: string, options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; hasDescription: (contentType: string) => boolean; @@ -128,11 +130,16 @@ export interface Session { on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel' | string, callback: () => void): void; - on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'cancel' | 'directionChanged' | 'trackAdded' | 'SessionDescriptionHandler-created' | string, callback: () => void): void; + on(name: 'replaced' | 'reinvite', callback: (newSession: Session) => void): void; on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; + on(name: 'refer' | 'bye' | 'notify', callback: (request: IncomingRequest) => void): void; + on(name: 'referRequested', callback: (request: ClientContext | ServerContext) => void): void; + + /* these come from the ClientContext that is on the session somehow */ + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } export namespace Session { @@ -164,7 +171,10 @@ export namespace Session { }; } - interface DTMF extends Object { } + interface DTMF extends Object { + direction: string | 'incoming'; + tone: any; + } interface Muted { audio?: boolean; @@ -364,27 +374,40 @@ export interface Subscription extends ClientContext { } /* Context */ -export interface Context { +export class Context { ua: UA; method: string; request: OutgoingRequest; localIdentity: NameAddrHeader; remoteIdentity: NameAddrHeader; data: {}; +} + +export class ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; + + // This exists on all Context, but I cant make it work right on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; on(name: 'notify', callback: (request: IncomingRequest) => void): void; on(name: string, callback: () => void): void; + + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } -export interface ClientContext extends Context { - cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; -} - -export interface ServerContext extends Context { +export class ServerContext extends Context { progress(options?: Session.ProgressOptions): void; accept(options?: Session.AcceptOptions): void; reject(options?: Session.CommonOptions): void; reply(options?: Session.CommonOptions): void; + + // This exists on all Context, but I cant make it work right + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; + + on(name: 'referRequestAccepted' | 'referRequestRejected' | 'referInviteSent' | 'referProgress' | 'referAccepted' | 'referRejected', + callback: (ServerContext: ServerContext) => void): void; } /* Request */ @@ -398,6 +421,7 @@ export interface OutgoingRequest extends Request { } export interface IncomingResponse extends Request { + reason_phrase: string | 'Ringing'; } export interface IncomingMessage extends Request { diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 5656c58bb3..9ee697cb43 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -7,7 +7,7 @@ // Kalley Powell // Francesco Agnoletto // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as Immutable from "immutable"; @@ -319,7 +319,7 @@ export class Text extends Immutable.Record({}) { addMark(index: number, length: number, mark: Mark): Text; addMarks(index: number, lenght: number, marks: Immutable.Set): Text; getLeaves(decorations?: Range[]): Immutable.List; - getActiveMarksBetweenOffset( + getActiveMarksBetweenOffsets( startOffset: number, endOffset: number ): Immutable.Set; diff --git a/types/socket.io/index.d.ts b/types/socket.io/index.d.ts index f5e6c5fd00..70ef1d6a2c 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -169,7 +169,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socket.io/v1/index.d.ts b/types/socket.io/v1/index.d.ts index 95a9ff1b4f..191680df46 100644 --- a/types/socket.io/v1/index.d.ts +++ b/types/socket.io/v1/index.d.ts @@ -169,7 +169,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socketcluster-client/index.d.ts b/types/socketcluster-client/index.d.ts new file mode 100644 index 0000000000..9c15a45465 --- /dev/null +++ b/types/socketcluster-client/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for socketcluster-client 13.0 +// Project: https://github.com/SocketCluster/socketcluster-client +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCAuthEngine } from "sc-auth"; +import { SCServer } from "socketcluster-server"; + +export import SCClientSocket = require("./lib/scclientsocket"); + +export function create(options?: SCClientSocket.ClientOptions): SCClientSocket; + +/** @deprecated */ +export function connect(options?: SCClientSocket.ClientOptions): SCClientSocket; + +export function destroy(socket: SCClientSocket): void; + +export const clients: { + [id: string]: SCClientSocket; +}; + +export const version: string; diff --git a/types/socketcluster-client/lib/scclientsocket.d.ts b/types/socketcluster-client/lib/scclientsocket.d.ts new file mode 100644 index 0000000000..19552bd102 --- /dev/null +++ b/types/socketcluster-client/lib/scclientsocket.d.ts @@ -0,0 +1,251 @@ +import Emitter = require("component-emitter"); +import { SCServer } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCChannel, SCChannelOptions, ChannelState } from "sc-channel"; +import WebSocket = require("ws"); + +declare class SCClientSocket extends Emitter { + constructor(opts: SCClientSocket.ClientOptions); + + id: string; + + channels: { + [channelName: string]: SCChannel; + }; + + CONNECTING: "connecting"; + OPEN: "open"; + CLOSED: "closed"; + + state: SCClientSocket.States; + getState(): SCClientSocket.States; + + AUTHENTICATED: "authenticated"; + UNAUTHENTICATED: "unauthenticated"; + + authState: SCClientSocket.AuthStates; + + PENDING: "pending"; + + pendingReconnect: boolean; + pendingReconnectTimeout: number; + + getBytesReceived(): number; + + deauthenticate(callback?: (err: Error) => void): void; + + connect(): void; + open(): void; + disconnect(code?: number, data?: string | object): void; + reconnect(code?: number, data?: string | object): void; + destroy(code?: number, data?: string | object): void; + + decodeBase64(encodedString: string): string; + encodeBase64(decodedString: string): string; + + getAuthToken(): object | null; + authToken: object | null; + + getSignedAuthToken(): string | null; + signedAuthToken: string | null; + + // Perform client-initiated authentication by providing an encrypted token string. + authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void; + + decode(message: any): any; + encode(object: any): any; + + send(data: any): void; + + emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void; + + publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void; + + subscribe(channelName: string, options?: SCChannelOptions): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string, options?: SCChannelOptions): SCChannel; + + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + processPendingSubscriptions(): void; + + watch(channelName: string, handler: SCClientSocket.WatcherFunction): void; + unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void; + watchers(channelName: string): SCClientSocket.WatcherFunction[]; + + on(event: "connecting", listener: () => void): this; + on(event: "connect", listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data: string | object) => void): this; + + on(event: "kickOut", listener: (message: string, channelName: string) => void): this; + + on(event: "authenticate", listener: (signedAuthToken: string | null) => void): this; + on(event: "deauthenticate", listener: (oldSignedToken: string | null) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this; + on(event: "removeAuthToken", listener: (oldToken: object | null) => void): this; + + on(event: "subscribe" | "subscribeRequest", listener: (channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "subscribeStateChange", listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void): this; + on(event: "subscribeFail", listener: (err: Error, channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "unsubscribe", listener: (channelName: string) => void): this; + + on(event: "error", listener: (err: Error) => void): this; + + on(event: "raw", listener: (data: any) => void): this; + on(event: "message", listener: (message: WebSocket.Data) => void): this; + + // Implements Emitter interface + + // tslint:disable:ban-types + // tslint:disable:adjacent-overload-signatures + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + off(event?: string, listener?: Function): this; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + // tslint:enable:adjacent-overload-signatures + // tslint:enable:ban-types +} + +export = SCClientSocket; + +declare namespace SCClientSocket { + interface ClientOptions { + host?: string; + + // Defaults to the current host (read from the URL). + hostname?: string; + + // Defaults to false. + secure?: boolean; + + // Defaults to 80 if !secure otherwise defaults to 443. + port?: number; + + // The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'. + path?: string; + + // A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection. + query?: string | { [key: string]: string }; + + // (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided). + ackTimeout?: number; + + // (milliseconds) + connectTimeout?: number; + + // Whether or not to automatically connect the socket as soon as it is created. Default is true. + autoConnect?: boolean; + + // Whether or not to automatically reconnect the socket when it loses the connection. + autoReconnect?: boolean; + + // Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds). + autoReconnectOptions?: AutoReconnectOptions; + + // Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page. + // This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true. + disconnectOnUnload?: boolean; + + // Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side. + // Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so + // you only need to turn it on from the server-side. + perMessageDeflate?: boolean; + + // Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address. + multiplex?: boolean; + + // Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching + // multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all + // subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the + // client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the + // same name which can be configured on the server. + pubSubBatchDuration?: number; + + // Whether or not to add a timestamp to the WebSocket handshake request. + timestampRequests?: boolean; + + // The query parameter name to use to hold the timestamp. + timestampParam?: string; + + // A custom engine to use for storing and loading JWT auth tokens on the client side. + authEngine?: SCAuthEngine | null; + + // The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'. + authTokenName?: string; + + // The type to use to represent binary on the client. Defaults to 'arraybuffer'. + binaryType?: string; + + // Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates. + rejectUnauthorized?: boolean; + + // If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket + // is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false + // by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed, + // then the changed version of that object will be sent out to the server. + cloneData?: boolean; + + // This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on + // connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side. + // See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket + // connection is established (or re-established). + autoSubscribeOnConnect?: boolean; + + // Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded + // once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function. + // The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript + // object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like + // (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately. + // Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the + // same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side + // (see 'setCodecEngine' method here). The default codec engine used by SC is here. + codecEngine?: SCServer.SCCodecEngine | null; + + // A prefix to add to the channel names. + channelPrefix?: string | null; + + subscriptionRetryOptions?: object | null; + } + + interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; + } + + interface AuthStatus { + isAuthenticated: AuthStates; + authError: Error; + } + + interface AuthStateChangeData { + oldState: AuthStates; + newState: AuthStates; + } + + interface ConnectStatus { + id: string; + pingTimeout: number; + isAuthenticated: boolean; + authToken?: object; + authError?: Error; + } + + interface SubscribeStateChangeData { + channel: string; + oldState: ChannelState; + newState: ChannelState; + subscriptionOptions: SCChannelOptions; + } + + type WatcherFunction = (data: any) => void; + type AuthStates = "authenticated" | "unauthenticated"; + type States = "connecting" | "open" | "closed"; +} diff --git a/types/socketcluster-client/socketcluster-client-tests.ts b/types/socketcluster-client/socketcluster-client-tests.ts new file mode 100644 index 0000000000..527385a5eb --- /dev/null +++ b/types/socketcluster-client/socketcluster-client-tests.ts @@ -0,0 +1,75 @@ +// Adapted from README + +import { create, destroy } from "socketcluster-client"; +import { ClientOptions } from "socketcluster-client/lib/scclientsocket"; + +const secureClientOptions: ClientOptions = { + hostname: "securedomain.com", + secure: true, + port: 443, + rejectUnauthorized: false +}; + +let socket = create(secureClientOptions); + +socket.on("connect", () => { + console.log("CONNECTED"); +}); + +// Listen to an event called 'rand' from the server +socket.on("rand", (num: any) => { + console.log("RANDOM: " + num); +}); + +const options: ClientOptions = { + path: "/socketcluster/", + port: 8000, + hostname: "127.0.0.1", + autoConnect: true, + secure: false, + rejectUnauthorized: false, + connectTimeout: 10000, // milliseconds + ackTimeout: 10000, // milliseconds + channelPrefix: null, + disconnectOnUnload: true, + multiplex: true, + autoReconnectOptions: { + initialDelay: 10000, // milliseconds + randomness: 10000, // milliseconds + multiplier: 1.5, // decimal + maxDelay: 60000 // milliseconds + }, + authEngine: null, + codecEngine: null, + subscriptionRetryOptions: {}, + query: { + yourparam: "hello" + } +}; +socket = create(options); + +socket.on("subscribe", channelname => { + console.log("subscribe:" + channelname); +}); + +socket.on("subscribeFail", channelname => { + console.log("subscribeFail:" + channelname); +}); + +socket.on("unsubscribe", channelname => { + console.log("unsubscribe:" + channelname); +}); + +socket.on("subscribeStateChange", data => { + console.log("subscribeStateChange:" + JSON.stringify(data)); +}); + +socket.on("message", data => { + console.log("message:" + data); +}); + +const channels = socket.channels; +const testChannel = channels["test"]; +const state = testChannel.getState(); + +destroy(socket); diff --git a/types/socketcluster-client/tsconfig.json b/types/socketcluster-client/tsconfig.json new file mode 100644 index 0000000000..54fc6ea8af --- /dev/null +++ b/types/socketcluster-client/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/scclientsocket.d.ts", + "socketcluster-client-tests.ts" + ] +} diff --git a/types/socketcluster-client/tslint.json b/types/socketcluster-client/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-client/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster-server/index.d.ts b/types/socketcluster-server/index.d.ts new file mode 100644 index 0000000000..7466d1daed --- /dev/null +++ b/types/socketcluster-server/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for socketcluster-server 13.1 +// Project: https://github.com/SocketCluster/socketcluster-server +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server } from "http"; + +export import SCServer = require("./scserver"); +export import SCServerSocket = require("./scserversocket"); + +export function listen(port?: number, options?: SCServer.SCServerOptions, listeningListener?: () => void): SCServer; +export function listen(port?: number, listeningListener?: () => void): SCServer; + +export function attach(server: Server, options?: SCServer.SCServerOptions): SCServer; diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts new file mode 100644 index 0000000000..a7147aa2dd --- /dev/null +++ b/types/socketcluster-server/scserver.d.ts @@ -0,0 +1,315 @@ +import { EventEmitter } from "events"; +import { Secret } from "jsonwebtoken"; +import { ServerOptions } from "https"; +import { IncomingMessage, Server } from "http"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; +import WebSocket = require("ws"); + +import SCServerSocket = require("./scserversocket"); + +declare class SCServer extends EventEmitter { + readonly MIDDLEWARE_HANDSHAKE_WS: "handshakeWS"; + readonly MIDDLEWARE_HANDSHAKE_SC: "handshakeSC"; + readonly MIDDLEWARE_AUTHENTICATE: "authenticate"; + readonly MIDDLEWARE_SUBSCRIBE: "subscribe"; + readonly MIDDLEWARE_PUBLISH_IN: "publishIn"; + readonly MIDDLEWARE_PUBLISH_OUT: "publishOut"; + readonly MIDDLEWARE_EMIT: "emit"; + + options: SCServer.SCServerOptions; + exchange: SCExchange; + + clients: { + [id: string]: SCServerSocket; + }; + clientsCount: number; + + pendingClients: { + [id: string]: SCServerSocket; + }; + pendingClientsCount: number; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "connection", listener: SCServer.connectionListenerFunction): this; + + addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void; + addMiddleware(type: "authenticate", middlewareFn: (req: SCServer.AuthenticateRequest, next: SCServer.nextAuthenticateMiddlewareFunction) => void): void; + addMiddleware(type: "subscribe", middlewareFn: (req: SCServer.SubscribeRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishIn", middlewareFn: (req: SCServer.PublishInRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishOut", middlewareFn: (req: SCServer.PublishOutRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; +} + +export = SCServer; + +declare namespace SCServer { + interface AuthToken { + [x: string]: any; + } + + interface SCServerOptions { + // The port on which to listen for outside connections/requests + port?: number; + + // Number of worker processes + workers?: number; + + // Number of broker processes + brokers?: number; + + // Should be either 'dev' or 'prod' - This affects the shutdown procedure + // when a 'SIGUSR2' signal is received by master. In 'dev', a SIGUSR2 will + // trigger an immediate shutdown of workers. In 'prod' workers will + // be terminated progressively in accordance with processTermTimeout. + environment?: string; + + // Setting this to true will cause the master process to shut down when + // it receives a SIGUSR2 signal (instead of just the workers). + // If you're using nodemon, set this to true. + killMasterOnSignal?: boolean; + + // A unique name for your app (this is used internally for + // various things such as the directory name in which to store socket + // file descriptors) - If you don't provide an appName, SC will + // generate a random one (UUID v4) + appName?: string; + + // This can be the name of an npm module or a path to a Node.js module + // to use as the WebSocket server engine. + // You can now set this to 'sc-uws' for a massive speedup of at least 2x! + wsEngine?: string; + + // An ID to associate with this specific instance of SC + // this may be useful if you are running an SC app on multiple + // hosts - You can access the instanceId from the Broker object + // (inside brokerController) - If you don't provide an instanceId, + // SC will generate a random one (UUID v4) + instanceId?: string; + + // A key which various SC processes will use to interact with + // scBroker broker processes securely, defaults to a 256 bits + // cryptographically random hex string + secretKey?: string; + + // The key which SC will use to encrypt/decrypt authTokens, defaults + // to a 256 bits cryptographically random hex string + // The default JWT algorithm used is 'HS256'. + // If you want to use RSA or ECDSA, you should provide a authPrivateKey + // and authPublicKey instead of authKey. + authKey?: Secret; + + // perMessageDeflate compression. Note that this option is passed directly to the wsEngine's + // Server object. So if you're using 'ws' as the engine, you can pass an object instead of + // a boolean. Search for perMessageDeflate here: + // https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback + // Note that by default, per-message deflate only kicks in for messages > 1024 bytes. + perMessageDeflate?: boolean; + + // If using an RSA or ECDSA algorithm to sign the authToken, you will need + // to provide an authPrivateKey and authPublicKey in PEM format (string or Buffer). + authPrivateKey?: Secret; + authPublicKey?: Secret; + + // The default expiry for auth tokens in seconds + authDefaultExpiry?: number; + + // The algorithm to use to sign and verify JWT tokens. + authAlgorithm?: string; + + // Crash workers when an error happens - This is the most sensible default + crashWorkerOnError?: boolean; + + // Reboot workers when they crash - This is a necessity + // in production but can be turned off for debugging + rebootWorkerOnCrash?: boolean; + + // Kill/respawn a worker process if its memory consumption exceeds this + // threshold (in bytes) - If this is null (default), this behavior + // will be switched off + killWorkerMemoryThreshold?: number; + + // Can be 'http' or 'https' + protocol?: "http" | "https"; + + // This is the same as the object provided to Node.js's https server + protocolOptions?: ServerOptions; + + // A log level of 3 will log everything, 2 will show notices and errors, + // 1 will only log errors, 0 will log nothing + logLevel?: 0 | 1 | 2 | 3; + + // In milliseconds, how long a client has to connect to SC before timing out + connectTimeout?: number; + + // In milliseconds - If the socket handshake hasn't been completed before + // this timeout is reached, the new connection attempt will be terminated. + handshakeTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your emit() call expects an ACK response from the other side + // (when callback is provided to emit) + ackTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your sendToWorker, sendToBroker or sendToMaster (IPC) call + // expects an ACK response from the other process + // (when callback is provided) + ipcAckTimeout?: number; + + // In milliseconds - If the socket cannot upgrade transport + // within this period, it will stop trying + socketUpgradeTimeout?: number; + + // Origins which are allowed to connect to the real-time scServer + origins?: string; + + // The maximum number of unique channels which a single + // socket can subscribe to + socketChannelLimit?: number; + + // The interval in milliseconds on which to + // send a ping to the client to check that + // it is still alive + pingInterval?: number; + + // How many milliseconds to wait without receiving a ping + // before closing the socket + pingTimeout?: number; + + // Maximum amount of milliseconds to wait before force-killing + // a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal + processTermTimeout?: number; + + // Whether or not errors from child processes (workers and brokers) + // should be passed to the current master process + propagateErrors?: boolean; + + // Whether or not warnings from child processes (workers and brokers) + // should be passed to the current master process + propagateWarnings?: number; + + // Whether or not a 'warning' event should be emitted (and logged to console) + // whenever an action is blocked by a middleware function + middlewareEmitWarnings?: number; + + // Lets you specify a host name to bind to - Defaults to + // 127.0.0.1 (localhost) + host?: string; + + // The path to a file used to bootstrap worker processes + workerController?: string; + + // The path to a file used to bootstrap broker processes + brokerController?: string; + + // The path to a file used to bootstrap the workerCluster process + workerClusterController?: string; + + // By default, SC will reboot all workers when it receives a 'SIGUSR2' signal - + // This can be used for updating workers with fresh source code in production + rebootOnSignal?: boolean; + + // If you run your master process (server.js) as super user, this option + // lets you downgrade worker and broker processes to run under + // the specified user (with fewer permissions than master) - You can provide + // a Linux UID or username + downgradeToUser?: number | string; + + // The URL path reserved by SocketCluster clients to interact with the server + path?: string; + + // The root directory in which to store your socket files in Linux. + socketRoot?: string; + + // Defaults to "rr", but can be set to "none" + schedulingPolicy?: "rr" | "none"; + + // Whether or not clients are allowed to publish messages to channels + allowClientPublish?: boolean; + + // This option is passed to the Node.js HTTP server if provided + tcpSynBacklog?: number; + + // SC keeps track of request per minutes internally - This allows you to change + // how often this gets updated + workerStatusInterval?: number; + + // This allows you to batch multiple messages together when passing them across + // message brokers. This may improve the efficiency of your pub/sub operations. + // This value is in milliseconds. 5 is generally a safe value to set this to. + pubSubBatchDuration?: number; + + // The default clustering/brokering engine (Node.js module name) which provides the + // SCWorker.exchange object and manages brokers behind the scenes. + // You shouldn't need to change this unless you want to build your own + // process clustering engine (which is difficult to do). + brokerEngine?: string; + + wsEngineServerOptions?: WebSocket.ClientOptions; + maxPayload?: number; + pingTimeoutDisabled?: boolean; + authSignAsync?: boolean; + authVerifyAsync?: boolean; + httpServer?: Server; + } + + interface SCServerSocketStatus { + id: string; + pingTimeout: number; + } + + interface HandshakeSCRequest { + socket: SCServerSocket; + } + + interface AuthenticateRequest { + socket: SCServerSocket; + authToken: AuthToken; + } + + interface SubscribeRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + waitForAuth?: boolean; + data?: any; + } + + interface PublishInRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + data?: any; + ackData?: any; + } + + interface PublishOutRequest { + socket: SCServerSocket; + channel?: string; + data?: any; + useCache?: boolean; + } + + interface EmitRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + event: string; + data?: any; + } + + type nextMiddlewareFunction = (error?: true | string | Error) => void; + type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void; + type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void; + type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; + + interface SCCodecEngine { + decode: (input: any) => any; + ncode: (object: any) => any; + } +} diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts new file mode 100644 index 0000000000..7b32cef72c --- /dev/null +++ b/types/socketcluster-server/scserversocket.d.ts @@ -0,0 +1,43 @@ +import Emitter = require("component-emitter"); +import { IncomingMessage } from "http"; +import { SCExchange } from "sc-broker-cluster"; +import { SignOptions } from "jsonwebtoken"; +import WebSocket = require("ws"); + +import SCServer = require("./scserver"); + +declare class SCServerSocket extends Emitter { + readonly CONNECTING: "connecting"; + readonly OPEN: "open"; + readonly CLOSED: "closed"; + + readonly AUTHENTICATED: "authenticated"; + readonly UNAUTHENTICATED: "unauthenticated"; + + id: string; + request: IncomingMessage; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + + exchange: SCExchange; + + state: "connecting" | "open" | "closed"; + authState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + + constructor(id: string, server: SCServer, socket: WebSocket); + + getState(): "connecting" | "open" | "closed"; + disconnect(code?: number, data?: any): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + getAuthToken(): SCServer.AuthToken; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; + deauthenticate(): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; + isSubscribed(channel?: string): boolean; +} + +export = SCServerSocket; diff --git a/types/socketcluster-server/socketcluster-server-tests.ts b/types/socketcluster-server/socketcluster-server-tests.ts new file mode 100644 index 0000000000..3d62fe9041 --- /dev/null +++ b/types/socketcluster-server/socketcluster-server-tests.ts @@ -0,0 +1,39 @@ +// Adapted from README + +// Using with basic http(s) module (example) + +import http = require("http"); +import * as socketClusterServer from "socketcluster-server"; + +let httpServer = http.createServer(); +let scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); + +// Using with Express (example) + +import serveStatic = require("serve-static"); +import path = require("path"); +import express = require("express"); + +const app = express(); + +app.use(serveStatic(path.resolve(__dirname, "public"))); + +httpServer = http.createServer(); + +// Attach express to our httpServer +httpServer.on("request", app); + +// Attach socketcluster-server to our httpServer +scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); diff --git a/types/socketcluster-server/tsconfig.json b/types/socketcluster-server/tsconfig.json new file mode 100644 index 0000000000..be1a6bdcb0 --- /dev/null +++ b/types/socketcluster-server/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scserver.d.ts", + "scserversocket.d.ts", + "socketcluster-server-tests.ts" + ] +} diff --git a/types/socketcluster-server/tslint.json b/types/socketcluster-server/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-server/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster/fsutil.d.ts b/types/socketcluster/fsutil.d.ts new file mode 100644 index 0000000000..bcfcbfc59f --- /dev/null +++ b/types/socketcluster/fsutil.d.ts @@ -0,0 +1,11 @@ +import { PathLike } from "fs"; + +export function fileExists(filePath: PathLike, callback: (exists: boolean) => void): void; + +export function waitForFile( + filePath: PathLike, + checkInterval: number, + startTime: number, + maxWaitDuration: number, + timeoutErrorMessage?: string +): Promise; diff --git a/types/socketcluster/index.d.ts b/types/socketcluster/index.d.ts new file mode 100644 index 0000000000..0ec8485cfa --- /dev/null +++ b/types/socketcluster/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for socketcluster 14.0 +// Project: https://github.com/SocketCluster/socketcluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventEmitter } from "events"; +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +interface WorkerStartInfo { + id: number; + pid: number; + respawn: boolean; +} + +interface WorkerClusterStartInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterReadyInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterExitInfo { + pid: number; + code: number; + signal: string; + childProcess: ChildProcess; +} + +export = SocketCluster; + +declare class SocketCluster extends EventEmitter { + readonly EVENT_FAIL: "fail"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_READY: "ready"; + readonly EVENT_WORKER_START: "workerStart"; + readonly EVENT_WORKER_EXIT: "workerExit"; + readonly EVENT_BROKER_START: "brokerStart"; + readonly EVENT_BROKER_EXIT: "brokerExit"; + readonly EVENT_WORKER_CLUSTER_START: "workerClusterStart"; + readonly EVENT_WORKER_CLUSTER_READY: "workerClusterReady"; + readonly EVENT_WORKER_CLUSTER_EXIT: "workerClusterExit"; + + options: SCServer.SCServerOptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "fail", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "workerStart", listener: (workerInfo: WorkerStartInfo) => void): this; + on(event: "workerExit", listener: (workerInfo: SocketCluster.WorkerExitInfo) => void): this; + on(event: "brokerStart", listener: (brokerInfo: SocketCluster.BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: SocketCluster.BrokerExitInfo) => void): this; + on(event: "workerClusterStart", listener: (workerClusterInfo: WorkerClusterStartInfo) => void): this; + on(event: "workerClusterReady", listener: (workerClusterInfo: WorkerClusterReadyInfo) => void): this; + on(event: "workerClusterExit", listener: (workerClusterInfo: WorkerClusterExitInfo) => void): this; +} + +declare namespace SocketCluster { + interface WorkerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } + + interface BrokerStartInfo { + id: number; + pid: number; + respawn: boolean; + } + + interface BrokerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } +} diff --git a/types/socketcluster/scbroker.d.ts b/types/socketcluster/scbroker.d.ts new file mode 100644 index 0000000000..461801aa63 --- /dev/null +++ b/types/socketcluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker-cluster/scbroker"); + +export = SCBroker; diff --git a/types/socketcluster/scworker.d.ts b/types/socketcluster/scworker.d.ts new file mode 100644 index 0000000000..48502692be --- /dev/null +++ b/types/socketcluster/scworker.d.ts @@ -0,0 +1,63 @@ +import { EventEmitter } from "events"; +import { Server as httpServer } from "http"; +import { Server as httpsServer } from "https"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; + +export = SCWorker; + +type middlewareFunction = (options: SCServer.SCServerOptions, next: (error?: string | Error) => void) => void; + +declare class SCWorker extends EventEmitter { + readonly EVENT_ERROR: "error"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_EXIT: "exit"; + readonly EVENT_READY: "ready"; + readonly EVENT_CONNECTION: "connection"; + + readonly MIDDLEWARE_START: "start"; + + id: number; + isLeader: boolean; + options: SCServer.SCServerOptions; + httpServer: httpServer | httpsServer; + scServer: SCServer; + exchange: SCExchange; + auth: SCAuthEngine; + + constructor(options?: SCServer.SCServerOptions); + + run(): void; + + getSCServer(): SCServer; + getHTTPServer(): httpServer | httpsServer; + getSocketPath(): string; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + + open(): void; + close(callback?: () => void): void; + + addMiddleware(type: "start", middlewareFn: middlewareFunction): void; + removeMiddleware(type: "start", middlewareFn: middlewareFunction): void; + + startHTTPServer(): void; + start(): Promise; + + getStatus(): { + clientCount: any; + httpRPM: number; + wsRPM: number; + }; + + sendToMaster(data: any, callback: (err: Error | null, data: any) => void): void; + respondToMaster(err: Error | null, data: any, rid: number): void; + + on(event: "connection", listener: (scSocket: SCServerSocket) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; +} diff --git a/types/socketcluster/socketcluster-tests.ts b/types/socketcluster/socketcluster-tests.ts new file mode 100644 index 0000000000..85ad9c3d05 --- /dev/null +++ b/types/socketcluster/socketcluster-tests.ts @@ -0,0 +1,76 @@ +import * as fsutil from "socketcluster/fsutil"; +import SocketCluster = require("socketcluster"); +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +//////////////////////////////////////////////////// +/// SocketCluster tests +//////////////////////////////////////////////////// + +{ + const options: SCServer.SCServerOptions = { port: 80 }; + + let sc = new SocketCluster(); + sc = new SocketCluster(options); + sc.options = { environment: "prod" }; + + sc.on(sc.EVENT_FAIL, err => { + const error: Error = err; + }); + sc.on(sc.EVENT_WARNING, warning => { + const warn: Error = warning; + }); + + sc.on(sc.EVENT_READY, () => {}); + + sc.on(sc.EVENT_WORKER_START, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const respawn: boolean = workerInfo.respawn; + }); + sc.on(sc.EVENT_WORKER_EXIT, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const code: number = workerInfo.code; + const signal: string = workerInfo.signal; + }); + + sc.on(sc.EVENT_BROKER_START, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const respawn: boolean = brokerInfo.respawn; + }); + sc.on(sc.EVENT_BROKER_EXIT, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const code: number = brokerInfo.code; + const signal: string = brokerInfo.signal; + }); + + sc.on(sc.EVENT_WORKER_CLUSTER_START, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_READY, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_EXIT, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const code: number = workerClusterInfo.code; + const signal: string = workerClusterInfo.signal; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); +} + +//////////////////////////////////////////////////// +/// fsutil tests +//////////////////////////////////////////////////// + +{ + fsutil.fileExists("/path/to/folder", err => {}); + fsutil.fileExists(Buffer.from(""), err => {}); + + const pathPromise: Promise = fsutil.waitForFile("/path/to/folder", 100, 0, 100); + const bufferPromise: Promise = fsutil.waitForFile(Buffer.from(""), 0, 0, 0, "timeout"); +} diff --git a/types/socketcluster/tsconfig.json b/types/socketcluster/tsconfig.json new file mode 100644 index 0000000000..1a0267f5f0 --- /dev/null +++ b/types/socketcluster/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fsutil.d.ts", + "scbroker.d.ts", + "scworker.d.ts", + "socketcluster-tests.ts" + ] +} diff --git a/types/socketcluster/tslint.json b/types/socketcluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/space-pen/tslint.json b/types/space-pen/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/space-pen/tslint.json +++ b/types/space-pen/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 955eb45faf..003c6a70f6 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -3562,7 +3562,7 @@ export class Euler { fromArray(xyzo: any[]): Euler; toArray(array?: number[], offset?: number): number[]; toVector3(optionalResult?: Vector3): Vector3; - onChange(callback: Function): void; + onChange(callback: Function): this; static RotationOrders: string[]; static DefaultOrder: string; diff --git a/types/toastr/tslint.json b/types/toastr/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/toastr/tslint.json +++ b/types/toastr/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/toobusy-js/index.d.ts b/types/toobusy-js/index.d.ts index 2d7f2688a7..2e6aca6c4b 100644 --- a/types/toobusy-js/index.d.ts +++ b/types/toobusy-js/index.d.ts @@ -1,19 +1,66 @@ // Type definitions for toobusy-js 0.5 // Project: https://github.com/STRML/node-toobusy // Definitions by: Arne Schubert +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = toobusy_js; +/** + * Main export function. + * @return True if node process is too busy. + */ declare function toobusy_js(): boolean; declare namespace toobusy_js { - function interval(newInterval: number): number; + /** + * Sets or gets the current check interval. + * If you want more sensitive checking, set a faster (lower) interval. A lower maxLag can also create a more + * sensitive check. + * @param [newInterval] New interval to set. If not provided, will return the existing interval. + * @return New or existing interval. + */ + function interval(newInterval?: number): number; + /** + * Returns last lag reading from last check interval. + * @return Lag in ms. + */ function lag(): number; - function maxLag(newLag: number): number; - function smoothingFactor(newFactor: number): number; + /** + * Set or get the current max latency threshold. Default is 70ms. + * + * Note that if event loop lag goes over this threshold, the process is not always 'too busy' - the farther + * it goes over the threshold, the more likely the process will be considered too busy. + * + * The percentage is equal to the percent over the max lag threshold. So 1.25x over the maxLag will indicate + * too busy 25% of the time. 2x over the maxLag threshold will indicate too busy 100% of the time. + * @param [newLag] New maxLag (highwater) threshold. + * @return New or existing maxLag (highwater) threshold. + */ + function maxLag(newLag?: number): number; + /** + * Set or get the smoothing factor. Default is 0.3333.... + * + * The smoothing factor per the standard exponential smoothing formula "αtn + (1-α)tn-1" + * See: https://en.wikipedia.org/wiki/Exponential_smoothing + * + * @param [newFactor] New smoothing factor. + * @return New or existing smoothing factor. + */ + function smoothingFactor(newFactor?: number): number; + /** + * Shuts down toobusy. + * + * Not necessary to call this manually, only do this if you know what you're doing. `unref()` is called + * on toobusy's check interval, so it will never keep the server open. + */ function shutdown(): void; + /** + * Registers an event listener for lag events, + * optionally specify a minimum value threshold for events being emitted + * @param fn Function of form onLag(value: number) => void + * @param [threshold=maxLag] Optional minimum lag value for events to be emitted + */ function onLag(fn: (lag: number) => void, threshold?: number): void; - function started(): boolean; } diff --git a/types/toobusy-js/toobusy-js-tests.ts b/types/toobusy-js/toobusy-js-tests.ts index 121b84ddb4..2678dcc777 100644 --- a/types/toobusy-js/toobusy-js-tests.ts +++ b/types/toobusy-js/toobusy-js-tests.ts @@ -1,4 +1,4 @@ -import toobusy = require("toobusy-js"); +import toobusy = require('toobusy-js'); let numberValue = 1; let booleanValue = true; @@ -7,11 +7,19 @@ booleanValue = toobusy(); booleanValue = toobusy.started(); numberValue = toobusy.interval(numberValue); +numberValue = toobusy.interval(); numberValue = toobusy.lag(); numberValue = toobusy.maxLag(numberValue); +numberValue = toobusy.maxLag(); numberValue = toobusy.smoothingFactor(numberValue); - -toobusy.onLag((duration: number) => {}); -toobusy.onLag((duration: number) => {}, numberValue); - +numberValue = toobusy.smoothingFactor(); toobusy.shutdown(); + +toobusy.onLag(duration => { + // $ExpectType number + duration; +}); +toobusy.onLag(duration => { + // $ExpectType number + duration; +}, numberValue); diff --git a/types/unist/index.d.ts b/types/unist/index.d.ts index ee61686f93..2d7d37e17f 100644 --- a/types/unist/index.d.ts +++ b/types/unist/index.d.ts @@ -4,6 +4,7 @@ // Jun Lu // Hernan Rajchert // Titus Wormer +// Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 @@ -26,6 +27,8 @@ export interface Node { * Must not be present if a node is generated. */ position?: Position; + + [key: string]: unknown; } /** diff --git a/types/vfile-message/index.d.ts b/types/vfile-message/index.d.ts index 908f72027b..5f4467e007 100644 --- a/types/vfile-message/index.d.ts +++ b/types/vfile-message/index.d.ts @@ -9,10 +9,6 @@ import * as Unist from 'unist'; declare namespace vfileMessage { - interface AnyNode extends Unist.Node { - [key: string]: unknown; - } - /** * Create a virtual message. */ @@ -25,7 +21,7 @@ declare namespace vfileMessage { * @param position Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). * @param origin Place in code the message originates from (`string`, optional). */ - (reason: string | Error, position?: AnyNode | Unist.Position | Unist.Point, origin?: string): VFileMessage; + (reason: string | Error, position?: Unist.Node | Unist.Position | Unist.Point, origin?: string): VFileMessage; /** * Category of message. */ diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index efb07e288d..aec7ca88f9 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -98,7 +98,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - message: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => vfileMessage.VFileMessage; + message: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; /** * Associates a fatal message with the file, then immediately throws it. * Note: fatal errors mean a file is no longer processable. @@ -107,7 +107,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - fail: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => never; + fail: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => never; /** * Associates an informational message with the file, where `fatal` is set to `null`. * Calls `message()` internally. @@ -115,7 +115,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - info: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => vfileMessage.VFileMessage; + info: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; } } diff --git a/types/web-resource-inliner/index.d.ts b/types/web-resource-inliner/index.d.ts new file mode 100644 index 0000000000..009f3a5dda --- /dev/null +++ b/types/web-resource-inliner/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for web-resource-inliner 4.2 +// Project: https://github.com/jrit/web-resource-inliner#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { CoreOptions, RequiredUriUrl } from 'request'; + +export function html(options: Options, callback: Callback): string; +export function css(options: Options, callback: Callback): string; + +export type Callback = (error: any, result: any) => void; + +export interface Options { + /** + * This is the HTML or CSS content to be inlined, you should provide HTML to the html() method and CSS to the css() method or you will get errors or garbage output. + */ + fileContent: string; + /** + * Sets the attribute that is used to include/exclude specific resources based on the default behavior for the resource type. + * + * For example, if scripts is set to false, an individual script can be inlined by adding the attribute to the script tag like . + * On the other hand, if images are set to be inlined by default, + * a specific image can be excluded by adding -ignore to the end of the inlineAttribute like . + * + * In CSS, a comment is required at the end of the line to perform the same thing, such as \/*data-inline*\/ or \/*data-inline-ignore*\/. + * + * @default "data-inline" + */ + inlineAttribute?: string; + /** + * When true, inline images unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude images unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline images only when the base64 content size is less than the number of KBs. + * + * For example, the default is to only inline images less than 8KB. + * + * @default 8 + */ + images?: boolean | number; + /** + * When true, inline SVG unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude SVG unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline SVG only when the content size is less than the number of KBs. + * + * For example, the default is to only inline SVGs less than 8KB. + * + * @default 8 + */ + svgs?: boolean | number; + /** + * When true, inline scripts unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude scripts unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline scripts only when the base64 content size is less than the number of KBs. + * + * @default true + */ + scripts?: boolean | number; + /** + * When true, inline stylesheet links unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude stylesheet links unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline stylesheet links only when the base64 content size is less than the number of KBs. + * + * @default true + */ + links?: boolean | number; + /** + * Describes the path relationship between where web-resource-inliner is running and what the relative paths in fileContent or href/src urls refer to. + * + * For example, the tests cases in this package are in test/cases/ so their relative paths start by referring to that folder, + * but the root of this project and where npm test runs from is 2 folders up, so relativeTo is set to test/cases/ in test/spec.js. + * Likewise, with href="content.css" and a relativeTo of http://github.com/ the resource retrieved would be http://github.com/content.css. + * + * @default "" + */ + relativeTo?: string; + /** + * Describes the path relationship between CSS content and the context it will be loaded in. + * + * For example, when a CSS file contains url(some-file.png) and the file is moved from a location in a folder like /css to / + * then the path to the image needs to be changed to url(css/some-file.png). + * In this case, rebaseRelativeTo would be css. You probably don't want to set this when you are using html(). + * + * @default "" + */ + rebaseRelativeTo?: string; + /** + * When strict is true, a missing resource will cause the inliner to halt and return an error in the callback. + * + * The default behavior is to log a warning to the console and continue inlining with the available resources, which is more similar to how a web page behaves. + * + * @default false + */ + strict?: boolean; + /** + * Allows to adjust issued requests. + * + * E.g., add authentication tokens to requested URLs. + * + * The function is called with the request options object as its parameter. + * + * It can modify this object or return a new one. + * + * See the [list of available options](https://www.npmjs.com/package/request#request-options-callback). + */ + requestTransform?: ( + requestOptions: RequiredUriUrl & CoreOptions + ) => RequiredUriUrl & CoreOptions; + /** + * Allows to make changes to scripts before they are inlined, such as minifying. + * + * Callback is standard node error first, second argument is transformed value. + */ + scriptTransform?: (content: string, done: Callback) => any; + /** + * Allows to make changes to links before they are inlined, such as CSS pre-and-post-processors. + * + * Callback is standard node error first, second argument is transformed value. + */ + linkTransform?: (content: string, done: Callback) => any; +} diff --git a/types/web-resource-inliner/tsconfig.json b/types/web-resource-inliner/tsconfig.json new file mode 100644 index 0000000000..cdfd6e6a41 --- /dev/null +++ b/types/web-resource-inliner/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", + "web-resource-inliner-tests.ts" + ] +} diff --git a/types/web-resource-inliner/tslint.json b/types/web-resource-inliner/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/web-resource-inliner/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/web-resource-inliner/web-resource-inliner-tests.ts b/types/web-resource-inliner/web-resource-inliner-tests.ts new file mode 100644 index 0000000000..a0410e151f --- /dev/null +++ b/types/web-resource-inliner/web-resource-inliner-tests.ts @@ -0,0 +1,49 @@ +import { html, css } from 'web-resource-inliner'; + +const fileContent = '

some content

'; +const cb = (error: any, result: any) => null; + +html({ fileContent }, cb); +html({ fileContent, inlineAttribute: 'foo' }, cb); +html({ fileContent, images: true }, cb); +html({ fileContent, images: 8 }, cb); +html({ fileContent, svgs: true }, cb); +html({ fileContent, svgs: 8 }, cb); +html({ fileContent, scripts: true }, cb); +html({ fileContent, scripts: 8 }, cb); +html({ fileContent, links: true }, cb); +html({ fileContent, links: 8 }, cb); +html({ fileContent, relativeTo: 'http://foo.bar' }, cb); +html({ fileContent, rebaseRelativeTo: 'css' }, cb); +html({ fileContent, strict: true }, cb); +html( + { + fileContent, + requestTransform(options) { + // $ExpectType (UriOptions & CoreOptions) | (UrlOptions & CoreOptions) + options; + return options; + }, + }, + cb +); +html( + { + fileContent, + scriptTransform(content, done) { + done(null, content); + }, + }, + cb +); +html( + { + fileContent, + linkTransform(content, done) { + done(null, content); + }, + }, + cb +); + +css({ fileContent }, cb); diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 2e2eb35481..408e434441 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3306,7 +3306,7 @@ declare namespace wx { function openCard(options: OpenCardOptions): void; interface OpenSettingOptions extends BaseOptions { - success?(res: { authSetting: { [key in Scope]: string} }): void; + success?(res: { authSetting: { [key in Scope]: boolean } }): void; } /** * 调起客户端小程序设置界面,返回用户设置的操作结果。 diff --git a/types/wx-js-sdk-dt/index.d.ts b/types/wx-js-sdk-dt/index.d.ts index cefc43887f..23b5388336 100644 --- a/types/wx-js-sdk-dt/index.d.ts +++ b/types/wx-js-sdk-dt/index.d.ts @@ -162,7 +162,7 @@ declare namespace wx { /** * 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 */ - function onMenuShareQzone(config: MenuShareWeibo): void; + function onMenuShareQZone(config: MenuShareWeibo): void; interface ChooseImageConfig { /** diff --git a/types/xmpp__xml/index.d.ts b/types/xmpp__xml/index.d.ts new file mode 100644 index 0000000000..b69eacee0f --- /dev/null +++ b/types/xmpp__xml/index.d.ts @@ -0,0 +1,66 @@ +// Type definitions for @xmpp/xml 0.6 +// Project: https://github.com/xmppjs/xmpp.js/tree/master/packages/xml +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export = xml; + +import * as ltx from 'ltx'; +import * as escape from 'ltx/lib/escape'; +import { EventEmitter } from 'events'; + +declare function xml( + name: string, + attrs?: string | { [key: string]: any }, + ...children: xml.ElementChild[] +): xml.Element; + +declare namespace xml { + function x( + name: string, + attrs?: string | { [key: string]: any }, + ...children: ElementChild[] + ): Element; + + const escapeXML: typeof escape.escapeXML; + const unescapeXML: typeof escape.unescapeXML; + const escapeXMLText: typeof escape.escapeXMLText; + const unescapeXMLText: typeof escape.unescapeXMLText; + + class Element extends ltx.Element { + attrs: { [key: string]: any }; + append(nodes: ElementChild): Element; + prepend(nodes: ElementChild): Element; + } + type ElementChild = Element | Element[] | string | number | boolean; + + class Parser extends EventEmitter { + readonly XMLError: typeof XMLError; + readonly parser: ltx.Parser; + root: Element | null; + cursor: Element | null; + + onStartElement(name: string, attrs?: string | { [attrName: string]: any }): void; + onEndElement(name: string): void; + onText(str: string): void; + write(data: Buffer): void; + end(data: Buffer): void; + } +} + +declare class XMLError extends Error { + readonly name: 'XMLError'; +} + +declare global { + namespace JSX { + interface IntrinsicElements { + [elemName: string]: any; + } + + type Element = xml.Element; + } +} diff --git a/types/xmpp__xml/tsconfig.json b/types/xmpp__xml/tsconfig.json new file mode 100644 index 0000000000..3fbf44dc71 --- /dev/null +++ b/types/xmpp__xml/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@xmpp/xml": [ + "xmpp__xml" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + }, + "files": [ + "index.d.ts", + "xmpp__xml-tests.ts", + "xmpp__xml-tests.tsx" + ] +} diff --git a/types/xmpp__xml/tslint.json b/types/xmpp__xml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/xmpp__xml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/xmpp__xml/xmpp__xml-tests.ts b/types/xmpp__xml/xmpp__xml-tests.ts new file mode 100644 index 0000000000..84820feaaa --- /dev/null +++ b/types/xmpp__xml/xmpp__xml-tests.ts @@ -0,0 +1,46 @@ +import xml = require('@xmpp/xml'); + +xml.escapeXML(''); +xml.unescapeXML(''); +xml.escapeXMLText(''); +xml.unescapeXMLText(''); + +const parser = new xml.Parser(); +parser.onStartElement('el'); +parser.onEndElement('el'); +parser.onText('text'); +parser.write((null as any) as Buffer); +parser.end((null as any) as Buffer); + +const recipient = 'user@example.com'; +const days = ['Monday', 'Tuesday']; +const message = xml( + 'message', + { to: recipient }, + xml('body', {}, 1 + 2), + xml('days', days.map(day => xml('day', {}, day))) +); +xml.x( + 'message', + { to: recipient }, + xml('body', {}, 1 + 2), + xml('days', days.map(day => xml('day', {}, day))) +); + +message.attrs; +message.getChild('body')!.text(); +message.getChild('body')!.toString(); +message.getChild('days')!.getChildren('day'); +message.getChildText('body'); + +message.attrs.type = 'chat'; +Object.assign(message.attrs, { type: 'chat' }); +message.getChild('body')!.text('Hello world'); +message.append(xml('foo')); +message.append('bar'); +message.append(days.map(day => xml('day', {}, day))); +message.prepend(xml('foo')); +message.prepend('bar'); +message.prepend(days.map(day => xml('day', {}, day))); +const body = message.getChild('body'); +message.remove(body!); diff --git a/types/xmpp__xml/xmpp__xml-tests.tsx b/types/xmpp__xml/xmpp__xml-tests.tsx new file mode 100644 index 0000000000..010cc43f2a --- /dev/null +++ b/types/xmpp__xml/xmpp__xml-tests.tsx @@ -0,0 +1,26 @@ +/** @jsx xml */ + +import xml = require('@xmpp/xml'); + +const recipient = 'user@example.com'; +const days = ['Monday', 'Tuesday']; +const message = ( + + {1 + 2} + + {days.map(day => ( + ${day} + ))} + + +); + +// write +message.append( + + {JSON.stringify(days)} + +); + +// read +JSON.parse(message.getChild('myevent', 'xmpp:example.org')!.getChildText('json', 'urn:xmpp:json:0')!);