diff --git a/README.es.md b/README.es.md index ce94bb0298..c3cff967db 100644 --- a/README.es.md +++ b/README.es.md @@ -87,6 +87,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re * `cd types/my-package-to-edit` * Haz cambios. Recuerda editar las pruebas. + Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal). * También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete. - Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete. - Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice , Bob `. diff --git a/README.md b/README.md index 7c58fe8901..554316e52a 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in * `cd types/my-package-to-edit` * Make changes. Remember to edit tests. + If you make breaking changes, do not forget to [update a major version](#i-want-to-update-a-package-to-a-new-major-version). * You may also want to add yourself to "Definitions by" section of the package header. - This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package. - Do this by adding your name to the end of the line, as in `// Definitions by: Alice , Bob `. diff --git a/notNeededPackages.json b/notNeededPackages.json index 6f3e4fe093..dd5523d102 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -660,6 +660,12 @@ "sourceRepoURL": "https://github.com/ashtuchkin/iconv-lite", "asOfVersion": "0.4.14" }, + { + "libraryName": "ids", + "typingsPackageName": "ids", + "sourceRepoURL": "https://github.com/bpmn-io/ids", + "asOfVersion": "0.2.2" + }, { "libraryName": "immutability-helper", "typingsPackageName": "immutability-helper", diff --git a/package.json b/package.json index db67595b77..37d1f4d48b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "definitely-typed", - "version": "0.0.1", + "version": "0.0.2", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped", "repository": { "type": "git", diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 5af66a09d1..5e2bd23e36 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -21,9 +21,9 @@ type MyEntity = AFrame.Entity<{ material: THREE.Material; sound: { pause(): void }; }>; -const camera = document.querySelector('a-entity[camera]').components.camera; -const material = document.querySelector('a-entity[material]').components.material; -document.querySelector('a-entity[sound]').components.sound.pause(); +const camera = (document.querySelector('a-entity[camera]') as MyEntity).components.camera; +const material = (document.querySelector('a-entity[material]') as MyEntity).components.material; +(document.querySelector('a-entity[sound]') as MyEntity).components.sound.pause(); entity.getDOMAttribute('geometry').primitive; @@ -38,21 +38,82 @@ entity.addEventListener('child-detached', (event) => { }); // Components -const Component = AFRAME.registerComponent('test', {}); + +interface TestComponent extends AFrame.Component { + multiply: (f: number) => number; + + data: { + myProperty: any[], + string: string, + num: number + }; + + system: TestSystem; +} + +const Component = AFRAME.registerComponent('test-component', { + schema: { + myProperty: { + default: [], + parse() { return [true]; }, + }, + string: { type: 'string' }, + num: 0 + }, + init() { + this.data.num = 0; + }, + update() {}, + tick() {}, + remove() {}, + pause() {}, + play() {}, + + multiply(this: TestComponent, f: number) { + // Reference to system because both were registered with the same name. + return f * this.data.num * this.system.data.counter; + } +}); // Scene const scene = document.querySelector('a-scene'); scene.hasLoaded; // System -const system = scene.systems['systemName']; + +interface TestSystem extends AFrame.System { + data: { + counter: number; + }; +} + +const testSystem: AFrame.SystemDefinition = { + schema: { + counter: 0 + }, + + init() { + this.data.counter = 1; + } +}; + +AFRAME.registerSystem('test-component', testSystem); // Register Custom Geometry -AFRAME.registerGeometry('a-test-geometry', { + +interface TestGeometry extends AFrame.Geometry { + schema: AFrame.MultiPropertySchema<{ + groupIndex: number; + }>; +} + +AFRAME.registerGeometry('a-test-geometry', { schema: { groupIndex: { default: 0 } }, init(data) { this.geometry = new THREE.Geometry(); + const temp = data.groupIndex; + temp; } }); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index 0da1ed0ef5..b405de0273 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -2,6 +2,7 @@ // Project: https://aframe.io/ // Definitions by: Paul Shannon // Roberto Ritger +// Trygve Wastvedt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -19,7 +20,7 @@ declare var hasNativeWebVRImplementation: boolean; interface Document { createElement(tagName: string): AFrame.Entity; querySelector(selectors: 'a-scene'): AFrame.Scene; - querySelector>(selectors: string): T; + querySelector(selectors: string): AFrame.Entity; querySelectorAll(selectors: string): NodeListOf | Element>; } @@ -36,15 +37,15 @@ declare namespace AFrame { components: { [ key: string ]: ComponentDescriptor }; geometries: { [ key: string ]: GeometryDescriptor }; primitives: { [ key: string ]: Entity }; - registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; + registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometry: GeometryDefinition): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): GeometryConstructor; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; - registerShader(name: string, shader: any): void; - registerSystem(name: string, definition: SystemDefinition): void; + registerShader(name: string, shader: T): ShaderConstructor; + registerSystem(name: string, definition: SystemDefinition): SystemConstructor; schema: SchemaUtils; shaders: { [ key: string ]: ShaderDescriptor }; - systems: { [key: string]: System }; + systems: { [key: string]: SystemConstructor }; THREE: typeof THREE; TWEEN: typeof TWEEN; utils: Utils; @@ -89,54 +90,39 @@ declare namespace AFrame { tick(): void; } - interface Component { + interface Component { attrName?: string; - data?: any; + data: T; dependencies?: string[]; el: Entity; id: string; multiple?: boolean; name: string; - schema: Schema; + schema: Schema; + system: S | undefined; - init(data?: any): void; - pause(): void; - play(): void; - remove(): void; - tick?(time: number, timeDelta: number): void; - update(oldData: any): void; - updateSchema?(): void; + init(this: this, data?: T): void; + pause(this: this): void; + play(this: this): void; + remove(this: this): void; + tick?(this: this, time: number, timeDelta: number): void; + update(this: this, oldData: T): void; + updateSchema?(this: this): void; - extendSchema(update: Schema): void; - flushToDOM(): void; + extendSchema(this: this, update: Schema): void; + flushToDOM(this: this): void; } - interface ComponentConstructor { - new (el: Entity, name: string, id: string): Component; + interface ComponentConstructor { + new (el: Entity, attrValue: string, id: string): T; } - interface ComponentDefinition { - dependencies?: string[]; - el?: Entity; - id?: string; - multiple?: boolean; - schema?: Schema; + type ComponentDefinition = Partial; - init?(data?: any): void; - pause?(): void; - play?(): void; - remove?(): void; - tick?(time: number, timeDelta: number): void; - update?(oldData: any): void; - updateSchema?(): void; - - [ key: string ]: any; - } - - interface ComponentDescriptor { - Component: Component; - dependencies: string[] | null; - multiple: boolean | null; + interface ComponentDescriptor { + Component: ComponentConstructor; + dependencies: string[] | undefined; + multiple: boolean | undefined; // internal APIs2 // parse @@ -144,7 +130,6 @@ declare namespace AFrame { // schema // stringify // type - [ key: string ]: any; } interface Coordinate { @@ -153,8 +138,14 @@ declare namespace AFrame { z: number; } + interface DefaultComponents { + position: Component; + rotation: Component; + scale: Component; + } + interface Entity> extends ANode { - components: C; + components: C & DefaultComponents; isPlaying: boolean; object3D: THREE.Object3D; object3DMap: ObjectMap; @@ -165,8 +156,8 @@ declare namespace AFrame { /** * @deprecated since 0.4.0 */ - getComputedAttribute(attr: string): T; - getDOMAttribute(attr: string): T; + getComputedAttribute(attr: string): Component; + getDOMAttribute(attr: string): any; getObject3D(type: string): THREE.Object3D; getOrCreateObject3D(type: string, construct: any): THREE.Object3D; is(stateName: string): boolean; @@ -179,7 +170,6 @@ declare namespace AFrame { // getAttribute specific usages getAttribute(type: string): any; - getAttribute(attr: string): T; getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; // setAttribute specific usages @@ -192,12 +182,18 @@ declare namespace AFrame { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } - type DetailEvent = Event & { detail: D }; + type DetailEvent = Event & { + detail: D; + target: EventTarget & Entity; + }; interface EntityEventMap { 'child-attached': DetailEvent<{ el: Element | Entity }>; 'child-detached': DetailEvent<{ el: Element | Entity }>; - 'componentchanged': DetailEvent<{ name: string }>; + 'componentchanged': DetailEvent<{ + name: string, + id: string + }>; 'componentremoved': DetailEvent<{ name: string, id: string, @@ -215,23 +211,28 @@ declare namespace AFrame { interface Geometry { name: string; geometry: THREE.Geometry; - schema: Schema; - update(data: object): void; - [ key: string ]: any; + schema: Schema; + + init(this: this, data: { [P in keyof this['schema']]: any }): void; + // Would like the above to be: + // init?(this: this, data?: { [P in keyof T['schema']]: T['schema'][P]['default'] } ): void; + // I think this is prevented by the following issue: https://github.com/Microsoft/TypeScript/issues/21760. } - interface GeometryDefinition extends ComponentDefinition { - geometry?: THREE.Geometry; + interface GeometryConstructor { + new (): T; } - interface GeometryDescriptor { - Geometry: Geometry; + type GeometryDefinition = Partial; + + interface GeometryDescriptor { + Geometry: GeometryConstructor; schema: Schema; } - interface MultiPropertySchema { - [ key: string ]: SinglePropertySchema; - } + type MultiPropertySchema = { + [P in keyof T]: SinglePropertySchema | T[P]; + }; interface PrimitiveDefinition { defaultComponents?: any; // TODO cleanup type @@ -240,8 +241,9 @@ declare namespace AFrame { transforms?: any; // TODO cleanup type } - type PropertyTypes = 'array' | 'boolean' | 'color' | 'int' | 'number' | 'selector' | - 'selectorAll' | 'src' | 'string' | 'vec2' | 'vec3' | 'vec4'; + type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' | + 'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' | + 'string' | 'vec2' | 'vec3' | 'vec4'; type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; @@ -265,7 +267,7 @@ declare namespace AFrame { addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; } - type Schema = SinglePropertySchema | MultiPropertySchema; + type Schema = SinglePropertySchema | MultiPropertySchema; interface SchemaUtils { isSingleProperty(schema: Schema): boolean; @@ -274,11 +276,25 @@ declare namespace AFrame { interface Shader { name: string; - schema: Schema; + data: { [key: string]: any }; + schema: Schema; + material: THREE.Material; + vertexShader: string; + fragmentShader: string; + + init(this: this, data?: this['data']): void; + tick?(this: this, time: number, timeDelta: number): void; + update(this: this, oldData: this['data']): void; } - interface ShaderDescriptor { - Shader: Shader; + interface ShaderConstructor { + new (): T; + } + + type ShaderDefinition = Partial; + + interface ShaderDescriptor { + Shader: ShaderConstructor; schema: Schema; } @@ -287,27 +303,23 @@ declare namespace AFrame { 'default'?: T; parse?(value: string): T; stringify?(value: T): string; - [ key: string ]: any; } interface System { - data: any; - schema: Schema; - init(): void; - pause(): void; - play(): void; - tick?(): void; + data: { [key: string]: any }; + schema: Schema; + init(this: this): void; + pause(this: this): void; + play(this: this): void; + tick?(this: this, t: number, dt: number): void; } - interface SystemDefinition { - schema?: Schema; - init?(): void; - pause?(): void; - play?(): void; - tick?(): void; - [ key: string ]: any; + interface SystemConstructor { + new (scene: Scene): T; } + type SystemDefinition = Partial; + interface Utils { coordinates: { isCoordinate(value: string): boolean; @@ -326,5 +338,8 @@ declare namespace AFrame { diff(a: object, b: object): object; extend(target: object, ... source: object[]): object; extendDeep(target: object, ... source: object[]): object; + + throttle(tickFunction: () => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; + throttleTick(tickFunction: (t: number, dt: number) => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; } } diff --git a/types/aframe/tslint.json b/types/aframe/tslint.json index 71ee04c4e1..495d29983d 100644 --- a/types/aframe/tslint.json +++ b/types/aframe/tslint.json @@ -1,6 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - "no-unnecessary-generics": false } } diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index b8cd1db6c5..2898f889fc 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -150,4 +150,17 @@ let _algoliaQueryParameters: QueryParameters = { let index: Index = algoliasearch('', '').initIndex(''); let search = index.search({ query: '' }); + index.search({ query: '' }, (err, res) => {}); + +// partialUpdateObject +index.partialUpdateObject({}, () => {}); +index.partialUpdateObject({}, false, () => {}); +index.partialUpdateObject({}).then(() => {}); +index.partialUpdateObject({}, false).then(() => {}); + +// partialUpdateObjects +index.partialUpdateObjects([{}], () => {}); +index.partialUpdateObjects([{}], false, () => {}); +index.partialUpdateObjects([{}]).then(() => {}); +index.partialUpdateObjects([{}], false).then(() => {}); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index fca13ac161..87c1f79a0e 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -286,14 +286,13 @@ declare namespace algoliasearch { * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ partialUpdateObject(object: {}, cb: (err: Error, res: Task) => void): void; + partialUpdateObject(object: {}, createIfNotExists: boolean, cb: (err: Error, res: Task) => void): void; /** * Update parameters of a list of objects * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects( - objects: {}[], - cb: (err: Error, res: Task) => void - ): void; + partialUpdateObjects(objects: {}[], cb: (err: Error, res: Task) => void): void; + partialUpdateObjects(objects: {}[], createIfNotExists: boolean, cb: (err: Error, res: Task) => void): void; /** * Delete a specific object * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects @@ -531,11 +530,13 @@ declare namespace algoliasearch { * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ partialUpdateObject(object: {}): Promise; + partialUpdateObject(object: {}, createIfNotExists: boolean): Promise; /** * Update parameters of a list of objects * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ partialUpdateObjects(objects: {}[]): Promise; + partialUpdateObjects(objects: {}[], createIfNotExists?: boolean): Promise; /** * Delete a specific object * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects diff --git a/types/amazon-cognito-auth-js/index.d.ts b/types/amazon-cognito-auth-js/index.d.ts new file mode 100644 index 0000000000..d828fccfc8 --- /dev/null +++ b/types/amazon-cognito-auth-js/index.d.ts @@ -0,0 +1,577 @@ +// Type definitions for amazon-cognito-auth-js 1.2 +// Project: https://github.com/aws/amazon-cognito-auth-js +// Definitions by: Scott Escue +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/* + * Create global variable to provide access to types when used without module + * loading. + */ +export as namespace AmazonCognitoIdentity; + +// Stubs the XDomainRequest built-in from older IE browsers, does not follow the project's interface naming convention +export interface XDomainRequest { + readonly responseText: string; + timeout: number; + onprogress: () => void; + ontimeout: () => void; + onerror: () => void; + onload: () => void; + + open(method: string, url: string): void; + send(data: string): void; + abort(): void; +} + +export interface CognitoSessionData { + /** + * The session's Id token. + */ + IdToken?: CognitoIdToken; + + /** + * The session's refresh token. + */ + RefreshToken?: CognitoRefreshToken; + + /** + * The session's access token. + */ + AccessToken?: CognitoAccessToken; + + /** + * The session's token scopes. + */ + TokenScopes?: CognitoTokenScopes; + + /** + * The session's state. + */ + State?: string; +} + +export interface CognitoAuthOptions { + /** + * Required: User pool application client id. + */ + ClientId: string; + + /** + * Required: The application/user-pools Cognito web hostname,this is set at the Cognito console. + */ + AppWebDomain: string; + + /** + * Optional: The token scopes + */ + TokenScopesArray?: ReadonlyArray; + + /** + * Required: Required: The redirect Uri, which will be launched after authentication as signed in. + */ + RedirectUriSignIn: string; + + /** + * Required: The redirect Uri, which will be launched when signed out. + */ + RedirectUriSignOut: string; + + /** + * Optional: Pre-selected identity provider (this allows to automatically trigger social provider authentication flow). + */ + IdentityProvider?: string; + + /** + * Optional: UserPoolId for the configured cognito userPool. + */ + UserPoolId?: string; + + /** + * Optional: boolean flag indicating if the data collection is enabled to support cognito advanced security features. By default, this flag is set to true. + */ + AdvancedSecurityDataCollectionFlag?: boolean; +} + +export interface CognitoAuthUserHandler { + onSuccess: (authSession: CognitoAuthSession) => void; + onFailure: (err: any) => void; +} + +export interface CognitoConstants { + DOMAIN_SCHEME: string; + DOMAIN_PATH_SIGNIN: string; + DOMAIN_PATH_TOKEN: string; + DOMAIN_PATH_SIGNOUT: string; + DOMAIN_QUERY_PARAM_REDIRECT_URI: string; + DOMAIN_QUERY_PARAM_SIGNOUT_URI: string; + DOMAIN_QUERY_PARAM_RESPONSE_TYPE: string; + DOMAIN_QUERY_PARAM_IDENTITY_PROVIDER: string; + DOMAIN_QUERY_PARAM_USERCONTEXTDATA: string; + CLIENT_ID: string; + STATE: string; + SCOPE: string; + TOKEN: string; + CODE: string; + POST: string; + PARAMETERERROR: string; + SCOPETYPEERROR: string; + QUESTIONMARK: string; + POUNDSIGN: string; + COLONDOUBLESLASH: string; + SLASH: string; + AMPERSAND: string; + EQUALSIGN: string; + SPACE: string; + CONTENTTYPE: string; + CONTENTTYPEVALUE: string; + AUTHORIZATIONCODE: string; + IDTOKEN: string; + ACCESSTOKEN: string; + REFRESHTOKEN: string; + ERROR: string; + ERROR_DESCRIPTION: string; + STRINGTYPE: string; + STATELENGTH: number; + STATEORIGINSTRING: string; + WITHCREDENTIALS: string; + UNDEFINED: string; + SELF: string; + HOSTNAMEREGEX: RegExp; + QUERYPARAMETERREGEX1: RegExp; + QUERYPARAMETERREGEX2: RegExp; + HEADER: { 'Content-Type': string }; +} + +export class CognitoIdToken { + /** + * Constructs a new CognitoIdToken object + * @param IdToken The JWT Id token + */ + constructor(IdToken: string); + + /** + * @returns the record's token. + */ + getJwtToken(): string; + + /** + * Sets new value for id token. + * @param idToken The JWT Id token + */ + setJwtToken(idToken: string): void; + + /** + * @returns the token's expiration (exp member). + */ + getExpiration(): number; + + /** + * @returns the token's payload. + */ + decodePayload(): object; +} + +export class CognitoRefreshToken { + /** + * Constructs a new CognitoRefreshToken object + * @param RefreshToken The JWT refresh token. + */ + constructor(RefreshToken: string); + + /** + * @returns the record's token. + */ + getToken(): string; + + /** + * Sets new value for refresh token. + * @param refreshToken The JWT refresh token. + */ + setToken(refreshToken: string): void; +} + +export class CognitoAccessToken { + /** + * Constructs a new CognitoAccessToken object + * @param AccessToken The JWT access token. + */ + constructor(AccessToken: string); + + /** + * @returns the record's token. + */ + getJwtToken(): string; + + /** + * Sets new value for access token. + * @param accessToken The JWT access token. + */ + setJwtToken(accessToken: string): void; + + /** + * @returns the token's expiration (exp member). + */ + getExpiration(): number; + + /** + * @returns the username from payload. + */ + getUsername(): string; + + /** + * @returns the token's payload. + */ + decodePayload(): object; +} + +export class CognitoTokenScopes { + /** + * Constructs a new CognitoTokenScopes object + * @param TokenScopesArray The token scopes + */ + constructor(TokenScopesArray: ReadonlyArray); + + /** + * @returns the token scopes. + */ + getScopes(): string[]; + + /** + * Sets new value for token scopes. + * @param tokenScopes The token scopes + */ + setTokenScopes(tokenScopes: ReadonlyArray): void; +} + +export class CognitoAuthSession { + /** + * Constructs a new CognitoUserSession object + * @param sessionData The session's tokens, scopes, and state. + */ + constructor(sessionData: CognitoSessionData); + + /** + * @returns the session's Id token + */ + getIdToken(): CognitoIdToken; + + /** + * Set a new Id token + * @param IdToken The session's Id token. + */ + setIdToken(IdToken: CognitoIdToken): void; + + /** + * @returns the session's refresh token + */ + getRefreshToken(): CognitoRefreshToken; + + /** + * Set a new Refresh token + * @param RefreshToken The session's refresh token. + */ + setRefreshToken(RefreshToken: CognitoRefreshToken): void; + + /** + * @returns the session's access token + */ + getAccessToken(): CognitoAccessToken; + + /** + * Set a new Access token + * @param AccessToken The session's access token. + */ + setAccessToken(AccessToken: CognitoAccessToken): void; + + /** + * @returns the session's token scopes + */ + getTokenScopes(): CognitoTokenScopes; + + /** + * Set new token scopes + * @param tokenScopes The session's token scopes. + */ + setTokenScopes(tokenScopes: CognitoTokenScopes): void; + + /** + * @returns the session's state + */ + getState(): string; + + /** + * Set new state + * @param state The session's state. + */ + setState(State: string): void; + + /** + * Checks to see if the session is still valid based on session expiry information found + * in Access and Id Tokens and the current time + * @returns if the session is still valid + */ + isValid(): boolean; +} + +export class CognitoAuth { + /** + * Called on success or error. + */ + userhandler: CognitoAuthUserHandler; + + /** + * Constructs a new CognitoAuth object + * @param options Creation options + */ + constructor(options: CognitoAuthOptions); + + /** + * @returns the constants + */ + getCognitoConstants(): CognitoConstants; + + /** + * @returns the client id + */ + getClientId(): string; + + /** + * @returns the app web domain + */ + getAppWebDomain(): string; + + /** + * method for getting the current user of the application from the local storage + * + * @returns the user retrieved from storage + */ + getCurrentUser(): string; + + /** + * method for setting the current user's name + * @param Username the user's name + */ + setUser(Username: string): void; + + /** + * sets response type to 'code' + */ + useCodeGrantFlow(): void; + + /** + * sets response type to 'token' + */ + useImplicitFlow(): void; + + /** + * @returns the current session for this user + */ + getSignInUserSession(): CognitoAuthSession; + + /** + * @returns the user's username + */ + getUsername(): string; + + /** + * @param Username the user's username + */ + setUsername(Username: string): void; + + /** + * @returns the user's state + */ + getState(): string; + + /** + * @param State the user's state + */ + setState(State: string): void; + + /** + * This is used to get a session, either from the session object or from the local storage, or by using a refresh token + * @param RedirectUriSignIn Required: The redirect Uri, which will be launched after authentication. + * @param TokenScopesArray Required: The token scopes, it is an array of strings specifying all scopes for the tokens. + */ + getSession(): void; + + /** + * Parse the http request response and proceed according to different response types. + * @param httpRequestResponse the http request response + */ + parseCognitoWebResponse(httpRequestResponse: string): void; + + /** + * Get the query parameter map and proceed according to code response type. + * @param Query parameter map + */ + getCodeQueryParameter(map: ReadonlyMap): void; + + /** + * Get the query parameter map and proceed according to token response type. + * @param Query parameter map + */ + getTokenQueryParameter(map: ReadonlyMap): void; + + /** + * Get cached tokens and scopes and return a new session using all the cached data. + * @returns the auth session + */ + getCachedSession(): CognitoAuthSession; + + /** + * This is used to get last signed in user from local storage + * @returns the last user name + */ + getLastUser(): string; + + /** + * This is used to save the session tokens and scopes to local storage. + */ + cacheTokensScopes(): void; + + /** + * Compare two sets if they are identical. + * @param set1 one set + * @param set2 the other set + * @returns boolean value is true if two sets are identical + */ + compareSets(set1: ReadonlySet, set2: ReadonlySet): boolean; + + /** + * Get the hostname from url. + * @param url the url string + * @returns hostname string + */ + getHostName(url: string): string; + + /** + * Get http query parameters and return them as a map. + * @param url the url string + * @param splitMark query parameters split mark (prefix) + * @returns map + */ + getQueryParameters(url: string, splitMark: string): Map; + + /** + * helper function to generate a random string + * @param length the length of string + * @param chars a original string + * @returns a random value. + */ + generateRandomString(length: number, chars: string): string; + + /** + * This is used to clear the session tokens and scopes from local storage + */ + clearCachedTokensScopes(): void; + + /** + * This is used to build a user session from tokens retrieved in the authentication result + * @param refreshToken Successful auth response from server. + */ + refreshSession(refreshToken: string): void; + + /** + * Make the http POST request. + * @param header header JSON object + * @param body body JSON object + * @param url string + * @param onSuccess callback + * @param onFailure callback + */ + makePOSTRequest(header: object, body: object, url: string, + onSuccess: (responseText: string) => void, + onFailure: (responseText: string) => void): void; + + /** + * Create the XHR object + * @param method which method to call + * @param url the url string + * @returns xhr + */ + createCORSRequest(method: string, url: string): XMLHttpRequest | XDomainRequest; + + /** + * The http POST request onFailure callback. + * @param err the error object + */ + onFailure(err: any): void; + + /** + * The http POST request onSuccess callback when refreshing tokens. + * @param jsonData tokens + */ + onSuccessRefreshToken(jsonData: string): void; + + /** + * The http POST request onSuccess callback when exchanging code for tokens. + * @param jsonData tokens + */ + onSuccessExchangeForToken(jsonData: string): void; + + /** + * Launch Cognito Auth UI page. + * @param URL the url to launch + */ + launchUri(URL: string): void; + + /** + * @returns scopes string + */ + getSpaceSeperatedScopeString(): string; + + /** + * Create the FQDN(fully qualified domain name) for authorization endpoint. + * @returns url + */ + getFQDNSignIn(): string; + + /** + * Sign out the user. + */ + signOut(): void; + + /** + * Create the FQDN(fully qualified domain name) for signout endpoint. + * @returns url + */ + getFQDNSignOut(): string; + + /** + * This method returns the encoded data string used for cognito advanced security feature. + * This would be generated only when developer has included the JS used for collecting the + * data on their client. Please refer to documentation to know more about using AdvancedSecurity + * features + */ + getUserContextData(): string; + + /** + * Helper method to let the user know if he has either a valid cached session + * or a valid authenticated session from the app integration callback. + * @returns userSignedIn + */ + isUserSignedIn(): boolean; +} + +export class DateHelper { + /** + * @returns The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. + */ + getNowString(): string; +} + +export class StorageHelper { + /** + * This is used to get a storage object + * @returns the storage + */ + constructor(); + + /** + * This is used to return the storage + * @returns the storage + */ + getStorage(): Storage; +} diff --git a/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts new file mode 100644 index 0000000000..42e58185e4 --- /dev/null +++ b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts @@ -0,0 +1,162 @@ +import * as lib from 'amazon-cognito-auth-js'; + +const idToken: lib.CognitoIdToken = new lib.CognitoIdToken('fak3T0ken1=='); +idToken.decodePayload(); // $ExpectType object +idToken.setJwtToken('fak3T0ken2=='); // $ExpectType void +idToken.getJwtToken(); // $ExpectType string +idToken.getExpiration(); // $ExpectType number + +const refreshToken: lib.CognitoRefreshToken = new lib.CognitoRefreshToken('refreshplease=='); +refreshToken.setToken('refreshagainplease=='); // $ExpectType void +refreshToken.getToken(); // $ExpectType string + +const accessToken: lib.CognitoAccessToken = new lib.CognitoAccessToken('fak3T0ken3=='); +accessToken.decodePayload(); // $ExpectType object +accessToken.setJwtToken('fak3T0ken4=='); // $ExpectType void +accessToken.getJwtToken(); // $ExpectType string +accessToken.getExpiration(); // $ExpectType number +accessToken.getUsername(); // $ExpectType string + +const tokenScopes: lib.CognitoTokenScopes = new lib.CognitoTokenScopes(['email', 'custom1']); +tokenScopes.setTokenScopes(['openid']); // $ExpectType void +tokenScopes.getScopes(); // $ExpectType string[] + +let sessionData: lib.CognitoSessionData = {}; +let authSession: lib.CognitoAuthSession = new lib.CognitoAuthSession(sessionData); + +sessionData = { + IdToken: idToken, + RefreshToken: refreshToken, + AccessToken: accessToken, + TokenScopes: tokenScopes, + State: '/myapp/home' +}; +authSession = new lib.CognitoAuthSession(sessionData); + +authSession.setIdToken(new lib.CognitoIdToken('fak3T0ken5==')); // $ExpectType void +authSession.setRefreshToken(new lib.CognitoRefreshToken('refreshmeyetagain==')); // $ExpectType void +authSession.setAccessToken(new lib.CognitoAccessToken('fak3T0ken6==')); // $ExpectType void +authSession.setTokenScopes(new lib.CognitoTokenScopes(['email'])); // $ExpectType void +authSession.setState('/myapp/login'); // $ExpectType void +authSession.getIdToken(); // $ExpectType CognitoIdToken +authSession.getRefreshToken(); // $ExpectType CognitoRefreshToken +authSession.getAccessToken(); // $ExpectType CognitoAccessToken +authSession.getTokenScopes(); // $ExpectType CognitoTokenScopes +authSession.getState(); // $ExpectType string + +let authOptions: lib.CognitoAuthOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout' +}; +let auth: lib.CognitoAuth = new lib.CognitoAuth(authOptions); + +authOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + TokenScopesArray: ['email', 'openid'], + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout', + IdentityProvider: 'Facebook', + UserPoolId: 'us-east-1_faKE4ReAl', + AdvancedSecurityDataCollectionFlag: true +}; +auth = new lib.CognitoAuth(authOptions); + +auth.getClientId(); // $ExpectType string +auth.getAppWebDomain(); // $ExpectType string +auth.getCurrentUser(); // $ExpectType string +auth.setUser('jane.doe'); // $ExpectType void +auth.useCodeGrantFlow(); // $ExpectType void +auth.useImplicitFlow(); // $ExpectType void +auth.getSignInUserSession(); // $ExpectType CognitoAuthSession +auth.getUsername(); // $ExpectType string +auth.setUsername('john.doe'); // $ExpectType void +auth.getState(); // $ExpectType string +auth.setState('/myhost/default.htm'); // $ExpectType void +auth.getSession(); // $ExpectType void +auth.parseCognitoWebResponse('url&stuff=true'); // $ExpectType void +auth.getCodeQueryParameter(new Map()); // $ExpectType void +auth.getTokenQueryParameter(new Map()); // $ExpectType void +auth.getCachedSession(); // $ExpectType CognitoAuthSession +auth.getLastUser(); // $ExpectType string +auth.cacheTokensScopes(); // $ExpectType void +auth.compareSets(new Set(['1']), new Set(['1'])); // $ExpectType boolean +auth.getHostName('https://site.com/page?size=10'); // $ExpectType string +auth.getQueryParameters('http://site.com?1=1&2=2', '?'); // $ExpectType Map +auth.generateRandomString(5, '159erf'); // $ExpectType string +auth.clearCachedTokensScopes(); // $ExpectType void +auth.refreshSession('refreshToken=='); // $ExpectType void +// $ExpectType void +auth.makePOSTRequest({ 'Content-Type': 'application/json' }, { pool: '2' }, + 'https://auth.com/signin', + (data) => console.log(data), + (error) => console.log(error)); +auth.createCORSRequest('POST', '/myapp/login'); // $ExpectType XMLHttpRequest | XDomainRequest +auth.onFailure('request failed'); // $ExpectType void +auth.onSuccessRefreshToken('{"name":"John", "age":31}'); // $ExpectType void +auth.onSuccessExchangeForToken('{"name":"Jane", "age":30}'); // $ExpectType void +auth.launchUri('https://auth.com/login'); // $ExpectType void +auth.getSpaceSeperatedScopeString(); // $ExpectType string +auth.getFQDNSignIn(); // $ExpectType string +auth.signOut(); // $ExpectType void +auth.getFQDNSignOut(); // $ExpectType string +auth.getUserContextData(); // $ExpectType string +auth.isUserSignedIn(); // $ExpectType boolean + +const userHandler: lib.CognitoAuthUserHandler = { + onSuccess: (authSession: lib.CognitoAuthSession) => console.log(authSession), + onFailure: (error: any) => console.log(error) +}; +auth.userhandler = userHandler; + +const constants: lib.CognitoConstants = auth.getCognitoConstants(); +constants.DOMAIN_SCHEME; // $ExpectType string +constants.DOMAIN_PATH_SIGNIN; // $ExpectType string +constants.DOMAIN_PATH_TOKEN; // $ExpectType string +constants.DOMAIN_PATH_SIGNOUT; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_REDIRECT_URI; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_SIGNOUT_URI; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_RESPONSE_TYPE; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_IDENTITY_PROVIDER; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_USERCONTEXTDATA; // $ExpectType string +constants.CLIENT_ID; // $ExpectType string +constants.STATE; // $ExpectType string +constants.SCOPE; // $ExpectType string +constants.TOKEN; // $ExpectType string +constants.CODE; // $ExpectType string +constants.POST; // $ExpectType string +constants.PARAMETERERROR; // $ExpectType string +constants.SCOPETYPEERROR; // $ExpectType string +constants.QUESTIONMARK; // $ExpectType string +constants.POUNDSIGN; // $ExpectType string +constants.COLONDOUBLESLASH; // $ExpectType string +constants.SLASH; // $ExpectType string +constants.AMPERSAND; // $ExpectType string +constants.EQUALSIGN; // $ExpectType string +constants.SPACE; // $ExpectType string +constants.CONTENTTYPE; // $ExpectType string +constants.CONTENTTYPEVALUE; // $ExpectType string +constants.AUTHORIZATIONCODE; // $ExpectType string +constants.IDTOKEN; // $ExpectType string +constants.ACCESSTOKEN; // $ExpectType string +constants.REFRESHTOKEN; // $ExpectType string +constants.ERROR; // $ExpectType string +constants.ERROR_DESCRIPTION; // $ExpectType string +constants.STRINGTYPE; // $ExpectType string +constants.STATELENGTH; // $ExpectType number +constants.STATEORIGINSTRING; // $ExpectType string +constants.WITHCREDENTIALS; // $ExpectType string +constants.UNDEFINED; // $ExpectType string +constants.SELF; // $ExpectType string +constants.HOSTNAMEREGEX; // $ExpectType RegExp +constants.QUERYPARAMETERREGEX1; // $ExpectType RegExp +constants.QUERYPARAMETERREGEX2; // $ExpectType RegExp +constants.HEADER['Content-Type']; // $ExpectType string + +const dateHelper: lib.DateHelper = new lib.DateHelper(); +dateHelper.getNowString(); // $ExpectType string + +const storageHelper: lib.StorageHelper = new lib.StorageHelper(); +storageHelper.getStorage(); // $ExpectType Storage diff --git a/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts new file mode 100644 index 0000000000..1e30dbbeb8 --- /dev/null +++ b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts @@ -0,0 +1,22 @@ +AmazonCognitoIdentity.CognitoIdToken; // $ExpectType typeof CognitoIdToken +AmazonCognitoIdentity.CognitoRefreshToken; // $ExpectType typeof CognitoRefreshToken +AmazonCognitoIdentity.CognitoAccessToken; // $ExpectType typeof CognitoAccessToken +AmazonCognitoIdentity.CognitoTokenScopes; // $ExpectType typeof CognitoTokenScopes +AmazonCognitoIdentity.CognitoAuthSession; // $ExpectType typeof CognitoAuthSession +AmazonCognitoIdentity.CognitoAuth; // $ExpectType typeof CognitoAuth +AmazonCognitoIdentity.DateHelper; // $ExpectType typeof DateHelper +AmazonCognitoIdentity.StorageHelper; // $ExpectType typeof StorageHelper + +const sessionData: AmazonCognitoIdentity.CognitoSessionData = {}; +new AmazonCognitoIdentity.CognitoAuthSession(sessionData); + +const authOptions: AmazonCognitoIdentity.CognitoAuthOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout' +}; +const auth = new AmazonCognitoIdentity.CognitoAuth(authOptions); +auth.userhandler; // $ExpectType CognitoAuthUserHandler +auth.getCognitoConstants(); // $ExpectType CognitoConstants +auth.createCORSRequest('', ''); // $ExpectType XMLHttpRequest | XDomainRequest diff --git a/types/amazon-cognito-auth-js/tsconfig.json b/types/amazon-cognito-auth-js/tsconfig.json new file mode 100644 index 0000000000..df5a9f2d73 --- /dev/null +++ b/types/amazon-cognito-auth-js/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/amazon-cognito-auth-js-tests.ts", + "test/amazon-cognito-auth-js-umd-tests.ts" + ] +} diff --git a/types/amazon-cognito-auth-js/tslint.json b/types/amazon-cognito-auth-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/amazon-cognito-auth-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index da5e1e40c2..7e0fd6383e 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -1,4 +1,4 @@ -import { db, aql, query } from "@arangodb"; +import { aql, db, query } from "@arangodb"; import { md5 } from "@arangodb/crypto"; import { createRouter } from "@arangodb/foxx"; import sessionsMiddleware = require("@arangodb/foxx/sessions"); @@ -52,6 +52,10 @@ bananas.updateByExample( { shape: { type: "round" } }, { mergeObjects: true } ); +bananas.ensureIndex({ + type: "geo", + fields: ["latLng"] +}); const router = createRouter(); module.context.use(router); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index deed6a97c5..5c3f56020f 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -89,7 +89,7 @@ declare namespace ArangoDB { | "network authentication required"; type EdgeDirection = "any" | "inbound" | "outbound"; type EngineType = "mmfiles" | "rocksdb"; - type IndexType = "hash" | "skiplist" | "fulltext" | "geo1" | "geo2"; + type IndexType = "hash" | "skiplist" | "fulltext" | "geo"; type ViewType = "arangosearch"; type KeyGeneratorType = "traditional" | "autoincrement"; type ErrorName = diff --git a/types/arrify/arrify-tests.ts b/types/arrify/arrify-tests.ts index 12995781bf..3fee89133d 100644 --- a/types/arrify/arrify-tests.ts +++ b/types/arrify/arrify-tests.ts @@ -1,5 +1,6 @@ import * as arrify from 'arrify'; +/***************** arrify *****************/ arrify(null); arrify(null); @@ -12,3 +13,74 @@ arrify([2, 3]); function test(val?: string | string[]) { arrify(val); } +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); // returns [] + +arrify(null); // returns [] + +{ + const value: number | string[] = 2018; + arrify(value); // returns [2018] +} + +{ + const value: number[] | string | string[] = ['a', 'b']; + arrify(value); // returns ['a', 'b'] +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | number[] | string[] = true; + // returns [true] + arrify(value); +} + +{ + const value: boolean[] | number | string[] = ['a', 'b']; + // returns ['a', 'b'] + arrify(value); +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | Date | number[] | string[] = new Date(2018); + // returns [ new Date(2018) ] + arrify(value); +} + +{ + const value: boolean[] | Date[] | number | string = [true, false]; + // returns [true, false] + arrify(value); +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | Date | number[] | RegExp | string[] = /test/; + // returns [ /test/ ] + arrify(value); +} + +{ + const value: boolean[] | Date[] | number | RegExp[] | string = [/test1/, /test2/]; + // returns [/test1/, /test2/] + arrify(value); +} +/***************** arrify *****************/ diff --git a/types/arrify/index.d.ts b/types/arrify/index.d.ts index 43c06af05f..7c3c588ea6 100644 --- a/types/arrify/index.d.ts +++ b/types/arrify/index.d.ts @@ -14,5 +14,78 @@ * arrify([2, 3]) // returns [2, 3] */ declare function arrify(val: undefined | null | T | T[]): T[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: number | string[] = 2018; + * // returns [2018] + * arrify(value); + * @example + * let value: number[] | string | string[] = ['a', 'b']; + * // returns ['a', 'b'] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T1[] | T2[]): T1[] | T2[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | number[] | string[] = true; + * // returns [true] + * arrify(value); + * @example + * let value: boolean[] | number | string[] = ['a', 'b']; + * // returns ['a', 'b'] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T1[] | T2[] | T3[]): T1[] | T2[] | T3[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | Date | number[] | string[] = new Date(2018); + * // returns [ new Date(2018) ] + * arrify(value); + * @example + * let value: boolean[] | Date[] | number | string = [true, false]; + * // returns [true, false] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T4 | T1[] | T2[] | T3[] | T4[]): T1[] | T2[] | T3[] | T4[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | Date | number[] | RegExp | string[] = /test/; + * // returns [ /test/ ] + * arrify(value); + * @example + * let value: boolean[] | Date[] | number | RegExp[] | string = [/test1/, /test2/]; + * // returns [/test1/, /test2/] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T4 | T5 | T1[] | T2[] | T3[] | T4[] | T5[]): T1[] | T2[] | T3[] | T4[] | T5[]; + declare namespace arrify {} export = arrify; diff --git a/types/blocked/blocked-tests.ts b/types/blocked/blocked-tests.ts new file mode 100644 index 0000000000..f43eb82cba --- /dev/null +++ b/types/blocked/blocked-tests.ts @@ -0,0 +1,7 @@ +import * as blocked from 'blocked'; + +blocked((ms: number) => { + // todo: show warning +}, { + threshold: 10 +}); diff --git a/types/blocked/index.d.ts b/types/blocked/index.d.ts new file mode 100644 index 0000000000..5292011f23 --- /dev/null +++ b/types/blocked/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for blocked 1.2 +// Project: https://github.com/visionmedia/node-blocked#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +export = Blocked; + +declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer; + +declare namespace Blocked { + interface Options { + threshold: number; // in milliseconds + } +} diff --git a/types/blocked/tsconfig.json b/types/blocked/tsconfig.json new file mode 100644 index 0000000000..3b110548b0 --- /dev/null +++ b/types/blocked/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "blocked-tests.ts" + ] +} diff --git a/types/blocked/tslint.json b/types/blocked/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/blocked/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-spies/chai-spies-tests.ts b/types/chai-spies/chai-spies-tests.ts index 1d99f0add2..f5247ba13f 100644 --- a/types/chai-spies/chai-spies-tests.ts +++ b/types/chai-spies/chai-spies-tests.ts @@ -88,6 +88,27 @@ spyStringArg('foo'); expect(spyStringArg).to.have.been.called.always.with.exactly('foo'); spyStringArg.should.have.been.called.always.with.exactly('foo'); +// .first / .second / .third +const spyStringIteratedArg = chai.spy((arg: string) => arg); +spyStringIteratedArg('foo'); +spyStringIteratedArg('bar'); +spyStringIteratedArg('baz'); +expect(spyStringIteratedArg).to.have.been.first.called.with('foo'); +spyStringIteratedArg.should.have.been.first.called.with('foo'); +expect(spyStringIteratedArg).to.have.been.first.called.with('bar'); +spyStringIteratedArg.should.have.been.first.called.with('bar'); +expect(spyStringIteratedArg).to.have.been.first.called.with('baz'); +spyStringIteratedArg.should.have.been.first.called.with('baz'); + +// .nth +const spyStringNthArg = chai.spy((arg: string) => arg); +spyStringNthArg('foo'); +spyStringNthArg('bar'); +expect(spyStringNthArg).on.nth(1).be.called.with('foo'); +spyStringNthArg.should.on.nth(1).be.called.with('foo'); +expect(spyStringNthArg).on.nth(2).be.called.with('bar'); +spyStringNthArg.should.on.nth(2).be.called.with('bar'); + // .once expect(spy).to.have.been.called.once; expect(spy).to.not.have.been.called.once; diff --git a/types/chai-spies/index.d.ts b/types/chai-spies/index.d.ts index ffed6e594b..75f702ca37 100644 --- a/types/chai-spies/index.d.ts +++ b/types/chai-spies/index.d.ts @@ -10,6 +10,10 @@ declare namespace Chai { spy: ChaiSpies.Spy; } + interface LanguageChains { + on: Assertion; + } + interface Assertion { /** * ####.spy @@ -31,6 +35,28 @@ declare namespace Chai { * Note that ```called``` can be used as a chainable method. */ called: ChaiSpies.Called; + + /** + * * ####.been + * * Assert that something has been spied on. Negation passes through. + * * ```ts + * * expect(spy).to.have.been.called(); + * * spy.should.have.been.called(); + * ``` + * Note that ```been``` can be used as a chainable method. + */ + been: ChaiSpies.Been; + + /** + * * ####.nth (function) + * * Assert that something has been spied on on a certain index. Negation passes through. + * * ```ts + * * expect(spy).on.nth(5).be.called.with('foobar'); + * * spy.should.on.nth(5).be.called.with('foobar'); + * ``` + * Note that ```nth``` can be used as a chainable method. + */ + nth(index: number): Assertion; } } @@ -224,6 +250,47 @@ declare namespace ChaiSpies { lt(n: number): Chai.Assertion; } + interface Been extends Chai.Assertion { + (): Chai.Assertion; + called: Called; + + /** + * ####.first + * Assert that a spy has been called first. + * ```ts + * expect(spy).to.have.been.called.first; + * expect(spy).to.not.have.been.called.first; + * spy.should.have.been.called.first; + * spy.should.not.have.been.called.first; + * ``` + */ + first: Chai.Assertion; + + /** + * ####.second + * Assert that a spy has been called second. + * ```ts + * expect(spy).to.have.been.called.second; + * expect(spy).to.not.have.been.called.second; + * spy.should.have.been.called.second; + * spy.should.not.have.been.called.second; + * ``` + */ + second: Chai.Assertion; + + /** + * ####.third + * Assert that a spy has been called third. + * ```ts + * expect(spy).to.have.been.called.third; + * expect(spy).to.not.have.been.called.third; + * spy.should.have.been.called.third; + * spy.should.not.have.been.called.third; + * ``` + */ + third: Chai.Assertion; + } + interface With { /** * ####.with diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index e6db82bc5a..04d2e182ee 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -221,7 +221,7 @@ declare namespace Chart { interface ChartTitleOptions { display?: boolean; position?: PositionType; - fullWdith?: boolean; + fullWidth?: boolean; fontSize?: number; fontFamily?: string; fontColor?: ChartColor; @@ -513,6 +513,7 @@ declare namespace Chart { gridLines?: GridLineOptions; barThickness?: number; scaleLabel?: ScaleTitleOptions; + offset?: boolean; beforeUpdate?(scale?: any): void; beforeSetDimension?(scale?: any): void; beforeDataLimits?(scale?: any): void; diff --git a/types/cli-progress/cli-progress-tests.ts b/types/cli-progress/cli-progress-tests.ts new file mode 100644 index 0000000000..b9fa6d5057 --- /dev/null +++ b/types/cli-progress/cli-progress-tests.ts @@ -0,0 +1,92 @@ +import progress = require('cli-progress'); + +function test0() { + // Usage + // Multiple examples are available e.g.example.js - just try it $ node example.js + + const _cliProgress = require('cli-progress'); + + // create a new progress bar instance and use shades_classic theme + const bar1 = new _cliProgress.Bar({}, _cliProgress.Presets.shades_classic); + + // start the progress bar with a total value of 200 and start value of 0 + bar1.start(200, 0); + + // update the current value in your application.. + bar1.update(100); + + // stop the progress bar + bar1.stop(); +} + +function test1() { + // Examples + // Example 1 - Set Options + + // change the progress characters + // set fps limit to 5 + // change the output stream and barsize + const bar = new progress.Bar({ + barCompleteChar: '#', + barIncompleteChar: '.', + fps: 5, + stream: process.stdout, + barsize: 65 + }); +} + +function test2() { + // Example 2 - Change Styles defined by Preset + // uee shades preset + // change the barsize + const bar = new progress.Bar({ + barsize: 65 + }, progress.Presets.shades_grey); +} + +function test3() { + // Example 3 - Custom Payload + // create new progress bar with custom token "speed" + const bar = new progress.Bar({ + format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit' + }); + + // initialize the bar - set payload token "speed" with the default value "N/A" + bar.start(200, 0, { + speed: "N/A" + }); + + // some code/update loop + // ... + + // update bar value. set custom token "speed" to 125 + bar.update(5, { + speed: '125' + }); + + // process finished + bar.stop(); +} + +function test4() { + // Example 4 - Custom Presets + // File mypreset.js + + const _colors = require('colors'); + + module.exports = { + format: _colors.red(' {bar}') + ' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit', + barCompleteChar: '\u2588', + barIncompleteChar: '\u2591' + }; +} + +function test5() { + // Application + + const _mypreset = require('./mypreset.js'); + + const bar = new progress.Bar({ + barsize: 65 + }, _mypreset); +} diff --git a/types/cli-progress/index.d.ts b/types/cli-progress/index.d.ts new file mode 100644 index 0000000000..3ac9dfe8a3 --- /dev/null +++ b/types/cli-progress/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for cli-progress 1.8 +// Project: https://github.com/AndiDittrich/Node.CLI-Progress +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export interface Options { + /** + * progress bar output format. + * The progressbar can be customized by using the following build-in placeholders. They can be combined in any order. + * {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString + * {percentage} - the current progress in percent (0-100) + * {total} - the end value + * {value} - the current value set by last update() call + * {eta} - expected time of accomplishment in seconds + * {duration} - elapsed time in seconds + * {eta_formatted} - expected time of accomplishment formatted into appropriate units + * {duration_formatted} - elapsed time formatted into appropriate units + * + * Example: + * progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} + * is rendered as + * progress [========================================] 100% | ETA: 0s | 200/200 + */ + format?: string; + + /** the maximum update rate (default: 10) */ + fps?: number; + + /** output stream to use (default: process.stderr) */ + stream?: NodeJS.WritableStream; + + /** automatically call stop() when the value reaches the total (default: false) */ + stopOnComplete?: boolean; + + /** clear the progress bar on complete / stop() call (default: false) */ + clearOnComplete?: boolean; + + /** the length of the progress bar in chars (default: 40) */ + barsize?: number; + + /** character to use as "complete" indicator in the bar (default: "=") */ + barCompleteString?: string; + + /** character to use as "incomplete" indicator in the bar (default: "-") */ + barIncompleteString?: string; + + /** character to use as "complete" indicator in the bar (default: "=") */ + barCompleteChar?: string; + + /** character to use as "incomplete" indicator in the bar (default: "-") */ + barIncompleteChar?: string; + + /** hide the cursor during progress operation; restored on complete (default: false) */ + hideCursor?: boolean; + + /** number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10) */ + etaBuffer?: number; + + /** disable line wrapping (default: false) - pass null to keep terminal settings; pass true to trim the output to terminal width */ + linewrap?: boolean | null; +} + +export interface Preset { + barCompleteChar: string; + barIncompleteChar: string; + format: string; +} + +export class Bar { + /** Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it! */ + constructor(opt: Options, preset?: Preset); + + calculateETA(): void; + + formatTime(t: any, roundToMultipleOf: any): any; + + getTotal(): any; + + /** Increases the current progress value by a specified amount (default +1). Update payload optionally */ + increment(step: number, payload?: object): void; + + render(): void; + + /** Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks. */ + setTotal(total: number): void; + + /** Starts the progress bar and set the total and initial value */ + start(total: number, startValue: number, payload?: object): void; + + /** Stops the progress bar and go to next line */ + stop(): void; + + stopTimer(): void; + + /** Sets the current progress value and optionally the payload with values of custom tokens as a second parameter */ + update(current: number, payload?: object): void; +} + +export const Presets: { + /** Styles as of cli-progress v1.3.0 */ + legacy: Preset; + + /** Unicode Rectangles */ + rect: Preset; + + /** Unicode background shades are used for the bar */ + shades_classic: Preset; + + /** Unicode background shades with grey bar */ + shades_grey: Preset; +}; diff --git a/types/cli-progress/tsconfig.json b/types/cli-progress/tsconfig.json new file mode 100644 index 0000000000..be8771c6c5 --- /dev/null +++ b/types/cli-progress/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "cli-progress-tests.ts" + ] +} diff --git a/types/cli-progress/tslint.json b/types/cli-progress/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-progress/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/daterangepicker/daterangepicker-tests.ts b/types/daterangepicker/daterangepicker-tests.ts index db79671721..2f8ab867e4 100644 --- a/types/daterangepicker/daterangepicker-tests.ts +++ b/types/daterangepicker/daterangepicker-tests.ts @@ -1,80 +1,116 @@ -import moment = require("moment") -import daterangepicker = require("daterangepicker"); +import moment = require('moment'); +import daterangepicker = require('daterangepicker'); function tests_simple() { $('#daterange').daterangepicker(); - $('input[name="daterange"]').daterangepicker({ - timePicker: true, - timePickerIncrement: 30, - locale: { - format: 'MM/DD/YYYY h:mm A' - } - }); + $('input[name="daterange"]') + .daterangepicker({ + timePicker: true, + timePickerIncrement: 30, + locale: { + format: 'MM/DD/YYYY h:mm A' + }, + maxSpan: { days: 10 }, + applyButtonClasses: 'my-apply-class', + cancelButtonClasses: 'my-cancel-class', + showDropdowns: true, + maxYear: 3000, + minYear: 2000 + }) + .data('daterangepicker') + .remove(); $('#reportrange').daterangepicker({ ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + 'Last Month': [ + moment() + .subtract(1, 'month') + .startOf('month'), + moment() + .subtract(1, 'month') + .endOf('month') + ] } }); - $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { - $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); + $('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) { + $(this).val( + `${picker.startDate.format('MM/DD/YYYY')} - ${picker.endDate.format('MM/DD/YYYY')}` + ); }); - - $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { + $('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) { $(this).val(''); }); - $('#demo').daterangepicker({ - "startDate": "05/06/2016", - "endDate": "05/12/2016" - }, function (start: moment.Moment, end: moment.Moment, label: string) { - console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); - }); - - $(function() { - - function cb(start: moment.Moment, end: moment.Moment) { - $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); - } - cb(moment().subtract(29, 'days'), moment()); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()], - 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] - } - }, cb); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()] + $('#demo').daterangepicker( + { + startDate: '05/06/2016', + endDate: '05/12/2016' }, - showCustomRangeLabel: false - }, cb); + (start: moment.Moment, end: moment.Moment, label: string) => { + console.log( + "New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')" + ); + } + ); - $('#endDate').daterangepicker({ - singleDatePicker: true, - startDate: moment() + $(() => { + function cb(start: moment.Moment, end: moment.Moment) { + $('#reportrange span').html( + `${start.format('MMMM D, YYYY')} - ${end.format('MMMM D, YYYY')}` + ); + } + cb(moment().subtract(29, 'days'), moment()); + + $('#reportrange').daterangepicker( + { + ranges: { + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [ + moment() + .subtract(1, 'month') + .startOf('month'), + moment() + .subtract(1, 'month') + .endOf('month') + ] + } + }, + cb + ); + + $('#reportrange').daterangepicker( + { + ranges: { + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()] + }, + showCustomRangeLabel: false + }, + cb + ); + + $('#endDate').daterangepicker({ + singleDatePicker: true, + startDate: moment() + }); }); -}); } declare const host: HTMLElement; function test_from_amd() { - var picker = new daterangepicker(host); - console.log(picker.startDate.format("YYYY-MM-DD")); + const picker = new daterangepicker(host); + console.log(picker.startDate.format('YYYY-MM-DD')); } diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 5a82950ca9..9267a801b2 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Date Range Picker v2.1.30 +// Type definitions for Date Range Picker 3.0 // Project: http://www.daterangepicker.com/ // Definitions by: SirMartin // Steven Masala @@ -7,62 +7,81 @@ // TypeScript Version: 2.3 /// -import moment = require("moment"); +import moment = require('moment'); declare global { interface JQuery { - daterangepicker(settings?: daterangepicker.Settings): JQuery; - daterangepicker(settings?: daterangepicker.Settings, callback?: daterangepicker.DataRangePickerCallback): JQuery; + daterangepicker: (( + options?: daterangepicker.Options, + callback?: daterangepicker.DataRangePickerCallback + ) => JQuery) & { defaultOptions?: daterangepicker.Options }; + data(key: 'daterangepicker'): daterangepicker | undefined; } } -declare const daterangepicker: daterangepicker.DateRangePicker; +declare class daterangepicker { + constructor( + element: HTMLElement, + options?: daterangepicker.Options, + callback?: daterangepicker.DataRangePickerCallback + ); + + startDate: moment.Moment; + endDate: moment.Moment; + container: JQuery; + + setStartDate(date: daterangepicker.DateOrString): void; + setEndDate(date: daterangepicker.DateOrString): void; + remove(): void; +} declare namespace daterangepicker { - type DataRangePickerCallback = (start: moment.Moment, end: moment.Moment, label: string | null) => any; + type DataRangePickerCallback = ( + start: moment.Moment, + end: moment.Moment, + label: string | null + ) => void; - interface DateRangePicker { - new (element: HTMLElement, settings?: daterangepicker.Settings, callback?: DataRangePickerCallback): DateRangePicker; - - startDate: moment.Moment; - endDate: moment.Moment; - container: JQuery; - - setStartDate(date: Date | moment.Moment | string): void; - setEndDate(date: Date | moment.Moment | string): void; - remove(): void; - } + type DateOrString = string | moment.Moment | Date; interface DatepickerEventObject extends JQueryEventObject { date: Date; format(format?: string): string; } - interface Settings { + interface Options { /** * The start of the initially selected date range */ - startDate?: string | moment.Moment | Date; + startDate?: DateOrString; /** * The end of the initially selected date range */ - endDate?: string | moment.Moment | Date; + endDate?: DateOrString; /** - * The earliest date a user may select + * The earliest date a user may select */ - minDate?: string | moment.Moment | Date; + minDate?: DateOrString; /** * The latest date a user may select */ - maxDate?: string | moment.Moment | Date; + maxDate?: DateOrString; /** * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) */ - dateLimit?: any; + maxSpan?: moment.MomentInput | moment.Duration; /** * Show year and month select boxes above calendars to jump to a specific month and year */ showDropdowns?: boolean; + /** + * The minimum year shown in the dropdowns when `showDropdowns` is set to true. + */ + minYear?: number; + /** + * The maximum year shown in the dropdowns when `showDropdowns` is set to true. + */ + maxYear?: number; /** * Show localized week numbers at the start of each week on the calendars */ @@ -90,15 +109,25 @@ declare namespace daterangepicker { /** * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. */ - ranges?: any; + ranges?: { [name: string]: [DateOrString, DateOrString] }; /** - * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + * Whether to show the 'Custom Range' label or just pre-defined ranges */ - opens?: string; + showCustomRangeLabel?: boolean; /** - * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to + * Normally, if you use the `ranges` option to specify pre-defined date ranges, calendars + * for choosing a custom date range are not shown until the user clicks "Custom Range". + * When this option is set to true, the calendars for choosing a custom date range are always shown instead. */ - drops?: string; + alwaysShowCalendars?: boolean; + /** + * Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + */ + opens?: 'left' | 'right' | 'center'; + /** + * Whether the picker appears below (default) or above the HTML element it's attached to + */ + drops?: 'down' | 'up'; /** * CSS class names that will be added to all buttons in the picker */ @@ -106,11 +135,11 @@ declare namespace daterangepicker { /** * CSS class string that will be added to the apply button */ - applyClass?: string; + applyButtonClasses?: string; /** - * CSS class string that will be added to the cancel button - */ - cancelClass?: string; + * CSS class string that will be added to the cancel button + */ + cancelButtonClasses?: string; /** * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. */ @@ -124,33 +153,28 @@ declare namespace daterangepicker { */ autoApply?: boolean; /** - * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. + * When enabled, the two calendars displayed will always be for two sequential months (i.e. + * January and February), and both will be advanced when clicking the left or right arrows + * above the calendars.When disabled, the two calendars can be individually advanced and + * display any month/ year. */ linkedCalendars?: boolean; - /** - * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' - */ - parentEl?: string; /** * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. */ - isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; + isInvalidDate?(startDate: DateOrString, endDate?: DateOrString): boolean; /** * A function that is passed each date in the two calendars before they are displayed, and may return a string or array of CSS class names to apply to that date's calendar cell. */ - isCustomDate?(date: string | moment.Moment | Date): string | string[] | undefined; + isCustomDate?(date: DateOrString): string | string[] | undefined; /** * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. */ autoUpdateInput?: boolean; /** - * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. - */ - alwaysShowCalendars?: boolean; - /** - * Whether to show the 'Custom Range' label or just pre-defined ranges - */ - showCustomRangeLabel?: boolean; + * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' + */ + parentEl?: string; } interface Locale { diff --git a/types/daterangepicker/tslint.json b/types/daterangepicker/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/daterangepicker/tslint.json +++ b/types/daterangepicker/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/deline/deline-tests.ts b/types/deline/deline-tests.ts new file mode 100644 index 0000000000..35f1696484 --- /dev/null +++ b/types/deline/deline-tests.ts @@ -0,0 +1,13 @@ +import * as dl from "deline"; + +const moduleName = "deline"; + +dl.deline(`deline`); // $ExpectType string +dl.deline(`module name: ${moduleName}`); // $ExpectType string +dl.deline`deline`; // $ExpectType string +dl.deline`tagged template: ${moduleName}`; // $ExpectType string +dl.deline` +tagged template: + +${moduleName} +`; diff --git a/types/deline/index.d.ts b/types/deline/index.d.ts new file mode 100644 index 0000000000..b65cd80d5e --- /dev/null +++ b/types/deline/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for deline 1.0 +// Project: https://github.com/airbnb/deline#readme +// Definitions by: Inaki Arroyo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function deline(strings: string | TemplateStringsArray, ...values: any[]): string; diff --git a/types/ids/tsconfig.json b/types/deline/tsconfig.json similarity index 87% rename from types/ids/tsconfig.json rename to types/deline/tsconfig.json index 1c739774db..ae8ad2e876 100644 --- a/types/ids/tsconfig.json +++ b/types/deline/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "ids-tests.ts" + "deline-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/deline/tslint.json b/types/deline/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/deline/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dom-to-image/index.d.ts b/types/dom-to-image/index.d.ts new file mode 100644 index 0000000000..b6e186f53b --- /dev/null +++ b/types/dom-to-image/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for dom-to-image 2.6 +// Project: https://github.com/tsayen/dom-to-image +// Definitions by: Jip Sterk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export interface DomToImage { + toSvg(node: Node, options?: Options): Promise; + toPng(node: Node, options?: Options): Promise; + toJpeg(node: Node, options?: Options): Promise; + toBlob(node: Node, options?: Options): Promise; + toPixelData(node: Node, options?: Options): Promise; +} + +export interface Options { + filter?: (node: Node) => boolean; + bgcolor?: string; + width?: number; + height?: number; + style?: {}; + quality?: number; + imagePlaceholder?: string; + cachebust?: boolean; +} + +export const DomToImage: DomToImage; + +type DomToImage_ = DomToImage; +type Options_ = Options; + +export default DomToImage; + +declare global { + namespace DomToImage { + type Options = Options_; + type DomToImage = DomToImage_; + } + + const DomToImage: DomToImage.DomToImage; +} diff --git a/types/dom-to-image/test/dom-to-image-global-tests.ts b/types/dom-to-image/test/dom-to-image-global-tests.ts new file mode 100644 index 0000000000..a21be8bd01 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-global-tests.ts @@ -0,0 +1,38 @@ +const node = new Node(); + +const options: DomToImage.Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await DomToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await DomToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await DomToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await DomToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await DomToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/test/dom-to-image-import-default-tests.ts b/types/dom-to-image/test/dom-to-image-import-default-tests.ts new file mode 100644 index 0000000000..0f300ffa38 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-import-default-tests.ts @@ -0,0 +1,40 @@ +import domToImage, { Options } from 'dom-to-image'; + +const node = new Node(); + +const options: Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await domToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await domToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await domToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await domToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await domToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/test/dom-to-image-module-tests.ts b/types/dom-to-image/test/dom-to-image-module-tests.ts new file mode 100644 index 0000000000..571a28f5b6 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-module-tests.ts @@ -0,0 +1,40 @@ +import { Options, DomToImage } from 'dom-to-image'; + +const node = new Node(); + +const options: Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await DomToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await DomToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await DomToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await DomToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await DomToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/tsconfig.json b/types/dom-to-image/tsconfig.json new file mode 100644 index 0000000000..10fc769913 --- /dev/null +++ b/types/dom-to-image/tsconfig.json @@ -0,0 +1,27 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/dom-to-image-module-tests.ts", + "test/dom-to-image-global-tests.ts", + "test/dom-to-image-import-default-tests.ts" + ] +} \ No newline at end of file diff --git a/types/dom-to-image/tslint.json b/types/dom-to-image/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/dom-to-image/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/event-stream/index.d.ts b/types/event-stream/index.d.ts index f7b10b34a2..35fb2c8b4c 100644 --- a/types/event-stream/index.d.ts +++ b/types/event-stream/index.d.ts @@ -36,7 +36,7 @@ export declare function mapSync(syncFunction: Function): MapStream; * * @param matcher */ -export declare function split(matcher: string | RegExp): MapStream; +export declare function split(matcher?: string | RegExp): MapStream; /** * Create a through stream that emits separator between each chunk, just like Array#join diff --git a/types/extract-text-webpack-plugin/index.d.ts b/types/extract-text-webpack-plugin/index.d.ts index 61b381d253..f0cc7bf65c 100644 --- a/types/extract-text-webpack-plugin/index.d.ts +++ b/types/extract-text-webpack-plugin/index.d.ts @@ -4,16 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { Plugin, NewLoader, OldLoader } from 'webpack'; +import { Plugin, Loader } from 'webpack'; export = ExtractTextPlugin; -/** - * extract-text-webpack-plugin has no support for .options instead of .query yet. - * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 - */ -type Loader = string | OldLoader | NewLoader; - /** * Use an `ExtractTextPlugin` instance and a loader returned by `extract` in concert to write files to disk instead of loading them into others. * Usage example at https://github.com/webpack/extract-text-webpack-plugin#usage-example-with-css diff --git a/types/google-libphonenumber/index.d.ts b/types/google-libphonenumber/index.d.ts index 9a46ac69a6..dd73c56790 100644 --- a/types/google-libphonenumber/index.d.ts +++ b/types/google-libphonenumber/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for libphonenumber v7.4.3 // Project: https://github.com/googlei18n/libphonenumber, https://github.com/seegno/google-libphonenumber // Definitions by: Leon Yu +// Roman Jurkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace libphonenumber { @@ -112,6 +113,7 @@ declare namespace libphonenumber { export class PhoneNumberUtil { static getInstance(): PhoneNumberUtil format(phoneNumber: PhoneNumber, format: PhoneNumberFormat): string; + formatOutOfCountryCallingNumber(phoneNumber: PhoneNumber, regionDialingFrom?: string): string; getNddPrefixForRegion(regionCode?: string, stripNonDigits?: boolean): string | undefined; getNumberType(phoneNumber: PhoneNumber): PhoneNumberType; getCountryCodeForRegion(supportedRegion:string):string; diff --git a/types/google-map-react/google-map-react-tests.tsx b/types/google-map-react/google-map-react-tests.tsx index 464f840658..552e75d362 100644 --- a/types/google-map-react/google-map-react-tests.tsx +++ b/types/google-map-react/google-map-react-tests.tsx @@ -1,9 +1,20 @@ -import GoogleMapReact, { BootstrapURLKeys } from 'google-map-react'; +import GoogleMapReact, { BootstrapURLKeys, MapOptions } from 'google-map-react'; import * as React from 'react'; const center = { lat: 0, lng: 0 }; const key: BootstrapURLKeys = { key: 'my-google-maps-key' }; const client: BootstrapURLKeys = { client: 'my-client-identifier', v: '3.28' , language: 'en' }; +const options: MapOptions = { + zoomControl: false, + gestureHandling: 'cooperative', + styles: [ + { + featureType: "administrative", + elementType: "all", + stylers: [ {saturation: "-100"} ] + } + ], +}; -; +; diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 7f34a68cc4..ca5348323a 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -8,15 +8,48 @@ import * as React from 'react'; export type BootstrapURLKeys = ({ key: string; } | { client: string; v: string; }) & { language?: string }; -export interface Options { - styles?: any[]; - scrollwheel?: boolean; - panControl?: boolean; +export interface MapTypeStyle { + elementType: string; + featureType: string; + stylers: any[]; +} + +export interface MapOptions { + // Any options from https://developers.google.com/maps/documentation/javascript/reference/3/#MapOptions + // excluding 'zoom' and 'center' which get set via props. + backgroundColor?: string; + clickableIcons?: boolean; + disableDefaultUI?: boolean; + disableDoubleClickZoom?: boolean; + draggable?: boolean; + draggableCursor?: string; + draggingCursor?: string; + fullscreenControl?: boolean; + fullscreenControlOptions?: {position: number}; + gestureHandling?: string; + heading?: number; + keyboardShortcuts?: boolean; mapTypeControl?: boolean; - minZoomOverride?: boolean; + mapTypeControlOptions?: any; + mapTypeId?: string; minZoom?: number; maxZoom?: number; - gestureHandling?: string; + noClear?: boolean; + panControl?: boolean; + panControlOptions?: {position: number}; + rotateControl?: boolean; + rotateControlOptions?: {position: number}; + scaleControl?: boolean; + scaleControlOptions?: any; + scrollwheel?: boolean; + streetView?: any; + streetViewControl?: boolean; + streetViewControlOptions?: {position: number}; + styles?: MapTypeStyle[]; + tilt?: number; + zoomControl?: boolean; + zoomControlOptions?: {position: number}; + minZoomOverride?: boolean; // Not a standard option; specific to google-map-react: https://github.com/google-map-react/google-map-react/pull/154 } export interface Maps { @@ -87,7 +120,7 @@ export interface Props { defaultZoom?: number; zoom?: number; hoverDistance?: number; - options?: Options | ((maps: Maps) => Options); + options?: MapOptions | ((maps: Maps) => MapOptions); margin?: any[]; debounced?: boolean; draggable?: boolean; diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index 0be931bee0..ce31564fb1 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { getLocation } from "../language"; import { ASTNode } from "../language/ast"; import { Source } from "../language/source"; @@ -58,7 +59,7 @@ export class GraphQLError extends Error { /** * The original error thrown from a field resolver during execution. */ - readonly originalError: Error | void; + readonly originalError: Maybe; /** * Extension fields to add to the formatted error. @@ -68,10 +69,10 @@ export class GraphQLError extends Error { constructor( message: string, nodes?: ReadonlyArray | ASTNode | undefined, - source?: Source | void, - positions?: ReadonlyArray | void, - path?: ReadonlyArray | void, - originalError?: Error | void, - extensions?: { [key: string]: any } | void + source?: Maybe, + positions?: Maybe>, + path?: Maybe>, + originalError?: Maybe, + extensions?: Maybe<{ [key: string]: any }> ); } diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 424bb62b5a..7ef4d5ce63 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError, locatedError } from "../error"; import { GraphQLSchema } from "../type/schema"; import { @@ -51,9 +52,9 @@ export type ExecutionArgs = { document: DocumentNode; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; }; /** @@ -74,9 +75,9 @@ export function execute( document: DocumentNode, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): MaybePromise; /** @@ -101,7 +102,7 @@ export function addPath( export function assertValidExecutionArguments( schema: GraphQLSchema, document: DocumentNode, - rawVariableValues: { [key: string]: any } | void + rawVariableValues: Maybe<{ [key: string]: any }> ): void; /** @@ -115,9 +116,9 @@ export function buildExecutionContext( document: DocumentNode, rootValue: any, contextValue: any, - rawVariableValues: { [key: string]: any } | void, - operationName: string | void, - fieldResolver: GraphQLFieldResolver | void + rawVariableValues: Maybe<{ [key: string]: any }>, + operationName: Maybe, + fieldResolver: Maybe> ): ReadonlyArray | ExecutionContext; /** @@ -181,4 +182,4 @@ export function getFieldDef( schema: GraphQLSchema, parentType: GraphQLObjectType, fieldName: string -): GraphQLField | void; +): Maybe>; diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index fb629325e8..e3cb7eb4bc 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError } from "../error"; import { GraphQLInputType, GraphQLField, GraphQLArgument } from "../type/definition"; import { GraphQLDirective } from "../type/directives"; @@ -35,7 +36,7 @@ export function getVariableValues( export function getArgumentValues( def: GraphQLField | GraphQLDirective, node: FieldNode | DirectiveNode, - variableValues?: { [key: string]: any } | void + variableValues?: Maybe<{ [key: string]: any }> ): { [key: string]: any }; /** @@ -54,5 +55,5 @@ export function getDirectiveValues( node: { readonly directives?: ReadonlyArray; }, - variableValues?: { [key: string]: any } | void + variableValues?: Maybe<{ [key: string]: any }> ): undefined | { [key: string]: any }; diff --git a/types/graphql/graphql.d.ts b/types/graphql/graphql.d.ts index 7282ea80f2..59dc3918f1 100644 --- a/types/graphql/graphql.d.ts +++ b/types/graphql/graphql.d.ts @@ -1,3 +1,4 @@ +import Maybe from "./tsutils/Maybe"; import { Source } from "./language/source"; import { GraphQLFieldResolver } from "./type/definition"; import { GraphQLSchema } from "./type/schema"; @@ -38,9 +39,9 @@ export interface GraphQLArgs { source: Source | string; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; } export function graphql(args: GraphQLArgs): Promise; @@ -49,9 +50,9 @@ export function graphql( source: Source | string, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): Promise; /** @@ -66,7 +67,7 @@ export function graphqlSync( source: Source | string, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): ExecutionResult; diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 68e04d104d..ba9213b7c4 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -13,6 +13,7 @@ // Dylan Stewart // Alessio Dionisi // Divyendu Singh +// Brad Zacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index a137fa318e..be50e6e02e 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ASTNode, ASTKindToNode } from "./ast"; import { TypeInfo } from "../utilities/TypeInfo"; @@ -157,4 +158,4 @@ export function visitWithTypeInfo(typeInfo: TypeInfo, visitor: Visitor, kind: string, isLeaving: boolean): VisitFn | void; +export function getVisitFn(visitor: Visitor, kind: string, isLeaving: boolean): Maybe>; diff --git a/types/graphql/subscription/subscribe.d.ts b/types/graphql/subscription/subscribe.d.ts index a9fe6b565e..f5b29ebbb8 100644 --- a/types/graphql/subscription/subscribe.d.ts +++ b/types/graphql/subscription/subscribe.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLSchema } from "../type/schema"; import { DocumentNode } from "../language/ast"; import { GraphQLFieldResolver } from "../type/definition"; @@ -28,10 +29,10 @@ export function subscribe(args: { document: DocumentNode; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; - subscribeFieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; + subscribeFieldResolver?: Maybe>; }): Promise | ExecutionResult>; export function subscribe( @@ -39,10 +40,10 @@ export function subscribe( document: DocumentNode, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void, - subscribeFieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe>, + subscribeFieldResolver?: Maybe> ): Promise | ExecutionResult>; /** @@ -69,6 +70,6 @@ export function createSourceEventStream( rootValue?: any, contextValue?: any, variableValues?: { [key: string]: any }, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + operationName?: Maybe, + fieldResolver?: Maybe> ): Promise | ExecutionResult>; diff --git a/types/graphql/tsconfig.json b/types/graphql/tsconfig.json index 72f0de0665..3bc66f8bea 100644 --- a/types/graphql/tsconfig.json +++ b/types/graphql/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "graphql-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/graphql/tsutils/Maybe.d.ts b/types/graphql/tsutils/Maybe.d.ts new file mode 100644 index 0000000000..7ad0bc85a4 --- /dev/null +++ b/types/graphql/tsutils/Maybe.d.ts @@ -0,0 +1,4 @@ +// Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ +type Maybe = null | undefined | T + +export default Maybe diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index ed87af50ad..b078acccb1 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { MaybePromise } from "../jsutils/MaybePromise"; import { ScalarTypeDefinitionNode, @@ -254,8 +255,8 @@ export type Thunk = (() => T) | T; */ export class GraphQLScalarType { name: string; - description: string | void; - astNode?: ScalarTypeDefinitionNode | void; + description: Maybe; + astNode?: Maybe; constructor(config: GraphQLScalarTypeConfig); // Serializes an internal value to include in a response. @@ -265,7 +266,7 @@ export class GraphQLScalarType { parseValue(value: any): any; // Parses an externally provided literal value to use as an input. - parseLiteral(valueNode: ValueNode, variables?: { [key: string]: any } | void): any; + parseLiteral(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; toString(): string; toJSON(): string; @@ -274,11 +275,11 @@ export class GraphQLScalarType { export interface GraphQLScalarTypeConfig { name: string; - description?: string | void; - astNode?: ScalarTypeDefinitionNode | void; - serialize(value: any): TExternal | void; - parseValue?(value: any): TInternal | void; - parseLiteral?(valueNode: ValueNode, variables: { [key: string]: any } | void): TInternal | void; + description?: Maybe; + astNode?: Maybe; + serialize(value: any): Maybe; + parseValue?(value: any): Maybe; + parseLiteral?(valueNode: ValueNode, variables: Maybe<{ [key: string]: any }>): Maybe; } /** @@ -320,10 +321,10 @@ export interface GraphQLScalarTypeConfig { */ export class GraphQLObjectType { name: string; - description: string | void; - astNode: ObjectTypeDefinitionNode | void; - extensionASTNodes: ReadonlyArray | void; - isTypeOf: GraphQLIsTypeOfFn | void; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + isTypeOf: Maybe>; constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; @@ -335,19 +336,19 @@ export class GraphQLObjectType { export interface GraphQLObjectTypeConfig { name: string; - interfaces?: Thunk; + interfaces?: Thunk>; fields: Thunk>; - isTypeOf?: GraphQLIsTypeOfFn | void; - description?: string | void; - astNode?: ObjectTypeDefinitionNode | void; - extensionASTNodes?: ReadonlyArray | void; + isTypeOf?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; } export type GraphQLTypeResolver = ( value: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise; +) => MaybePromise>; export type GraphQLIsTypeOfFn = ( source: TSource, @@ -385,9 +386,9 @@ export interface GraphQLFieldConfig; subscribe?: GraphQLFieldResolver; - deprecationReason?: string | void; - description?: string | void; - astNode?: FieldDefinitionNode | void; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldConfigArgumentMap = { [key: string]: GraphQLArgumentConfig }; @@ -395,8 +396,8 @@ export type GraphQLFieldConfigArgumentMap = { [key: string]: GraphQLArgumentConf export interface GraphQLArgumentConfig { type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldConfigMap = { @@ -405,22 +406,22 @@ export type GraphQLFieldConfigMap = { export interface GraphQLField { name: string; - description: string | void; + description: Maybe; type: GraphQLOutputType; args: GraphQLArgument[]; resolve?: GraphQLFieldResolver; subscribe?: GraphQLFieldResolver; isDeprecated?: boolean; - deprecationReason?: string | void; - astNode?: FieldDefinitionNode | void; + deprecationReason?: Maybe; + astNode?: Maybe; } export interface GraphQLArgument { name: string; type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldMap = { @@ -447,10 +448,10 @@ export type GraphQLFieldMap = { */ export class GraphQLInterfaceType { name: string; - description: string | void; - astNode?: InterfaceTypeDefinitionNode | void; - extensionASTNodes: ReadonlyArray | void; - resolveType: GraphQLTypeResolver | void; + description: Maybe; + astNode?: Maybe; + extensionASTNodes: Maybe>; + resolveType: Maybe>; constructor(config: GraphQLInterfaceTypeConfig); @@ -469,10 +470,10 @@ export interface GraphQLInterfaceTypeConfig { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver | void; - description?: string | void; - astNode?: InterfaceTypeDefinitionNode | void; - extensionASTNodes?: ReadonlyArray | void; + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; } /** @@ -500,9 +501,9 @@ export interface GraphQLInterfaceTypeConfig { */ export class GraphQLUnionType { name: string; - description: string | void; - astNode?: UnionTypeDefinitionNode | void; - resolveType: GraphQLTypeResolver | void; + description: Maybe; + astNode?: Maybe; + resolveType: Maybe>; constructor(config: GraphQLUnionTypeConfig); @@ -521,9 +522,9 @@ export interface GraphQLUnionTypeConfig { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver | void; - description?: string | void; - astNode?: UnionTypeDefinitionNode | void; + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; } /** @@ -549,15 +550,15 @@ export interface GraphQLUnionTypeConfig { */ export class GraphQLEnumType { name: string; - description: string | void; - astNode: EnumTypeDefinitionNode | void; + description: Maybe; + astNode: Maybe; constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; - getValue(name: string): GraphQLEnumValue | void; - serialize(value: any): string | void; - parseValue(value: any): any; - parseLiteral(valueNode: ValueNode, _variables: { [key: string]: any } | void): any; + getValue(name: string): Maybe; + serialize(value: any): Maybe; + parseValue(value: any): Maybe; + parseLiteral(valueNode: ValueNode, _variables: Maybe<{ [key: string]: any }>): Maybe; toString(): string; toJSON(): string; inspect(): string; @@ -566,25 +567,25 @@ export class GraphQLEnumType { export interface GraphQLEnumTypeConfig { name: string; values: GraphQLEnumValueConfigMap; - description?: string | void; - astNode?: EnumTypeDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLEnumValueConfigMap = { [key: string]: GraphQLEnumValueConfig }; export interface GraphQLEnumValueConfig { value?: any; - deprecationReason?: string | void; - description?: string | void; - astNode?: EnumValueDefinitionNode | void; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; } export interface GraphQLEnumValue { name: string; - description: string | void; + description: Maybe; isDeprecated?: boolean; - deprecationReason: string | void; - astNode?: EnumValueDefinitionNode | void; + deprecationReason: Maybe; + astNode?: Maybe; value: any; } @@ -610,8 +611,8 @@ export interface GraphQLEnumValue { */ export class GraphQLInputObjectType { name: string; - description: string | void; - astNode: InputObjectTypeDefinitionNode | void; + description: Maybe; + astNode: Maybe; constructor(config: GraphQLInputObjectTypeConfig); getFields(): GraphQLInputFieldMap; toString(): string; @@ -622,15 +623,15 @@ export class GraphQLInputObjectType { export interface GraphQLInputObjectTypeConfig { name: string; fields: Thunk; - description?: string | void; - astNode?: InputObjectTypeDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export interface GraphQLInputFieldConfig { type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLInputFieldConfigMap = { @@ -641,8 +642,8 @@ export interface GraphQLInputField { name: string; type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLInputFieldMap = { [key: string]: GraphQLInputField }; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index f6e19f674d..ca9e947640 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLFieldConfigArgumentMap, GraphQLArgument } from "./definition"; import { DirectiveDefinitionNode } from "../language/ast"; import { DirectiveLocationEnum } from "../language/directiveLocation"; @@ -13,20 +14,20 @@ export function isDirective(directive: any): directive is GraphQLDirective; */ export class GraphQLDirective { name: string; - description: string | void; + description: Maybe; locations: DirectiveLocationEnum[]; args: GraphQLArgument[]; - astNode: DirectiveDefinitionNode | void; + astNode: Maybe; constructor(config: GraphQLDirectiveConfig); } export interface GraphQLDirectiveConfig { name: string; - description?: string | void; + description?: Maybe; locations: DirectiveLocationEnum[]; - args?: GraphQLFieldConfigArgumentMap | void; - astNode?: DirectiveDefinitionNode | void; + args?: Maybe; + astNode?: Maybe; } /** diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index a7bb94f5c5..b5ddc9d8d4 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLObjectType } from "./definition"; import { GraphQLType, GraphQLNamedType, GraphQLAbstractType } from "./definition"; import { SchemaDefinitionNode } from "../language/ast"; @@ -35,21 +36,21 @@ export function isSchema(schema: any): schema is GraphQLSchema; * */ export class GraphQLSchema { - astNode: SchemaDefinitionNode | void; + astNode: Maybe; constructor(config: GraphQLSchemaConfig); - getQueryType(): GraphQLObjectType | void; - getMutationType(): GraphQLObjectType | void; - getSubscriptionType(): GraphQLObjectType | void; + getQueryType(): Maybe; + getMutationType(): Maybe; + getSubscriptionType(): Maybe; getTypeMap(): TypeMap; - getType(name: string): GraphQLNamedType | void; + getType(name: string): Maybe; getPossibleTypes(abstractType: GraphQLAbstractType): ReadonlyArray; isPossibleType(abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType): boolean; getDirectives(): ReadonlyArray; - getDirective(name: string): GraphQLDirective | void; + getDirective(name: string): Maybe; } type TypeMap = { [key: string]: GraphQLNamedType }; @@ -72,14 +73,14 @@ export interface GraphQLSchemaValidationOptions { * This option is provided to ease adoption and may be removed in a future * major release. */ - allowedLegacyNames?: ReadonlyArray | void; + allowedLegacyNames?: Maybe>; } export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { - query: GraphQLObjectType | void; - mutation?: GraphQLObjectType | void; - subscription?: GraphQLObjectType | void; - types?: GraphQLNamedType[] | void; - directives?: GraphQLDirective[] | void; - astNode?: SchemaDefinitionNode | void; + query: Maybe; + mutation?: Maybe; + subscription?: Maybe; + types?: Maybe; + directives?: Maybe; + astNode?: Maybe; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index 1c2f139642..826704a52b 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLSchema } from "../type/schema"; import { GraphQLOutputType, @@ -28,14 +29,15 @@ export class TypeInfo { initialType?: GraphQLType ); - getType(): GraphQLOutputType | void; - getParentType(): GraphQLCompositeType | void; - getInputType(): GraphQLInputType | void; - getParentInputType(): GraphQLInputType | void; - getFieldDef(): GraphQLField | void; - getDirective(): GraphQLDirective | void; - getArgument(): GraphQLArgument | void; - getEnumValue(): GraphQLEnumValue | void; + getType(): Maybe; + getParentType(): Maybe; + getInputType(): Maybe; + getParentInputType(): Maybe; + getFieldDef(): GraphQLField>; + getDefaultValue(): Maybe; + getDirective(): Maybe; + getArgument(): Maybe; + getEnumValue(): Maybe; enter(node: ASTNode): any; leave(node: ASTNode): any; } @@ -44,4 +46,4 @@ type getFieldDef = ( schema: GraphQLSchema, parentType: GraphQLType, fieldNode: FieldNode -) => GraphQLField | void; +) => Maybe>; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 9c2198e6d6..e6c9f1ba6c 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ValueNode } from "../language/ast"; import { GraphQLInputType } from "../type/definition"; @@ -18,4 +19,4 @@ import { GraphQLInputType } from "../type/definition"; * | null | NullValue | * */ -export function astFromValue(value: any, type: GraphQLInputType): ValueNode | void; +export function astFromValue(value: any, type: GraphQLInputType): Maybe; diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index ebff50b4f7..e2406c7ee1 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DocumentNode, Location, @@ -47,7 +48,7 @@ type TypeDefinitionsMap = { [key: string]: TypeDefinitionNode }; type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; export class ASTDefinitionBuilder { - constructor(typeDefinitionsMap: TypeDefinitionsMap, options: BuildSchemaOptions | void, resolveType: TypeResolver); + constructor(typeDefinitionsMap: TypeDefinitionsMap, options: Maybe, resolveType: TypeResolver); buildTypes(nodes: ReadonlyArray): Array; @@ -69,7 +70,7 @@ export class ASTDefinitionBuilder { */ export function getDescription( node: { readonly description?: StringValueNode; readonly loc?: Location }, - options: BuildSchemaOptions | void + options: Maybe ): string | undefined; /** diff --git a/types/graphql/utilities/getOperationAST.d.ts b/types/graphql/utilities/getOperationAST.d.ts index 81e9bd4cbe..a36cfa139c 100644 --- a/types/graphql/utilities/getOperationAST.d.ts +++ b/types/graphql/utilities/getOperationAST.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DocumentNode, OperationDefinitionNode } from "../language/ast"; /** @@ -7,5 +8,5 @@ import { DocumentNode, OperationDefinitionNode } from "../language/ast"; */ export function getOperationAST( documentAST: DocumentNode, - operationName: string | void -): OperationDefinitionNode | void; + operationName: Maybe +): Maybe; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index 750fe0d99c..f2172595f8 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DirectiveLocationEnum } from "../language/directiveLocation"; export interface IntrospectionOptions { @@ -16,8 +17,8 @@ export interface IntrospectionQuery { export interface IntrospectionSchema { readonly queryType: IntrospectionNamedTypeRef; - readonly mutationType: IntrospectionNamedTypeRef | void; - readonly subscriptionType: IntrospectionNamedTypeRef | void; + readonly mutationType: Maybe>; + readonly subscriptionType: Maybe>; readonly types: ReadonlyArray; readonly directives: ReadonlyArray; } @@ -42,13 +43,13 @@ export type IntrospectionInputType = IntrospectionScalarType | IntrospectionEnum export interface IntrospectionScalarType { readonly kind: "SCALAR"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; } export interface IntrospectionObjectType { readonly kind: "OBJECT"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly fields: ReadonlyArray; readonly interfaces: ReadonlyArray>; } @@ -56,7 +57,7 @@ export interface IntrospectionObjectType { export interface IntrospectionInterfaceType { readonly kind: "INTERFACE"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly fields: ReadonlyArray; readonly possibleTypes: ReadonlyArray>; } @@ -64,21 +65,21 @@ export interface IntrospectionInterfaceType { export interface IntrospectionUnionType { readonly kind: "UNION"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly possibleTypes: ReadonlyArray>; } export interface IntrospectionEnumType { readonly kind: "ENUM"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly enumValues: ReadonlyArray; } export interface IntrospectionInputObjectType { readonly kind: "INPUT_OBJECT"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly inputFields: ReadonlyArray; } @@ -114,30 +115,30 @@ export interface IntrospectionNamedTypeRef; readonly args: ReadonlyArray; readonly type: IntrospectionOutputTypeRef; readonly isDeprecated: boolean; - readonly deprecationReason?: string | void; + readonly deprecationReason?: Maybe; } export interface IntrospectionInputValue { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly type: IntrospectionInputTypeRef; - readonly defaultValue?: string | void; + readonly defaultValue?: Maybe; } export interface IntrospectionEnumValue { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly isDeprecated: boolean; - readonly deprecationReason?: string | void; + readonly deprecationReason?: Maybe; } export interface IntrospectionDirective { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly locations: ReadonlyArray; readonly args: ReadonlyArray; } diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index cd67108aad..c95eca9002 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLInputType } from "../type/definition"; import { ValueNode, VariableNode, ListValueNode, ObjectValueNode } from "../language/ast"; @@ -22,7 +23,7 @@ import { ValueNode, VariableNode, ListValueNode, ObjectValueNode } from "../lang * */ export function valueFromAST( - valueNode: ValueNode | void, + valueNode: Maybe, type: GraphQLInputType, - variables?: { [key: string]: any } | void + variables?: Maybe<{ [key: string]: any }> ): any; diff --git a/types/graphql/utilities/valueFromASTUntyped.d.ts b/types/graphql/utilities/valueFromASTUntyped.d.ts index 98d3137694..4ca58ca867 100644 --- a/types/graphql/utilities/valueFromASTUntyped.d.ts +++ b/types/graphql/utilities/valueFromASTUntyped.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ValueNode } from "../language/ast"; /** @@ -16,4 +17,4 @@ import { ValueNode } from "../language/ast"; * | Null | null | * */ -export function valueFromASTUntyped(valueNode: ValueNode, variables?: { [key: string]: any } | void): any; +export function valueFromASTUntyped(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; diff --git a/types/graphql/validation/ValidationContext.d.ts b/types/graphql/validation/ValidationContext.d.ts index 0f8a4ea8f7..24049decdf 100644 --- a/types/graphql/validation/ValidationContext.d.ts +++ b/types/graphql/validation/ValidationContext.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError } from "../error"; import { DocumentNode, @@ -19,7 +20,11 @@ import { GraphQLDirective } from "../type/directives"; import { TypeInfo } from "../utilities/TypeInfo"; type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; -type VariableUsage = { node: VariableNode; type: GraphQLInputType | void }; +type VariableUsage = { + readonly node: VariableNode; + readonly type: Maybe; + readonly defaultValue: Maybe; +}; /** * An instance of this class is passed as the "this" context to all validators, @@ -37,7 +42,7 @@ export default class ValidationContext { getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinitionNode | void; + getFragment(name: string): Maybe; getFragmentSpreads(node: SelectionSetNode): ReadonlyArray; @@ -47,17 +52,17 @@ export default class ValidationContext { getRecursiveVariableUsages(operation: OperationDefinitionNode): ReadonlyArray; - getType(): GraphQLOutputType | void; + getType(): Maybe; - getParentType(): GraphQLCompositeType | void; + getParentType(): Maybe; - getInputType(): GraphQLInputType | void; + getInputType(): Maybe; - getParentInputType(): GraphQLInputType | void; + getParentInputType(): Maybe; - getFieldDef(): GraphQLField | void; + getFieldDef(): Maybe>; - getDirective(): GraphQLDirective | void; + getDirective(): Maybe; - getArgument(): GraphQLArgument | void; + getArgument(): Maybe; } diff --git a/types/graphql/validation/rules/NoUndefinedVariables.d.ts b/types/graphql/validation/rules/NoUndefinedVariables.d.ts index 611ad01a9b..f340b41ad8 100644 --- a/types/graphql/validation/rules/NoUndefinedVariables.d.ts +++ b/types/graphql/validation/rules/NoUndefinedVariables.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function undefinedVarMessage(varName: string, opName: string | void): string; +export function undefinedVarMessage(varName: string, opName: Maybe): string; /** * No undefined variables diff --git a/types/graphql/validation/rules/NoUnusedVariables.d.ts b/types/graphql/validation/rules/NoUnusedVariables.d.ts index 10282cdacd..1846995a1f 100644 --- a/types/graphql/validation/rules/NoUnusedVariables.d.ts +++ b/types/graphql/validation/rules/NoUnusedVariables.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function unusedVariableMessage(varName: string, opName: string | void): string; +export function unusedVariableMessage(varName: string, opName: Maybe): string; /** * No unused variables diff --git a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts index fef0869710..54b1fec36a 100644 --- a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts +++ b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function singleFieldOnlyMessage(name: string | void): string; +export function singleFieldOnlyMessage(name: Maybe): string; /** * Subscriptions must only include one field. diff --git a/types/gulp-svgmin/gulp-svgmin-tests.ts b/types/gulp-svgmin/gulp-svgmin-tests.ts new file mode 100644 index 0000000000..2d3d6e7e44 --- /dev/null +++ b/types/gulp-svgmin/gulp-svgmin-tests.ts @@ -0,0 +1,51 @@ +import svgmin = require("gulp-svgmin"); +import { basename, extname } from "path"; + +// From tests + +svgmin({ plugins: [] }); +svgmin({ plugins: [{ removeDoctype: false }] }); +svgmin({ plugins: [{ removeDoctype: false }, { removeComments: false }] }); + +// From examples given in README + +// $ExpectType Transform +svgmin(); + +// $ExpectType Transform +svgmin({ + plugins: [{ + removeDoctype: false + }, { + removeComments: false + }, { + cleanupNumericValues: { + floatPrecision: 2 + } + }, { + convertColors: { + names2hex: false, + rgb2hex: false + } + }] +}); + +// $ExpectType Transform +svgmin({ + js2svg: { + pretty: true + } +}); + +// $ExpectType Transform +svgmin(function getOptions(file) { + const prefix = basename(file.relative, extname(file.relative)); + return { + plugins: [{ + cleanupIDs: { + prefix: prefix + '-', + minify: true + } + }] + }; +}); diff --git a/types/gulp-svgmin/index.d.ts b/types/gulp-svgmin/index.d.ts new file mode 100644 index 0000000000..08c84bc930 --- /dev/null +++ b/types/gulp-svgmin/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gulp-svgmin 1.2 +// Project: https://github.com/ben-eb/gulp-svgmin +// Definitions by: Aankhen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +// (required because svgo specifies 2.2) + +/// + +import SVGO = require("svgo"); +import { Transform } from "stream"; +import * as File from "vinyl"; + +export = GulpSvgmin; + +declare function GulpSvgmin(cb: (file: File) => SVGO.Options): Transform; +declare function GulpSvgmin(options?: SVGO.Options): Transform; diff --git a/types/gulp-svgmin/tsconfig.json b/types/gulp-svgmin/tsconfig.json new file mode 100644 index 0000000000..1d94db7181 --- /dev/null +++ b/types/gulp-svgmin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-svgmin-tests.ts" + ] +} diff --git a/types/gulp-svgmin/tslint.json b/types/gulp-svgmin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-svgmin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hexo-log/hexo-log-tests.ts b/types/hexo-log/hexo-log-tests.ts index 9d0c263c03..a6fbcced57 100644 --- a/types/hexo-log/hexo-log-tests.ts +++ b/types/hexo-log/hexo-log-tests.ts @@ -1,90 +1,52 @@ -import mocha = require('mocha'); -import chai = require('chai'); -const should = chai.should(); -import rewire = require('rewire'); -import sinon = require('sinon'); import logger = require('hexo-log'); -const _c = logger(); -type HexoLogger = typeof _c; +declare function it(s: string, cb: () => void): void; -describe('hexo-log', () => { - const loggerModule = rewire<(options?: { name?: string; silent?: boolean; debug?: boolean; }) => HexoLogger>('./'); +it('add alias for levels', () => { + const log = logger(); - it('add alias for levels', () => { - const log = logger(); - - log.d.should.eql(log.debug); - log.i.should.eql(log.info); - log.w.should.eql(log.warn); - log.e.should.eql(log.error); - log.log.should.eql(log.info); - }); - - it('default name is hexo', () => { - const log = logger(); - - log.fields.name.should.eql('hexo'); - }); - - it('options.name', () => { - const log = logger({ name: 'foo' }); - - log.fields.name.should.eql('foo'); - }); - - it('level should be trace if options.debug is true', () => { - const log: any = logger({ debug: true }); - - log.streams[0].level.should.eql(10); - }); - - it('should add file stream if options.debug is true', () => { - const log: any = logger({ debug: true }); - - log.streams[1].path.should.eql('debug.log'); - }); - - it('should remove console stream if options.silent is true', () => { - const log: any = logger({ silent: true }); - - log.streams.length.should.eql(0); - }); - - it('should display time if options.debug is true', () => { - const spy = sinon.spy(); - const now = new Date(); - - loggerModule.__with__({ - process: { - stdout: { - write: spy - } - } - })(() => { - sinon.useFakeTimers(now.valueOf()); - const log = loggerModule({ debug: true }); - log.info('test'); - sinon.restore(undefined); - }); - - spy.args[0][0].should.contain(now.toISOString().substring(11, 23)); - }); - - it('should print error to process.stderr stream', () => { - const spy = sinon.spy(); - - loggerModule.__with__({ - process: { - stderr: { - write: spy - } - } - })(() => { - const log = loggerModule(); - log.error('test'); - }); - - spy.calledOnce.should.be.true; - }); + log.d === log.debug; + log.i === log.info; + log.w === log.warn; + log.e === log.error; + log.log === log.info; +}); + +it('default name is hexo', () => { + const log = logger(); + + log.fields.name === 'hexo'; +}); + +it('options.name', () => { + const log = logger({ name: 'foo' }); + log.fields === 'foo'; +}); + +it('level should be trace if options.debug is true', () => { + const log = logger({ debug: true }); + // TODO + // log.streams[0].level.should.eql(10); +}); + +it('should add file stream if options.debug is true', () => { + const log = logger({ debug: true }); + // TODO + // log.streams[1].path === 'debug.log'; +}); + +it('should remove console stream if options.silent is true', () => { + const log = logger({ silent: true }); + // TODO + // log.streams.length === 0; +}); + +it('should display time if options.debug is true', () => { + const log = logger({ debug: true }); + log.info('test'); +}); + +it('should print error to process.stderr stream', () => { + const log = logger(); + log.error('test'); }); diff --git a/types/ids/ids-tests.ts b/types/ids/ids-tests.ts deleted file mode 100644 index 16ba06e34f..0000000000 --- a/types/ids/ids-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import Ids = require('ids'); - -const ids = new Ids(); - -const next = ids.next(); // returns id - -ids.claim('f71a81'); // claim id as already existing - -ids.assigned('f71a81'); // true if id was already generated / claimed diff --git a/types/ids/index.d.ts b/types/ids/index.d.ts deleted file mode 100644 index f744f77a5c..0000000000 --- a/types/ids/index.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Type definitions for ids 0.2.0 -// Project: https://github.com/bpmn-io/ids -// Definitions by: Jan Steinbruecker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = Ids; - -declare class Ids { - - /** - * Create a new id generator / cache instance. - * @param {number[]} [seed] a seed that is used internally. - */ - constructor(seed?: number[]); - - /** - * Returns true if the given id has already been assigned. - * @param {string} id - * @return {boolean} - */ - assigned(id: string): boolean; - - /** - * Manually claim an existing id. - * @param {string} id - * @param {*} [element] element the id is claimed by - */ - claim(id: string, element?: any): void; - - /** Clear all claimed ids. */ - clear(): void; - - /** - * Generate a next id. - * @param {*} [element] element to bind the id to - * @return {string} id - */ - next(element?: any): string; - - /** - * Generate a next id with a given prefix. - * @param {*} [element] element to bind the id to - * @return {string} id - */ - nextPrefixed(prefix: string, element?: any): string; - - /** - * Unclaim an id. - * @param {string} id - the id to unclaim - */ - unclaim(id: string): void; - -} diff --git a/types/ids/tslint.json b/types/ids/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/ids/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/in-app-purchase/in-app-purchase-tests.ts b/types/in-app-purchase/in-app-purchase-tests.ts new file mode 100644 index 0000000000..4e142e53e2 --- /dev/null +++ b/types/in-app-purchase/in-app-purchase-tests.ts @@ -0,0 +1,38 @@ +import * as iap from 'in-app-purchase'; + +iap.config({ + /* Configurations for Amazon Store */ + amazonAPIVersion: 2, // tells the module to use API version 2 + secret: 'abcdefghijklmnoporstuvwxyz', // this comes from Amazon + + /* Configurations for Apple */ + applePassword: 'abcdefg...', // this comes from iTunes Connect (You need this to valiate subscriptions) + + /* Configurations for Google Play */ + googlePublicKeyPath: 'path/to/public/key/directory/', // this is the path to the directory containing iap-sanbox/iap-live files + googleAccToken: 'abcdef...', // optional, for Google Play subscriptions + googleRefToken: 'dddd...', // optional, for Google Play subscritions + clientId: 'aaaa', // optional, for Google Play subscriptions + clientSecret: 'bbbb', // optional, for Google Play subscriptions + refreshToken: 'cccc', // optional, for Google Play subscriptions + + /* Configurations for Roku */ + rokuApiKey: 'aaaa...', // this comes from Roku Developer Dashboard + + /* Configurations all platforms */ + test: true, // For Apple and Googl Play to force Sandbox validation only + verbose: true // Output debug logs to stdout stream +}); +iap.setup() + .then(() => iap.validate('abcdef')) + .then((validatedData) => { + const options = { + ignoreCanceled: true, // Apple ONLY (for now...): purchaseData will NOT contain cancceled items + ignoreExpired: true // purchaseData will NOT contain exipired subscription items + }; + + const purchaseData = iap.getPurchaseData(validatedData, options); + }) + .catch((error) => { + // error... + }); diff --git a/types/in-app-purchase/index.d.ts b/types/in-app-purchase/index.d.ts new file mode 100644 index 0000000000..b27daf2c20 --- /dev/null +++ b/types/in-app-purchase/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for in-app-purchase 1.9 +// Project: https://github.com/voltrue2/in-app-purchase#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export const UNITY = 'unity'; +export const APPLE = 'apple'; +export const GOOGLE = 'google'; +export const WINDOWS = 'windows'; +export const AMAZON = 'amazon'; +export const ROKU = 'roku'; + +export function config(params: Config): void; +export function setup(): Promise; +export function setup(callback: (err: any) => void): void; +export function getService(receipt: Receipt): Service; + +export function validate(receipt: Receipt): Promise; +export function validate(receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; +export function validate(service: Service, receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; + +export function validateOnce(receipt: Receipt, secretOrPubKey: any): Promise; +export function validateOnce(receipt: Receipt, secretOrPubKey: any, callback: (err: any, res: ValidationResponse) => void): void; +export function validateOnce(service: Service, secretOrPubKey: any, receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; + +export function isValidated(response: ValidationResponse): boolean; +export function isExpired(item: PurchasedItem): boolean; +export function getPurchaseData(purchaseData?: ValidationResponse, options?: { + ignoreCanceled: boolean; + ignoreExpired: boolean; +}): PurchasedItem[] | null; + +export function refreshGoogleToken(): Promise; +export function refreshGoogleToken(callback: (err: any) => void): void; + +// for test use only, resets the google setup +export function reset(): void; + +export interface Config { + /* Configurations for Amazon Store */ + amazonAPIVersion?: number; + secret?: string; + + /* Configurations for Apple */ + + // this comes from iTunes Connect (You need this to valiate subscriptions) + applePassword?: string; + + /* Configurations for Google Play */ + // this is the path to the directory containing iap-sanbox/iap-live files + googlePublicKeyPath?: string; + // optional, for Google Play subscriptions + googleAccToken?: string; + // optional, for Google Play subscritions + googleRefToken?: string; + // optional, for Google Play subscriptions + clientId?: string; + // optional, for Google Play subscriptions + clientSecret?: string; + // optional, for Google Play subscriptions + refreshToken?: string; + + /* Configurations for Roku */ + // this comes from Roku Developer Dashboard + rokuApiKey?: string; + + /* Configurations all platforms */ + // For Apple and Googl Play to force Sandbox validation only + test?: boolean; + // Output debug logs to stdout stream + verbose?: boolean; +} + +export type Service = typeof UNITY | typeof APPLE | typeof GOOGLE | typeof WINDOWS | typeof AMAZON | typeof ROKU; + +export type UnityReceipt = object | string; +export type AppleReceipt = string; +export type GoogleReceipt = { + date: string; + signature: string; +} | string; +export type WindowsReceipt = string; +export type AmazonReceipt = object | string; +export type RokuReceipt = string; + +export type Receipt = UnityReceipt | AppleReceipt | GoogleReceipt | WindowsReceipt | AmazonReceipt | RokuReceipt; + +export interface ValidationResponse { + service: Service; + status: number; + // there are more fields depending on the used service +} + +export interface PurchasedItem { + bundleId?: string; // only Apple + orderId?: string; // only Google + transactionId: string; + productId: string; + purchaseDate: number; + // iTunes, windows and amazon subscription only + // Google subscriptions only with google play store api info + expirationDate?: number; + quantity: number; + // this was created based on the source code of in-app-purchase + // eventually there are more fields +} diff --git a/types/in-app-purchase/tsconfig.json b/types/in-app-purchase/tsconfig.json new file mode 100644 index 0000000000..7752182f8a --- /dev/null +++ b/types/in-app-purchase/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", + "in-app-purchase-tests.ts" + ] +} diff --git a/types/in-app-purchase/tslint.json b/types/in-app-purchase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/in-app-purchase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/intercom-web/index.d.ts b/types/intercom-web/index.d.ts index a0b4e71015..563d241c31 100755 --- a/types/intercom-web/index.d.ts +++ b/types/intercom-web/index.d.ts @@ -4,6 +4,7 @@ // customize-the-intercom-messenger/the-intercom-javascript-api // Definitions by: Andrew Fong // Samer Albahra +// Onat Yigit Mercan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Intercom_ { @@ -27,6 +28,8 @@ declare namespace Intercom_ { monthly_spend?: number, [index: string]: any; }; + vertical_padding?: number; + horizontal_padding?: number; } type IntercomCommand = 'boot' diff --git a/types/intercom-web/intercom-web-tests.ts b/types/intercom-web/intercom-web-tests.ts index 22eeddc8fa..b07013322d 100755 --- a/types/intercom-web/intercom-web-tests.ts +++ b/types/intercom-web/intercom-web-tests.ts @@ -60,3 +60,15 @@ intercomSettings = { user_id: "12345", user_hash: "775c502lcc1087d12398571837c" }; + +/* + From https://docs.intercom.com/configure-intercom-for-your-product-or-site/ + customize-the-intercom-messenger/ + customize-the-intercom-messenger-technical +*/ +intercomSettings = { + app_id: "pi3243fa", + alignment: "left", + horizontal_padding: 20, + vertical_padding: 20 +}; diff --git a/types/jest-axe/index.d.ts b/types/jest-axe/index.d.ts new file mode 100644 index 0000000000..f16f4e7651 --- /dev/null +++ b/types/jest-axe/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for jest-axe 2.2 +// Project: https://github.com/nickcolley/jest-axe +// Definitions by: Josh Goldberg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +import { AxeResults, Result, RunOnly } from "axe-core"; + +/** + * Version of the aXe verifier with defaults set. + * + * @remarks You can still pass additional options to this new instance; + * they will be merged with the defaults. + */ +export const axe: JestAxe; + +/** + * Core options to run aXe. + */ +export interface AxeOptions { + elementRef?: boolean; + iframes?: boolean; + rules?: object; + runOnly?: RunOnly; + selectors?: boolean; +} + +/** + * Runs aXe on HTML. + * + * @param html Raw HTML string to verify with aXe. + * @param options Options to run aXe. + * @returns Promise for the results of running aXe. + */ +export type JestAxe = (html: string, options?: AxeOptions) => Promise; + +/** + * Creates a new aXe verifier function. + * + * @param options Options to run aXe. + * @returns New aXe verifier function. + */ +export function configureAxe(options?: AxeOptions): JestAxe; + +/** + * Results from asserting whether aXe verification passed. + */ +export interface AssertionsResult { + /** + * Actual checked aXe verification results. + */ + actual: Result[]; + + /** + * @returns Message from the Jest assertion. + */ + message(): string; + + /** + * Whether the assertion passed. + */ + pass: boolean; +} + +/** + * Asserts an aXe-verified result has no violations. + * + * @param results aXe verification result, if not running via expect(). + * @returns Jest expectations for the aXe result. + */ +export type IToHaveNoViolations = (results?: Partial) => AssertionsResult; + +export const toHaveNoViolations: { + toHaveNoViolations: IToHaveNoViolations; +}; + +declare global { + namespace jest { + interface Matchers { + toHaveNoViolations: IToHaveNoViolations; + } + } +} diff --git a/types/jest-axe/jest-axe-tests.ts b/types/jest-axe/jest-axe-tests.ts new file mode 100644 index 0000000000..38caeb88eb --- /dev/null +++ b/types/jest-axe/jest-axe-tests.ts @@ -0,0 +1,19 @@ +import { configureAxe, axe, toHaveNoViolations, JestAxe } from "jest-axe"; + +expect.extend(toHaveNoViolations); + +const newJestWithDefaults: JestAxe = configureAxe(); + +const newJestWithOptions: JestAxe = configureAxe({ + elementRef: false, + iframes: false, + rules: {}, + runOnly: { + type: "rules", + }, + selectors: false, +}); + +const sameJest: JestAxe = axe; + +expect("").toHaveNoViolations(); diff --git a/types/jest-axe/package.json b/types/jest-axe/package.json new file mode 100644 index 0000000000..d9427293a7 --- /dev/null +++ b/types/jest-axe/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "axe-core": "^2.6.1" + } +} diff --git a/types/jest-axe/tsconfig.json b/types/jest-axe/tsconfig.json new file mode 100644 index 0000000000..887813c869 --- /dev/null +++ b/types/jest-axe/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jest-axe-tests.ts" + ] +} diff --git a/types/jest-axe/tslint.json b/types/jest-axe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jest-axe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsonic/index.d.ts b/types/jsonic/index.d.ts new file mode 100644 index 0000000000..610101b136 --- /dev/null +++ b/types/jsonic/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jsonic 0.3 +// Project: https://github.com/rjrodger/jsonic +// Definitions by: Rong SHen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function jsonic(text: string): any; +declare namespace jsonic { + interface Options { + depth?: number; + maxitems?: number; + maxchars?: number; + omit?: string[]; + exclude?: string[]; + } + + function stringify(val: any, opts?: Options): string; +} + +export = jsonic; diff --git a/types/jsonic/jsonic-tests.ts b/types/jsonic/jsonic-tests.ts new file mode 100644 index 0000000000..fb0df5dd95 --- /dev/null +++ b/types/jsonic/jsonic-tests.ts @@ -0,0 +1,7 @@ +import * as jsonic from "jsonic"; + +jsonic("a:x, b:y z"); +jsonic.stringify( + { a: "a", b: "b", c: { c1: "c1" } }, + { depth: 1, omit: ["a"], exclude: ["b"] } +); diff --git a/types/jsonic/tsconfig.json b/types/jsonic/tsconfig.json new file mode 100644 index 0000000000..88bfd64ef6 --- /dev/null +++ b/types/jsonic/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "jsonic-tests.ts"] +} diff --git a/types/jsonic/tslint.json b/types/jsonic/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonic/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 90a700b7dc..624fde2d01 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -23,7 +23,7 @@ type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string type TableName = string | Knex.Raw | Knex.QueryBuilder; interface Knex extends Knex.QueryInterface { - (tableName?: string): Knex.QueryBuilder; + (tableName?: TableName): Knex.QueryBuilder; VERSION: string; __knex__: string; @@ -179,7 +179,7 @@ declare namespace Knex { } interface Table { - (tableName: string): QueryBuilder; + (tableName: TableName): QueryBuilder; (callback: Function): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -269,8 +269,8 @@ declare namespace Knex { (callback: QueryCallback): QueryBuilder; (object: Object): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; + (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; + (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; } interface WhereRaw extends RawQueryBuilder { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index eaf186a186..9167ad3f77 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -206,6 +206,11 @@ knex('users').where('votes', '>', 100); knex('users').where('votes', null); knex('users').where('votes', 'is not', null); +// Using Raw in where +knex('users').where(knex.raw('votes + 1'), '>', 101); +knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); +knex('users').where('votes', '>', knex.raw('100 + 1')); + var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); knex('accounts').where('id', 'in', subquery); diff --git a/types/natural-sort/index.d.ts b/types/natural-sort/index.d.ts index 4e929d4edc..3a88919a25 100644 --- a/types/natural-sort/index.d.ts +++ b/types/natural-sort/index.d.ts @@ -1,9 +1,18 @@ // Type definitions for NaturalSort // Project: https://github.com/studio-b12/natural-sort // Definitions by: Antonio Morales +// Brian Crowell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace naturalSort; -declare function naturalSort(a: T, b: T): number; +interface Options { + /** Set to true to make the sort case-sensitive. */ + caseSensitive?: boolean; + + /** Set to 'desc' to sort in reverse. */ + direction?: 'desc' +} + +declare function naturalSort(options?: Options): (a: string | number, b: string | number) => number; export = naturalSort; diff --git a/types/natural-sort/natural-sort-tests.ts b/types/natural-sort/natural-sort-tests.ts index b336542520..6218f4e796 100644 --- a/types/natural-sort/natural-sort-tests.ts +++ b/types/natural-sort/natural-sort-tests.ts @@ -1,5 +1,8 @@ import naturalSort = require("natural-sort"); -[5, 3, 2, 4, 1].sort(naturalSort); -["a", "c", "b", "z", "w", "l"].sort(naturalSort); +['10. tenth', 'odd', 1, '', '2. second'].sort(naturalSort()); +[3, 4, 1, 5, 2].sort(naturalSort({direction: 'desc'})); + +['a', 'B'].sort(naturalSort()); +['a', 'B'].sort(naturalSort({caseSensitive: true})); diff --git a/types/net-keepalive/net-keepalive-tests.ts b/types/net-keepalive/net-keepalive-tests.ts index 68b71daff4..71b5104e27 100644 --- a/types/net-keepalive/net-keepalive-tests.ts +++ b/types/net-keepalive/net-keepalive-tests.ts @@ -9,7 +9,7 @@ const server = Net.createServer((socket) => { }) server.listen(1337, '127.0.0.1', () => { - const {port, address} = server.address() + const {port, address} = server.address() as Net.AddressInfo const clientSocket = Net.createConnection({ port, host: address }, () => { @@ -18,4 +18,4 @@ server.listen(1337, '127.0.0.1', () => { NetKeepAlive.setKeepAliveProbes(clientSocket, 1) clientSocket.end() }) -}) \ No newline at end of file +}) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 4696819626..b8ae0864ba 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,15 +1,46 @@ import * as React from "react"; +import * as http from "http"; + +export interface Context { + err?: Error; + req: http.IncomingMessage; + res: http.ServerResponse; + pathname: string; + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + asPath: string; + + renderPage( + enhancer?: (page: React.Component) => React.ComponentType + ): { + html?: string; + head: Array>; + errorHtml: string; + }; +} export interface DocumentProps { __NEXT_DATA__?: any; dev?: boolean; chunks?: string[]; + html?: string; head?: Array>; + errorHtml?: string; styles?: Array>; + [key: string]: any; } export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} -export default class extends React.Component {} +export default class extends React.Component { + static getInitialProps(ctx: Context): DocumentProps; +} diff --git a/types/ngtoaster/index.d.ts b/types/ngtoaster/index.d.ts index caf9bd0539..092e1a7b0e 100644 --- a/types/ngtoaster/index.d.ts +++ b/types/ngtoaster/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angularjs-toaster v0.4.13 +// Type definitions for angularjs-toaster 2.2 // Project: https://github.com/jirikavi/AngularJS-Toaster // Definitions by: Ben Tesser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,100 +10,126 @@ export = ngtoaster; export as namespace toaster; declare namespace ngtoaster { - interface IToasterService { - pop(params:IPopParams): void - /** - * @param {string} type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' - */ - pop(type?:string, title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number, showCloseButton?:boolean): void - error(params: IPopParams): void - error(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - info(params: IPopParams): void - info(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - wait(params: IPopParams): void - wait(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - success(params: IPopParams): void - success(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - warning(params: IPopParams): void - warning(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - clear(): void - toast:IToast; - } + interface IToasterService { + pop(params: IPopParams): void; + /** + * @param type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' + */ + pop(type?: string, title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + error(params: IPopParams): void; + error(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + info(params: IPopParams): void; + info(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + wait(params: IPopParams): void; + wait(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + success(params: IPopParams): void; + success(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + warning(params: IPopParams): void; + warning(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + clear(toasterId?: number, toastId?: string|number): void; + toast: IToast; + } - interface IToasterEventRegistry { - setup(): void - subscribeToNewToastEvent(onNewToast:IToastEventListener): void - subscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - unsubscribeToNewToastEvent(onNewToast:IToastEventListener): void - unsubscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - } + interface IToasterEventRegistry { + setup(): void; + subscribeToNewToastEvent(onNewToast: IToastEventListener): void; + subscribeToClearToastsEvent(onClearToasts: IToastEventListener): void; + unsubscribeToNewToastEvent(onNewToast: IToastEventListener): void; + unsubscribeToClearToastsEvent(onClearToasts: IToastEventListener): void; + } - interface IPopParams extends IToast{ - toasterId?: number; - } + interface IPopParams extends IToast { + toasterId?: number; + } - interface IToastEventListener { - (event:Event, toasterId: number): void; - } + interface IPopReturn { + toasterId: number; + toastId: string|number; + } - interface IToast { - /** - * Acceptable types are: - * 'error', 'info', 'wait', 'success', and 'warning' - */ - type?: string; - title?: string; - body?: string; - timeout?: number; - bodyOutputType?: string; - clickHandler?: EventListener; - showCloseButton?: boolean; - } + type IToastCallback = (toast: IToast) => void; - interface IToasterConfig { - /** - * limits max number of toasts - */ - limit?: number; - 'tap-to-dismiss'?: boolean; - 'close-button'?: boolean; - 'newest-on-top'?: boolean; - 'time-out'?: number; - 'icon-classes'?: IIconClasses; - /** - * Options include: - * '', 'trustedHtml', 'template', 'templateWithData' - */ - 'body-output-type'?: string; - 'body-template'?: string; - 'icon-class'?: string; - /** - * Options include: - * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', - * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', - * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', - */ - 'position-class'?: string; - 'title-class'?: string; - 'message-class'?: string; - 'prevent-duplicates'?: boolean; - /** - * stop timeout on mouseover and restart timer on mouseout - */ - 'mouseover-timer-stop'?: boolean; - } + type IToastEventListener = (event: Event, toasterId: number, toastId: string|number) => void; - interface IIconClasses { - error: string; - info: string; - wait: string; - success: string; - warning: string; - } + interface IToast { + /** + * Acceptable types are: + * 'error', 'info', 'wait', 'success', and 'warning' + */ + type?: string; + title?: string; + body?: string; + timeout?: number; + bodyOutputType?: string; + clickHandler?: EventListener; + showCloseButton?: boolean; + closeHtml?: string; + toastId?: string|number; + /** + * Called when the toast has been displayed. + * @param toast the displayed toast + */ + onShowCallback?: IToastCallback; + /** + * Called when the toast has been removed. + * @param toast the displayed toast + */ + onHideCallback?: IToastCallback; + directiveData?: any; + tapToDismiss?: boolean; + } + + interface IToasterConfig { + /** + * limits max number of toasts + */ + limit?: number; + 'tap-to-dismiss'?: boolean; + 'close-button'?: boolean; + 'close-html'?: string; + 'newest-on-top'?: boolean; + 'time-out'?: number; + 'icon-classes'?: IIconClasses; + /** + * Options include: + * '', 'trustedHtml', 'template', 'templateWithData' + */ + 'body-output-type'?: string; + 'body-template'?: string; + 'icon-class'?: string; + /** + * Options include: + * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', + * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', + * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', + */ + 'position-class'?: string; + 'title-class'?: string; + 'message-class'?: string; + 'prevent-duplicates'?: boolean; + /** + * stop timeout on mouseover and restart timer on mouseout + */ + 'mouseover-timer-stop'?: boolean; + } + + interface IIconClasses { + error: string; + info: string; + wait: string; + success: string; + warning: string; + } } diff --git a/types/ngtoaster/ngtoaster-tests.ts b/types/ngtoaster/ngtoaster-tests.ts index eb30c181d4..0640ba2191 100644 --- a/types/ngtoaster/ngtoaster-tests.ts +++ b/types/ngtoaster/ngtoaster-tests.ts @@ -1,45 +1,57 @@ -import ngtoaster = require("ngtoaster"); -import * as ng from 'angular'; +import ngtoaster = require('ngtoaster'); import * as angular from 'angular'; class NgToasterTestController { - constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public toaster: ngtoaster.IToasterService) { - this.bar = 'Hi'; - } - bar: string; - - pop(): void { - this.toaster.success({ title: "title", body: "text1" }); - this.toaster.error("title", "text2"); - this.toaster.pop({ type: 'wait', title: "title", body: "text" }); - this.toaster.pop('success', "title", '
  • Render html
', 5000, 'trustedHtml'); - this.toaster.pop('error', "title", '
  • Render html
', null, 'trustedHtml'); - this.toaster.pop('wait', "title", null, null, 'template'); - this.toaster.pop('warning', "title", "myTemplate.html", null, 'template'); - this.toaster.pop('note', "title", "text"); - this.toaster.pop('success', "title", 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => { - var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); - if (match) { - this.$window.open(match[0]); - } - return true; - }); - this.toaster.pop('warning', "Hi ", "{template: 'myTemplateWithData.html', data: 'MyData'}", 15000, 'templateWithData'); - } - - goToLink(toaster: ngtoaster.IToast): boolean { - var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); - if (match) { - this.$window.open(match[0]); + constructor( + public $scope: angular.IScope, + public $window: angular.IWindowService, + public toaster: ngtoaster.IToasterService + ) { + this.bar = 'Hi'; } - return true; - } + bar: string; - clear(): void { - this.toaster.clear(); - } + pop(): void { + this.toaster.success({ title: 'title', body: 'text1' }); + this.toaster.error('title', 'text2'); + this.toaster.pop({ + type: 'wait', + title: 'title', + body: 'text', + onShowCallback: (toast) => { + this.toaster.clear(null, toast.toastId); + } + }); + this.toaster.pop('success', 'title', '
  • Render html
', 5000, 'trustedHtml'); + this.toaster.pop('error', 'title', '
  • Render html
', null, 'trustedHtml'); + this.toaster.pop('wait', 'title', null, null, 'template'); + this.toaster.pop('warning', 'title', 'myTemplate.html', null, 'template'); + this.toaster.pop('note', 'title', 'text'); + this.toaster.pop('success', 'title', 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => { + const match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + }); + this.toaster.pop('warning', 'Hi ', `{template: 'myTemplateWithData.html', data: 'MyData'}`, 15000, 'templateWithData'); + } + + goToLink(toaster: ngtoaster.IToast): boolean { + const match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + } + + clear(): void { + this.toaster.clear(); + this.toaster.clear(1); + this.toaster.clear(null, 'mytoast'); + } } angular - .module('main', ['ngAnimate', 'toaster']) - .controller('myController', NgToasterTestController); \ No newline at end of file + .module('main', ['ngAnimate', 'toaster']) + .controller('myController', NgToasterTestController); diff --git a/types/ngtoaster/tslint.json b/types/ngtoaster/tslint.json index a41bf5d19a..eaaf55d976 100644 --- a/types/ngtoaster/tslint.json +++ b/types/ngtoaster/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "interface-name": false } } diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 60c73d850f..b36d014b63 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -158,6 +158,7 @@ declare namespace Nightmare { typeInterval?: number; x?: number; y?: number; + electronPath?: string; openDevTools?: { /** * Opens the devtools with specified dock state, can be right, bottom, undocked, detach. diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 2784d95fa3..703c78aa9b 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -48,6 +48,7 @@ declare module "node-forge" { function publicKeyFromPem(pem: PEM): Key; function privateKeyFromPem(pem: PEM): Key; function certificateToPem(cert: Certificate, maxline?: number): PEM; + function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; interface oids { [key: string]: string; diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 29b8267714..1bb8dff08c 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -8,6 +8,7 @@ let x: string = forge.ssh.privateKeyToOpenSSH(key); let pemKey: forge.pki.PEM = publicKeyPem; let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); +let certPem = forge.pki.certificateFromPem(pemKey); let cert = forge.pki.createCertificate(); { diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 12c9551bec..d228742629 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -13,7 +13,6 @@ // Deividas Bakanas // Kelvin Jin // Alvis HT Tang -// Oliver Joseph Ash // Sebastian Silbermann // Hannes Magnusson // Alberto Schiabel @@ -380,7 +379,7 @@ declare var Buffer: { * Creates a new Buffer using the passed {data} * @param data data to create a new Buffer */ - from(data: any[] | string | Buffer | ArrayBuffer /*| TypedArray*/): Buffer; + from(data: any[] | string | Buffer | ArrayBuffer | Uint8Array /*| TypedArray*/): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. @@ -2666,6 +2665,12 @@ declare module "net" { type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + export interface AddressInfo { + address: string; + family: string; + port: number; + } + export interface SocketConstructorOpts { fd?: number; allowHalfOpen?: boolean; @@ -2713,7 +2718,7 @@ declare module "net" { setTimeout(timeout: number, callback?: Function): this; setNoDelay(noDelay?: boolean): this; setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; unref(): void; ref(): void; @@ -2829,7 +2834,7 @@ declare module "net" { listen(handle: any, backlog?: number, listeningListener?: Function): this; listen(handle: any, listeningListener?: Function): this; close(callback?: Function): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; getConnections(cb: (error: Error | null, count: number) => void): void; ref(): this; unref(): this; @@ -2905,22 +2910,17 @@ declare module "net" { } declare module "dgram" { - import * as events from "events"; + import { AddressInfo } from "net"; import * as dns from "dns"; + import * as events from "events"; - interface RemoteInfo { + export interface RemoteInfo { address: string; family: string; port: number; } - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface BindOptions { + export interface BindOptions { port: number; address?: string; exclusive?: boolean; @@ -2928,7 +2928,7 @@ declare module "dgram" { type SocketType = "udp4" | "udp6"; - interface SocketOptions { + export interface SocketOptions { type: SocketType; reuseAddr?: boolean; recvBufferSize?: number; @@ -2940,14 +2940,14 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; bind(options: BindOptions, callback?: Function): void; close(callback?: () => void): void; - address(): AddressInfo; + address(): AddressInfo | string; setBroadcast(flag: boolean): void; setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; @@ -5624,23 +5624,6 @@ declare module "tls" { prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - export interface SecurePair { encrypted: any; cleartext: any; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index efc00ef201..d428cf8753 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -432,10 +432,13 @@ function bufferTests() { // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); + const arrUint16: Uint16Array = new Uint16Array(2); + arrUint16[0] = 5000; + arrUint16[1] = 4000; + const buf4: Buffer = Buffer.from(arrUint16.buffer); + const arrUint8: Uint8Array = new Uint8Array(2); + const buf5: Buffer = Buffer.from(arrUint8); + const buf6: Buffer = Buffer.from(buf1); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -1551,7 +1554,7 @@ namespace dgram_tests { ds.bind(4123, 'localhost', () => { }); ds.bind(4123, () => { }); ds.bind(() => { }); - var ai: dgram.AddressInfo = ds.address(); + const addr: net.AddressInfo | string = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); ds.send(new Buffer("hello"), 5000, "127.0.0.1"); @@ -1564,7 +1567,7 @@ namespace dgram_tests { let _boolean: boolean; let _err: Error; let _str: string; - let _rinfo: dgram.AddressInfo; + let _rinfo: net.AddressInfo; /** * events.EventEmitter * 1. close @@ -1580,7 +1583,7 @@ namespace dgram_tests { _socket = _socket.addListener("listening", () => { }); _socket = _socket.addListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _boolean = _socket.emit("close"); @@ -1595,7 +1598,7 @@ namespace dgram_tests { _socket = _socket.on("listening", () => { }); _socket = _socket.on("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.once("close", () => { }); @@ -1605,7 +1608,7 @@ namespace dgram_tests { _socket = _socket.once("listening", () => { }); _socket = _socket.once("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependListener("close", () => { }); @@ -1615,7 +1618,7 @@ namespace dgram_tests { _socket = _socket.prependListener("listening", () => { }); _socket = _socket.prependListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependOnceListener("close", () => { }); @@ -1625,7 +1628,7 @@ namespace dgram_tests { _socket = _socket.prependOnceListener("listening", () => { }); _socket = _socket.prependOnceListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); } @@ -2730,10 +2733,7 @@ namespace net_tests { server = server.close((...args: any[]) => { }); // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; + let address: net.AddressInfo | string = server.address(); } { diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 5271a8d06a..45f1c85b64 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -2851,8 +2851,8 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index ef189f57c3..5a76e4cc45 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2657,6 +2657,12 @@ declare module "net" { type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + export interface AddressInfo { + address: string; + family: string; + port: number; + } + export interface SocketConstructorOpts { fd?: number; allowHalfOpen?: boolean; @@ -2704,7 +2710,7 @@ declare module "net" { setTimeout(timeout: number, callback?: Function): this; setNoDelay(noDelay?: boolean): this; setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; unref(): void; ref(): void; @@ -2820,7 +2826,7 @@ declare module "net" { listen(handle: any, backlog?: number, listeningListener?: Function): this; listen(handle: any, listeningListener?: Function): this; close(callback?: Function): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; getConnections(cb: (error: Error | null, count: number) => void): void; ref(): this; unref(): this; @@ -2896,22 +2902,17 @@ declare module "net" { } declare module "dgram" { - import * as events from "events"; + import { AddressInfo } from "net"; import * as dns from "dns"; + import * as events from "events"; - interface RemoteInfo { + export interface RemoteInfo { address: string; family: string; port: number; } - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface BindOptions { + export interface BindOptions { port: number; address?: string; exclusive?: boolean; @@ -2919,7 +2920,7 @@ declare module "dgram" { type SocketType = "udp4" | "udp6"; - interface SocketOptions { + export interface SocketOptions { type: SocketType; reuseAddr?: boolean; recvBufferSize?: number; @@ -2931,14 +2932,14 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; bind(options: BindOptions, callback?: Function): void; close(callback?: () => void): void; - address(): AddressInfo; + address(): AddressInfo | string; setBroadcast(flag: boolean): void; setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; @@ -5139,23 +5140,6 @@ declare module "tls" { prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - export interface SecurePair { encrypted: any; cleartext: any; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index efc00ef201..d6751541b9 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -1551,7 +1551,7 @@ namespace dgram_tests { ds.bind(4123, 'localhost', () => { }); ds.bind(4123, () => { }); ds.bind(() => { }); - var ai: dgram.AddressInfo = ds.address(); + const addr: net.AddressInfo | string = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); ds.send(new Buffer("hello"), 5000, "127.0.0.1"); @@ -1564,7 +1564,7 @@ namespace dgram_tests { let _boolean: boolean; let _err: Error; let _str: string; - let _rinfo: dgram.AddressInfo; + let _rinfo: net.AddressInfo; /** * events.EventEmitter * 1. close @@ -1580,7 +1580,7 @@ namespace dgram_tests { _socket = _socket.addListener("listening", () => { }); _socket = _socket.addListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _boolean = _socket.emit("close"); @@ -1595,7 +1595,7 @@ namespace dgram_tests { _socket = _socket.on("listening", () => { }); _socket = _socket.on("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.once("close", () => { }); @@ -1605,7 +1605,7 @@ namespace dgram_tests { _socket = _socket.once("listening", () => { }); _socket = _socket.once("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependListener("close", () => { }); @@ -1615,7 +1615,7 @@ namespace dgram_tests { _socket = _socket.prependListener("listening", () => { }); _socket = _socket.prependListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependOnceListener("close", () => { }); @@ -1625,7 +1625,7 @@ namespace dgram_tests { _socket = _socket.prependOnceListener("listening", () => { }); _socket = _socket.prependOnceListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); } @@ -2730,10 +2730,7 @@ namespace net_tests { server = server.close((...args: any[]) => { }); // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; + let address: net.AddressInfo | string = server.address(); } { diff --git a/types/passport-http-bearer/index.d.ts b/types/passport-http-bearer/index.d.ts index 58da308106..14f6f91e26 100644 --- a/types/passport-http-bearer/index.d.ts +++ b/types/passport-http-bearer/index.d.ts @@ -28,7 +28,7 @@ interface VerifyFunctionWithRequest { (req: express.Request, token: string, done: (error: any, user?: any, options?: IVerifyOptions | string) => void): void; } -declare class Strategy extends passport.Strategy { +declare class Strategy implements passport.Strategy { constructor(verify: VerifyFunction); constructor(options: IStrategyOptions, verify: VerifyFunction); constructor(options: IStrategyOptions, verify: VerifyFunctionWithRequest); diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 6b405d3e53..ac35dc064b 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -347,6 +347,7 @@ export interface ModeBarButton { // Data export type Datum = string | number | Date; +export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array; export type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; @@ -356,9 +357,9 @@ export type Color = string | Array | Array( range: NodeRange, nodeType: NodeType, - attrs?: { [key: string]: any } + attrs?: { [key: string]: any }, + innerRange?: NodeRange ): Array<{ type: NodeType; attrs?: { [key: string]: any } | null }> | null | undefined; /** * Check whether splitting at the given position is allowed. diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 54ef9b722a..510ae37107 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -900,6 +900,11 @@ export interface FrameBase { selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } ): Promise; + + waitForXPath( + xpath: string, + options?: { visible?: boolean; hidden?: boolean; timeout?: number } + ): Promise; } export interface Frame extends FrameBase { diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index 043c2f5c78..05065e043a 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -117,9 +117,15 @@ puppeteer.launch().then(async browser => { await watchDog; let currentURL: string; + page .waitForSelector("img", { visible: true }) - .then(() => console.log("First URL with image: " + currentURL)); + .then(() => console.log("First URL with image by selector: " + currentURL)); + + page + .waitForXPath("//img", { visible: true }) + .then(() => console.log("First URL with image by xpath: " + currentURL)); + for (currentURL of [ "https://example.com", "https://google.com", diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 5a3b58cd5b..9849ee48b1 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for ramda 0.25 // Project: https://github.com/donnut/typescript-ramda // Definitions by: Erwin Poeze +// Tycho Grouwstra // Matt DeKrey // Matt Dziuban // Stephen King @@ -18,6 +19,7 @@ // Jack Leigh // Keagan McClelland // Tomas Szabo +// Bonggyun Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -1021,11 +1023,13 @@ declare namespace R { median(list: ReadonlyArray): number; /** + * @deprecated since v0.25.0 + * * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an * additional call to fn; instead, the cached result for that set of arguments will be returned. */ - memoize(fn: (...a: any[]) => T): (...a: any[]) => T; + memoize any>(fn: T): T; /** * A customisable version of R.memoize. memoizeWith takes an additional function that will be applied to a given @@ -1487,6 +1491,7 @@ declare namespace R { * Reasonable analog to SQL `select` statement. */ project(props: ReadonlyArray, objs: ReadonlyArray): U[]; + project(props: ReadonlyArray): (objs: ReadonlyArray) => U[]; /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 81eb438535..8cbbf9ceac 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -305,7 +305,7 @@ R.times(i, 5); function stringLength(str: string): number { return str.length; } - const memoStringLength = R.memoize(stringLength); + const memoStringLength = R.memoize(stringLength); const isLong = memoStringLength('short') > 10; // false })(); @@ -1619,6 +1619,7 @@ class Rectangle { const fred = {name: "Fred", age: 12, hair: "brown", grade: 7}; const kids = [abby, fred]; R.project(["name", "grade"], kids); // => [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] + R.project(["name", "grade"])(kids); // => [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] }; () => { diff --git a/types/react-bootstrap-daterangepicker/index.d.ts b/types/react-bootstrap-daterangepicker/index.d.ts index 5a2cfa4735..26fb15f45a 100644 --- a/types/react-bootstrap-daterangepicker/index.d.ts +++ b/types/react-bootstrap-daterangepicker/index.d.ts @@ -11,7 +11,7 @@ declare namespace ReactBootstrapDaterangepicker { export interface EventHandler { (event?: any, picker?: any): any; } - export interface Props extends daterangepicker.Settings{ + export interface Props extends daterangepicker.Options{ onShow?: EventHandler; onHide?: EventHandler; onShowCalendar?: EventHandler; diff --git a/types/react-google-maps-loader/index.d.ts b/types/react-google-maps-loader/index.d.ts new file mode 100644 index 0000000000..1bea9e2a9c --- /dev/null +++ b/types/react-google-maps-loader/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for react-google-maps-loader 4.2 +// Project: https://github.com/xuopled/react-google-maps-loader +// Definitions by: Vasily Nesterov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// +import { Component, ReactNode } from "react"; + +export default ReactGoogleMapsLoader; + +declare class ReactGoogleMapsLoader extends Component< + ReactGoogleMapsLoader.Props +> {} + +declare namespace ReactGoogleMapsLoader { + type GoogleMaps = typeof google.maps; + + interface Params { + key: string; + libraries?: string; + } + + interface Props { + params: Params; + render: (googleMaps: GoogleMaps, error?: string | null) => ReactNode; + } +} diff --git a/types/react-google-maps-loader/react-google-maps-loader-tests.tsx b/types/react-google-maps-loader/react-google-maps-loader-tests.tsx new file mode 100644 index 0000000000..e82c3f6038 --- /dev/null +++ b/types/react-google-maps-loader/react-google-maps-loader-tests.tsx @@ -0,0 +1,23 @@ +import * as React from "react"; +import ReactGoogleMapsLoader from "react-google-maps-loader"; + +const ReactGoogleMapsLoaderTest: React.SFC = () => ( +
} + /> +); + +const ReactGoogleMapsLoaderWithLibrariesTest: React.SFC = () => ( +
} + /> +); + +const ReactGoogleMapsLoaderWithErrorHandlerTest: React.SFC = () => ( +
{error}
} + /> +); diff --git a/types/react-google-maps-loader/tsconfig.json b/types/react-google-maps-loader/tsconfig.json new file mode 100644 index 0000000000..98ee7f63aa --- /dev/null +++ b/types/react-google-maps-loader/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "jsx": "react", + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-google-maps-loader-tests.tsx" + ] +} diff --git a/types/react-google-maps-loader/tslint.json b/types/react-google-maps-loader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-google-maps-loader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-autocomplete-input/index.d.ts b/types/react-native-autocomplete-input/index.d.ts new file mode 100644 index 0000000000..f6c5f06eb6 --- /dev/null +++ b/types/react-native-autocomplete-input/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for react-native-autocomplete-input 3.5 +// Project: https://github.com/l-urence/react-native-autocomplete-input#readme +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { Component, ReactNode } from 'react'; +import { + GestureResponderHandlers, + ListViewProperties, + StyleProp, + TextInputProperties, + ViewStyle, +} from 'react-native'; + +export interface AutocompleteProps extends TextInputProperties { + /** + * style + * These styles will be applied to the container which surrounds the autocomplete component. + */ + containerStyle?: StyleProp; + + /** + * bool + * Set to true to hide the suggestion list. + */ + hideResults?: boolean; + + /** + * array + * An array with suggestion items to be rendered in renderItem(item). Any array with length > 0 will open the suggestion list and any array with length < 1 will hide the list. + */ + data: T[]; + + /** + * style + * These styles will be applied to the container which surrounds the textInput component. + */ + inputContainerStyle?: StyleProp; + + /** + * style + * These styles will be applied to the container which surrounds the result list. + */ + listContainerStyle?: StyleProp; + + /** + * style + * These style will be applied to the result list. + */ + listStyle?: StyleProp; + + /** + * function + * onShowResult will be called when the autocomplete suggestions appear or disappear. + */ + onShowResult?(showResults: boolean): void; + + /** + * function + * onStartShouldSetResponderCapture will be passed to the result list view container (onStartShouldSetResponderCapture). + */ + onStartShouldSetResponderCapture?: GestureResponderHandlers['onStartShouldSetResponderCapture']; + + /** + * function + * renderItem will be called to render the data objects which will be displayed in the result view below the text input. + */ + renderItem(item: T): ReactNode; + + /** + * function + * renderSeparator will be called to render the list separators which will be displayed between the list elements in the result view below the text input. + */ + renderSeparator?: ListViewProperties['renderSeparator']; + + /** + * function + * render custom TextInput. All props passed to this function. + */ + renderTextInput?(props: TextInputProperties): ReactNode; +} + +export default class Autocomplete extends Component> {} diff --git a/types/react-native-autocomplete-input/react-native-autocomplete-input-tests.tsx b/types/react-native-autocomplete-input/react-native-autocomplete-input-tests.tsx new file mode 100644 index 0000000000..b9ddaa3ae2 --- /dev/null +++ b/types/react-native-autocomplete-input/react-native-autocomplete-input-tests.tsx @@ -0,0 +1,35 @@ +import Autocomplete from 'react-native-autocomplete-input'; +import * as React from 'react'; +import { + StyleSheet, + Text, + TouchableOpacity, + View +} from 'react-native'; + +interface Item { query: string; value: string; } + +class AutocompleteExample extends React.Component<{}, {query: string}> { + state = { + query: '' + }; + + filterData(query: string): Item[] { + return [{query: '', value: 'here i am'}]; + } + + render() { + const { query } = this.state; + const data = this.filterData(query); + return ( this.setState({ query: text })} + renderItem={(item: Item) => ( + this.setState({ query: item.query })}> + {item.value} + + )} + />); + } +} diff --git a/types/react-native-autocomplete-input/tsconfig.json b/types/react-native-autocomplete-input/tsconfig.json new file mode 100644 index 0000000000..a96ec56028 --- /dev/null +++ b/types/react-native-autocomplete-input/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "jsx": "react", + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-autocomplete-input-tests.tsx" + ] +} diff --git a/types/react-native-autocomplete-input/tslint.json b/types/react-native-autocomplete-input/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-autocomplete-input/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-navigation/index.d.ts b/types/react-native-navigation/index.d.ts index 75c0d51be0..86b94bff44 100644 --- a/types/react-native-navigation/index.d.ts +++ b/types/react-native-navigation/index.d.ts @@ -64,6 +64,11 @@ export interface SingleScreenApp { drawer?: Drawer; passProps?: object; animationType?: 'none' | 'slide-down' | 'fade'; + appStyle?: { + orientation?: 'auto' | 'landscape' | 'portrait'; + backButtonImage?: any; + hideBackButtonTitle?: boolean; + }; } export interface Screen { diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index d5f9801b5d..1233ca39e3 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -20,7 +20,7 @@ // TypeScript Version: 2.6 /** - * Reference: https://github.com/react-navigation/react-navigation/tree/a37473c5e4833f48796ee6c7c9cb4a8ac49d9c06 + * Reference: https://github.com/react-navigation/react-navigation/tree/3f3ef6485c8932f49fddc3dd2c508629110bf2b6 * * NOTE: Please update the commit/link above when updating to a new Flow * react-navigation/flow/react-navigation.js reference, so we can conveniently just look at diffs on @@ -313,6 +313,7 @@ export interface NavigationStackRouterConfig { initialRouteParams?: NavigationParams; paths?: NavigationPathsConfig; navigationOptions?: NavigationScreenConfig; + initialRouteKey?: string; } export type NavigationStackAction = diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 6b8b5c99e8..b00b0a27fc 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -50,6 +50,7 @@ const viewStyle: ViewStyle = { }; const ROUTE_NAME_START_SCREEN = "StartScreen"; +const ROUTE_KEY_START_SCREEN = "StartScreen-key"; interface StartScreenNavigationParams { id: number; @@ -131,6 +132,7 @@ export const AppNavigator = StackNavigator( routeConfigMap, { initialRouteName: ROUTE_NAME_START_SCREEN, + initialRouteKey: ROUTE_KEY_START_SCREEN, initialRouteParams, navigationOptions, }, diff --git a/types/react-onsenui/index.d.ts b/types/react-onsenui/index.d.ts index 00437e099b..91055d25b4 100644 --- a/types/react-onsenui/index.d.ts +++ b/types/react-onsenui/index.d.ts @@ -200,11 +200,14 @@ export class Dialog extends Component<{ }, any> {} export class Modal extends Component<{ - animation?: "fade" | "none", - animationOptions?: AnimationOptions - onShow?(): void, - onHide?(): void, - isOpen?: boolean + animation?: "fade" | "lift" | "none", + animationOptions?: AnimationOptions, + onPreShow?(): void, + onPostShow?(): void, + onPreHide?(): void, + onPostHide?(): void, + isOpen?: boolean, + onDeviceBackButton?(): void, }, any> {} export class Popover extends Component<{ diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 23f2f4f78a..32834eed79 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -16,6 +16,7 @@ // Egor Shulga // Youen Toupin // Rahul Raina +// Maksim Sharipov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -58,11 +59,15 @@ export interface RedirectProps { } export class Redirect extends React.Component { } -export interface RouteComponentProps

{ - match: match

; - location: H.Location; +export interface StaticContext { + statusCode?: number; +} + +export interface RouteComponentProps { history: H.History; - staticContext?: any; + location: H.Location; + match: match

; + staticContext: C | undefined; } export interface RouteProps { diff --git a/types/recaptcha2/index.d.ts b/types/recaptcha2/index.d.ts new file mode 100644 index 0000000000..78391ade16 --- /dev/null +++ b/types/recaptcha2/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for recaptcha2 1.3 +// Project: https://github.com/fereidani/recaptcha2#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = Recaptcha2; + +declare class Recaptcha2 { + constructor(options: Recaptcha2.Options); + + getRequestOptions(body: T): Recaptcha2.RequestOptions; + validate(token: string): Promise; + validateRequest(req: object, ip: string): Promise; + translateErrors(errorCodes: string): string; + translateErrors(errorCodes: string[]): string[]; + formElement(htmlClass: string): string; +} + +declare namespace Recaptcha2 { + interface Options { + siteKey: string; + secretKey: string; + ssl?: boolean; + } + + interface RequestOptions { + uri: string; + method: 'POST'; + json: true; + form: T; + } +} diff --git a/types/recaptcha2/recaptcha2-tests.ts b/types/recaptcha2/recaptcha2-tests.ts new file mode 100644 index 0000000000..15ef3537e7 --- /dev/null +++ b/types/recaptcha2/recaptcha2-tests.ts @@ -0,0 +1,19 @@ +import * as reCAPTCHA from 'recaptcha2'; + +const recaptcha = new reCAPTCHA({ + siteKey: 'your-site-key', + secretKey: 'your-secret-key' +}); + +const key = 'invalid'; + +recaptcha.validate(key) + .then(() => { + // validated and secure + }) + .catch((errorCodes) => { + // translate error codes to human readable text + const message = recaptcha.translateErrors(errorCodes); + }); + +const formSnippet = recaptcha.formElement('recaptcha'); diff --git a/types/recaptcha2/tsconfig.json b/types/recaptcha2/tsconfig.json new file mode 100644 index 0000000000..196e86baf0 --- /dev/null +++ b/types/recaptcha2/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", + "recaptcha2-tests.ts" + ] +} diff --git a/types/recaptcha2/tslint.json b/types/recaptcha2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/recaptcha2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/seed-random/index.d.ts b/types/seed-random/index.d.ts new file mode 100644 index 0000000000..a7dfc33e3f --- /dev/null +++ b/types/seed-random/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for seed-random 2.2 +// Project: https://github.com/ForbesLindesay/seed-random +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* + * Usage: + * import * as seed from 'seed-random'; + */ + +export = SeedRandom; + +declare function SeedRandom(seed?: string, options?: SeedRandom.Options): () => number; + +declare namespace SeedRandom { + interface Options { + global?: boolean; + entropy?: boolean; + } + + function resetGlobal(): void; +} diff --git a/types/seed-random/seed-random-tests.ts b/types/seed-random/seed-random-tests.ts new file mode 100644 index 0000000000..9872f63dfa --- /dev/null +++ b/types/seed-random/seed-random-tests.ts @@ -0,0 +1,26 @@ +/// + +import * as assert from 'assert'; +import * as seed from 'seed-random'; + +const trueRandomA = seed(); +const trueRandomB = seed(); +assert(trueRandomA() !== trueRandomB()); + +const fakeRandomA = seed('foo'); +const fakeRandomB = seed('foo'); +assert(fakeRandomA() === fakeRandomB()); + +const fakeRandomC = seed('foo', {entropy: true}); +const fakeRandomD = seed('foo', {entropy: true}); +assert(fakeRandomC() !== fakeRandomD()); + +// override global Math.random +seed('foo', {global: true}); +const numA = Math.random(); +seed('foo', {global: true}); +const numB = Math.random(); +assert(numA === numB); + +// reset to default Math.random +seed.resetGlobal(); diff --git a/types/seed-random/tsconfig.json b/types/seed-random/tsconfig.json new file mode 100644 index 0000000000..2a332b0baf --- /dev/null +++ b/types/seed-random/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", + "seed-random-tests.ts" + ] +} diff --git a/types/seed-random/tslint.json b/types/seed-random/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/seed-random/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/smtp-server/smtp-server-tests.ts b/types/smtp-server/smtp-server-tests.ts index 5be0634ebb..839d4ee3bc 100644 --- a/types/smtp-server/smtp-server-tests.ts +++ b/types/smtp-server/smtp-server-tests.ts @@ -1,3 +1,4 @@ +import { AddressInfo } from 'net'; import { SMTPServer, SMTPServerAddress, SMTPServerAuthentication, SMTPServerAuthenticationResponse, SMTPServerOptions, SMTPServerSession } from 'smtp-server'; import { Readable } from 'stream'; @@ -71,6 +72,6 @@ server.on('close', () => { }); server.listen(port, () => { - const address = server.server.address(); + const address = server.server.address() as AddressInfo; console.log(`Listening on [${address.address}]:${address.port}`); }); diff --git a/types/stompjs/index.d.ts b/types/stompjs/index.d.ts index 91d5277fba..4c591367dc 100644 --- a/types/stompjs/index.d.ts +++ b/types/stompjs/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for stompjs 2.3 // Project: https://github.com/jmesnil/stomp-websocket -// Definitions by: Jimi Charalampidis , Stefan Erichsen +// Definitions by: Jimi Charalampidis +// Stefan Erichsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,7 +10,7 @@ export const VERSIONS: { V1_0: string, V1_1: string, V1_2: string, - supportedVersions: () => Array + supportedVersions: () => string[] }; export class Client { @@ -31,8 +32,8 @@ export class Client { disconnect(disconnectCallback: () => any, headers?: {}): any; send(destination: string, headers?: {}, body?: string): any; - subscribe(destination: string, callback?: (message: Message) => any, headers?: {}): any; - unsubscribe(): any; + subscribe(destination: string, callback?: (message: Message) => any, headers?: {}): Subscription; + unsubscribe(id: string): void; begin(transaction: string): any; commit(transaction: string): any; @@ -42,23 +43,22 @@ export class Client { nack(messageID: string, subscription: string, headers?: {}): any; } -export interface Message { - command: string; - headers: {}; - body: string; +export interface Subscription { + id: string; + unsubscribe(): void; +} +export interface Message extends Frame { ack(headers?: {}): any; nack(headers?: {}): any; } -export class Frame implements Message { +export class Frame { command: string; headers: {}; body: string; constructor(command: string, headers?: {}, body?: string); - ack(headers?: {}): any; - nack(headers?: {}): any; toString(): string; static sizeOfUTF8(s: string): number; static unmarshall(datas: any): any; diff --git a/types/stompjs/stompjs-tests.ts b/types/stompjs/stompjs-tests.ts index fcc0c46ff5..9a3841e41a 100644 --- a/types/stompjs/stompjs-tests.ts +++ b/types/stompjs/stompjs-tests.ts @@ -61,10 +61,11 @@ client.send('destination'); client.send('destination', {}); client.send('destination', {}, 'body'); -client.subscribe('destination', (message) => { }); -client.subscribe('destination', (message) => { }, {}); +let subscription = client.subscribe('destination', (message) => { }); +subscription = client.subscribe('destination', (message) => { }, {}); +subscription.unsubscribe(); -client.unsubscribe(); +client.unsubscribe(subscription.id); client.begin('transaction'); diff --git a/types/swaggerize-express/swaggerize-express-tests.ts b/types/swaggerize-express/swaggerize-express-tests.ts index 9dd0e1e718..46ada50a77 100644 --- a/types/swaggerize-express/swaggerize-express-tests.ts +++ b/types/swaggerize-express/swaggerize-express-tests.ts @@ -1,6 +1,7 @@ import http = require('http'); import express = require('express'); import swaggerize = require('swaggerize-express'); +import { AddressInfo } from 'net'; const api = { swagger: "2.0", @@ -50,5 +51,6 @@ app.use(swaggerize({ })); var server = app.listen(18888, 'localhost', function () { - (app).swagger.api.host = server.address().address + ':' + server.address().port; + const addr = server.address() as AddressInfo; + (app).swagger.api.host = addr.address + ':' + addr.port; }); diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index dd7bd22adf..351084f0d1 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -7029,7 +7029,7 @@ export class DodecahedronGeometry extends Geometry { } export class EdgesGeometry extends BufferGeometry { - constructor(geometry: BufferGeometry, thresholdAngle: number); + constructor(geometry: BufferGeometry | Geometry, thresholdAngle: number); } export class ExtrudeGeometry extends Geometry { diff --git a/types/tokgen/index.d.ts b/types/tokgen/index.d.ts new file mode 100644 index 0000000000..50a1abf7b9 --- /dev/null +++ b/types/tokgen/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for tokgen 1.0 +// Project: https://github.com/maxtruxa/tokgen#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = TokenGenerator; + +declare class TokenGenerator { + constructor(options?: TokenGenerator.Options); + + generate(length?: number): string; + generate(length: number, callback: TokenGenerator.Callback): void; + generate(callback: TokenGenerator.Callback): void; +} + +declare namespace TokenGenerator { + interface OptionsObject { + chars?: string; + length?: number; + } + + type Options = number | string | OptionsObject; + type Callback = (error: any, token: string) => void; +} diff --git a/types/tokgen/tokgen-tests.ts b/types/tokgen/tokgen-tests.ts new file mode 100644 index 0000000000..af3f384fcd --- /dev/null +++ b/types/tokgen/tokgen-tests.ts @@ -0,0 +1,20 @@ +import * as TokenGenerator from 'tokgen'; + +const generator1 = new TokenGenerator(); +const generator2 = new TokenGenerator('0-9a-f'); +const generator3 = new TokenGenerator({chars: '0-9a-f'}); +const generator4 = new TokenGenerator(8); +const generator5 = new TokenGenerator({length: 8}); +const generator6 = new TokenGenerator({chars: '0-9a-f', length: 8}); + +const token1 = generator1.generate(); + +const token2 = generator1.generate(10); + +generator1.generate((error, token) => { + // nothing to do in this test +}); + +generator1.generate(8, (error, token) => { + // nothing to do in this test +}); diff --git a/types/tokgen/tsconfig.json b/types/tokgen/tsconfig.json new file mode 100644 index 0000000000..5a6995c482 --- /dev/null +++ b/types/tokgen/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", + "tokgen-tests.ts" + ] +} diff --git a/types/tokgen/tslint.json b/types/tokgen/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tokgen/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tough-cookie/index.d.ts b/types/tough-cookie/index.d.ts index ee431874dc..d4e9a58548 100644 --- a/types/tough-cookie/index.d.ts +++ b/types/tough-cookie/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/salesforce/tough-cookie // Definitions by: Leonard Thieu // LiJinyao +// Michael Wei // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -151,7 +152,7 @@ export class CookieJar { static deserialize(serialized: CookieJar.Serialized | string, store: Store, cb: (err: Error | null, object: CookieJar) => void): void; static deserialize(serialized: CookieJar.Serialized | string, cb: (err: Error | null, object: CookieJar) => void): void; - static deserializeSync(serialized: CookieJar.Serialized | string): CookieJar; + static deserializeSync(serialized: CookieJar.Serialized | string, store?: Store): CookieJar; static fromJSON(string: string): CookieJar; diff --git a/types/tough-cookie/tough-cookie-tests.ts b/types/tough-cookie/tough-cookie-tests.ts index 8798e0d840..0ce120a144 100644 --- a/types/tough-cookie/tough-cookie-tests.ts +++ b/types/tough-cookie/tough-cookie-tests.ts @@ -1,4 +1,4 @@ -import { Cookie, CookieJar } from 'tough-cookie'; +import { Cookie, CookieJar, MemoryCookieStore } from 'tough-cookie'; let header = ''; const cb = () => { }; @@ -13,3 +13,6 @@ cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); cookiejar.getCookies('http://example.com/otherpath', (err, cookies) => { // res.headers['cookie'] = cookies.join('; '); }); + +CookieJar.deserializeSync("test cookie with store", new MemoryCookieStore()); +CookieJar.deserializeSync("test cookie"); diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index e422c58b32..05113ea6d4 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -205,9 +205,9 @@ declare namespace webpack { interface Module { /** A array of applied pre loaders. */ - preLoaders?: Rule[]; + preLoaders?: RuleSetRule[]; /** A array of applied post loaders. */ - postLoaders?: Rule[]; + postLoaders?: RuleSetRule[]; /** A RegExp or an array of RegExps. Don’t parse files matching. */ noParse?: RegExp | RegExp[] | ((content: string) => boolean); unknownContextRequest?: string; @@ -223,7 +223,7 @@ declare namespace webpack { wrappedContextCritical?: boolean; strictExportPresence?: boolean; /** An array of rules applied for modules. */ - rules: Rule[]; + rules: RuleSetRule[]; } interface Resolve { @@ -357,143 +357,187 @@ declare namespace webpack { __dirname?: boolean | string; [nodeBuiltin: string]: boolean | string | undefined; } - - interface BaseConditionSpec { - /** The Condition must match. The convention is the provide a string or array of strings here, but it's not enforced. */ - include?: Condition; - /** The Condition must NOT match. The convention is the provide a string or array of strings here, but it's not enforced. */ - exclude?: Condition; - } - interface TestConditionSpec extends BaseConditionSpec { - /** The Condition must match. The convention is the provide a RegExp or array of RegExps here, but it's not enforced. */ - test: Condition; - } - interface AndConditionSpec extends BaseConditionSpec { - /** All Conditions must match. */ - and: Condition[]; - } - interface OrConditionSpec extends BaseConditionSpec { - /** Any Condition must match. */ - or: Condition[]; - } - interface NotConditionSpec extends BaseConditionSpec { - /** The Condition must NOT match. */ - not: Condition; - } - type ConditionSpec = TestConditionSpec | OrConditionSpec | AndConditionSpec | NotConditionSpec; - - // tslint:disable-next-line:no-empty-interface - interface ConditionArray extends Array { } - type Condition = string | RegExp | ((absPath: string) => boolean) | ConditionSpec | ConditionArray; - - interface OldLoader { - loader: string; - query?: { [name: string]: any }; - } interface NewLoader { loader: string; options?: { [name: string]: any }; } - type Loader = string | OldLoader | NewLoader; + type Loader = string | NewLoader; + interface ParserOptions { [optName: string]: any; system?: boolean; } - /** - * There are direct and delegate rules. Direct Rules need a test, Delegate rules delegate to subrules bringing their own. - * Direct rules can optionally contain delegate keys (oneOf, rules). - * - * These types exist to enforce that a rule has the keys `((loader XOR loaders) AND test) OR oneOf OR rules` - */ - interface BaseRule { - /** - * Specifies the category of the loader. No value means normal loader. - * - * There is also an additional category "inlined loader" which are loaders applied inline of the import/require. - * - * All loaders are sorted in the order post, inline, normal, pre and used in this order. - * - * All normal loaders can be omitted (overridden) by prefixing ! in the request. - * - * All normal and pre loaders can be omitted (overridden) by prefixing -! in the request. - * - * All normal, post and pre loaders can be omitted (overridden) by prefixing !! in the request. - * - * Inline loaders and ! prefixes should not be used as they are non-standard. They may be use by loader generated code. - */ - enforce?: 'pre' | 'post'; - /** A condition that must be met */ - test?: Condition | Condition[]; - /** A condition that must not be met */ - exclude?: Condition | Condition[]; - /** A condition that must be met */ - include?: Condition | Condition[]; - /** A Condition matched with the resource. */ - resource?: Condition | Condition[]; - /** A Condition matched with the resource query. */ - resourceQuery?: Condition | Condition[]; - /** A condition matched with the issuer */ - issuer?: Condition | Condition[]; - /** - * An object with parser options. All applied parser options are merged. - * - * For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options. - * Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true. - */ - parser?: ParserOptions; - /** An array of Rules that is also used when the Rule matches. */ - rules?: Rule[]; - /** An array of Rules from which only the first matching Rule is used when the Rule matches. */ - oneOf?: Rule[]; - /** Configures module resolving. */ - resolve?: Resolve; - /** Configures the module type. */ - type?: "javascript/auto" | "javascript/esm" | "javascript/dynamic" | "json" | "webassembly/experimental"; - /** Flags a module as with or without side effects */ - sideEffects?: boolean; - } - interface BaseDirectRule extends BaseRule { - /** A condition that must be met */ - test: Condition | Condition[]; - } - // Direct Rules - interface BaseSingleLoaderRule extends BaseDirectRule { - /** Loader name or an object with name and options */ - loader: Loader; - } - interface OldLoaderRule extends BaseSingleLoaderRule { - /** - * Loader options - * @deprecated: - */ - query?: { [name: string]: any }; - } - interface NewLoaderRule extends BaseSingleLoaderRule { - options?: { [name: string]: any }; - } - type LoaderRule = OldLoaderRule | NewLoaderRule; - interface OldUseRule extends BaseDirectRule { - /** - * A array of loaders. - * @deprecated use `use` instead - */ - loaders: string[]; - } - interface NewUseRule extends BaseDirectRule { - /** A loader or array of loaders */ - use: Loader | Loader[]; - } - type UseRule = OldUseRule | NewUseRule; - // Delegate Rules - interface RulesRule extends BaseRule { - /** An array of Rules that is also used when the Rule matches. */ - rules: Rule[]; + type RuleSetCondition = string + | { + [k: string]: any; + } + | { + /** + * Logical AND + */ + and?: RuleSetConditions; + /** + * Exclude all modules matching any of these conditions + */ + exclude?: RuleSetCondition; + /** + * Exclude all modules matching not any of these conditions + */ + include?: RuleSetCondition; + /** + * Logical NOT + */ + not?: RuleSetConditions; + /** + * Logical OR + */ + or?: RuleSetConditions; + /** + * Exclude all modules matching any of these conditions + */ + test?: RuleSetCondition; + }; + type RuleSetConditions = RuleSetCondition[]; + + interface RuleSetRule { + /** + * Enforce this rule as pre or post step + */ + enforce?: "pre" | "post"; + /** + * Shortcut for resource.exclude + */ + exclude?: RuleSetCondition & { + [k: string]: any; + }; + /** + * Shortcut for resource.include + */ + include?: RuleSetCondition & { + [k: string]: any; + }; + /** + * Match the issuer of the module (The module pointing to this module) + */ + issuer?: RuleSetCondition & { + [k: string]: any; + }; + /** + * Shortcut for use.loader + */ + loader?: RuleSetLoader | RuleSetUse; + /** + * Shortcut for use.loader + */ + loaders?: RuleSetUse; + /** + * Only execute the first matching rule in this array + */ + oneOf?: RuleSetRules; + /** + * Shortcut for use.options + */ + options?: RuleSetQuery; + /** + * Options for parsing + */ + parser?: { + [k: string]: any; + }; + /** + * Options for the resolver + */ + resolve?: Resolve; + /** + * Flags a module as with or without side effects + */ + sideEffects?: boolean; + /** + * Shortcut for use.query + */ + query?: RuleSetQuery; + /** + * Module type to use for the module + */ + type?: "javascript/auto" | "javascript/dynamic" | "javascript/esm" | "json" | "webassembly/experimental"; + /** + * Match the resource path of the module + */ + resource?: RuleSetCondition & { + [k: string]: any; + }; + /** + * Match the resource query of the module + */ + resourceQuery?: RuleSetCondition; + /** + * Match the child compiler name + */ + compiler?: RuleSetCondition; + /** + * Match and execute these rules when this rule is matched + */ + rules?: RuleSetRules; + /** + * Shortcut for resource.test + */ + test?: RuleSetCondition & { + [k: string]: any; + }; + /** + * Modifiers applied to the module when rule is matched + */ + use?: RuleSetUse; } - interface OneOfRule extends BaseRule { - oneOf: Rule[]; - } - type Rule = LoaderRule | UseRule | RulesRule | OneOfRule; + type RuleSetLoader = string; + type RuleSetUse = + | RuleSetUseItem + | { + [k: string]: any; + } + | RuleSetUseItem[]; + type RuleSetUseItem = + | RuleSetLoader + | { + [k: string]: any; + } + | { + /** + * Loader name + */ + loader?: RuleSetLoader; + /** + * Loader options + */ + options?: RuleSetQuery; + /** + * Unique loader identifier + */ + ident?: string; + /** + * Loader query + */ + query?: RuleSetQuery; + }; + type RuleSetQuery = + | { + [k: string]: any; + } + | string; + type CommonArrayOfStringOrStringArrayValues = Array<(string | string[])>; + type CommonArrayOfStringValues = string[]; + type RuleSetRules = RuleSetRule[]; + + /** + * @deprecated Use RuleSetCondition instead + */ + type Condition = RuleSetCondition; + + /** + * @deprecated Use RuleSetRule instead + */ + type Rule = RuleSetRule; namespace Options { // tslint:disable-next-line:max-line-length diff --git a/types/webpack/webpack-tests.ts b/types/webpack/webpack-tests.ts index 4ce24fb25d..803e227c4a 100644 --- a/types/webpack/webpack-tests.ts +++ b/types/webpack/webpack-tests.ts @@ -684,3 +684,17 @@ class BannerPlugin extends webpack.Plugin { }); } } + +configuration = { + module: { + rules: [ + { + test: /\.css$/, + oneOf: [ + { resourceQuery: /global/, use: ["style-loader", "css-loader"] }, + { use: ["to-string-loader", "css-loader"] } + ] + } + ] + } +}; diff --git a/types/ws/index.d.ts b/types/ws/index.d.ts index f9bda66eba..9bdf092f38 100644 --- a/types/ws/index.d.ts +++ b/types/ws/index.d.ts @@ -176,7 +176,7 @@ declare namespace WebSocket { constructor(options?: ServerOptions, callback?: () => void); - address(): { port: number; family: string; address: string; }; + address(): net.AddressInfo | string; close(cb?: (err?: Error) => void): void; handleUpgrade(request: http.IncomingMessage, socket: net.Socket, upgradeHead: Buffer, callback: (client: WebSocket) => void): void; diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 93a60450e7..699d1893bf 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for yup 0.24 // Project: https://github.com/jquense/yup -// Definitions by: Dominik Hardtke , Vladyslav Tserman , Moreton Bay Regional Council +// Definitions by: Dominik Hardtke , +// Vladyslav Tserman , +// Moreton Bay Regional Council , +// Sindre Seppola // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -34,8 +37,8 @@ export interface Schema { meta(): any; describe(): SchemaDescription; concat(schema: this): this; - validate(value: T, options?: ValidateOptions): Promise; - validateSync(value: T, options?: ValidateOptions): ValidationError|T; + validate(value: T, options?: ValidateOptions): Promise; + validateSync(value: T, options?: ValidateOptions): ValidationError | T; isValid(value: T, options?: any): Promise; isValidSync(value: T, options?: any): boolean; cast(value: any, options?: any): T; @@ -57,8 +60,8 @@ export interface Schema { } export interface MixedSchemaConstructor { - (): MixedSchema; - new(options?: { type?: string, [key: string]: any }): MixedSchema; + (): MixedSchema; + new(options?: { type?: string, [key: string]: any }): MixedSchema; } // tslint:disable-next-line:no-empty-interface @@ -73,7 +76,7 @@ export interface StringSchemaConstructor { export interface StringSchema extends Schema { min(limit: number | Ref, message?: string): StringSchema; max(limit: number | Ref, message?: string): StringSchema; - matches(regex: RegExp, message?: string): StringSchema; + matches(regex: RegExp, messageOrOptions?: string | { message?: string; excludeEmptyString?: boolean }): StringSchema; email(message?: string): StringSchema; url(message?: string): StringSchema; ensure(): StringSchema; @@ -133,7 +136,7 @@ export interface ArraySchema extends Schema { export interface ObjectSchemaConstructor { (fields?: { [field in keyof T]: Schema }): ObjectSchema; - new (): ObjectSchema<{}>; + new(): ObjectSchema<{}>; } export interface ObjectSchema extends Schema { @@ -155,8 +158,8 @@ export interface WhenOptionsBuilder { } export type WhenOptions = WhenOptionsBuilder -| { is: boolean | ((value: any) => boolean), then: any, otherwise: any } -| object; + | { is: boolean | ((value: any) => boolean), then: any, otherwise: any } + | object; export interface ValidateOptions { /** @@ -245,12 +248,12 @@ export interface Lazy extends Schema { } export interface LocaleObject { - mixed?: { [key in keyof MixedSchema]?: string }; - string?: { [key in keyof StringSchema]?: string }; - number?: { [key in keyof NumberSchema]?: string }; - boolean?: { [key in keyof BooleanSchema]?: string }; - bool?: { [key in keyof BooleanSchema]?: string }; - date?: { [key in keyof DateSchema]?: string }; - array?: { [key in keyof ArraySchema]?: string }; - object?: { [key in keyof ObjectSchema]?: string }; + mixed?: { [key in keyof MixedSchema]?: string }; + string?: { [key in keyof StringSchema]?: string }; + number?: { [key in keyof NumberSchema]?: string }; + boolean?: { [key in keyof BooleanSchema]?: string }; + bool?: { [key in keyof BooleanSchema]?: string }; + date?: { [key in keyof DateSchema]?: string }; + array?: { [key in keyof ArraySchema]?: string }; + object?: { [key in keyof ObjectSchema]?: string }; }