diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index b405de0273..075d063e5f 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,345 +1,476 @@ -// Type definitions for AFRAME 0.7 +// Type definitions for AFRAME 0.8 // Project: https://aframe.io/ // Definitions by: Paul Shannon // Roberto Ritger // Trygve Wastvedt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /** - * Extended tests available at https://github.com/devpaul/aframe-typings.git + * Extended tests and examples available at https://github.com/devpaul/aframe-experiments.git */ -/// /// -// Globals -declare var AFRAME: AFrame.AFrameGlobal; -declare var hasNativeWebVRImplementation: boolean; +import * as three from 'three'; +import * as tween from '@tweenjs/tween.js'; -interface Document { - createElement(tagName: string): AFrame.Entity; - querySelector(selectors: 'a-scene'): AFrame.Scene; - querySelector(selectors: string): AFrame.Entity; - querySelectorAll(selectors: string): NodeListOf | Element>; +export type ThreeLib = typeof three; +export type TweenLib = typeof tween; + +export interface ObjectMap { + [key: string]: T; } -// Interfaces -declare namespace AFrame { - interface ObjectMap { - [ key: string ]: T; - } +export interface Animation { + attribute: string; + begin: string | number; + delay: number; + direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse'; + dur: number; + easing(): void; + end: string; + fill: 'backwards' | 'both' | 'forwards' | 'none'; + from: any; // TODO type + repeat: number | 'indefinite'; + to: number; +} - interface AFrameGlobal { - AEntity: Entity; - ANode: ANode; - AScene: Scene; - components: { [ key: string ]: ComponentDescriptor }; - geometries: { [ key: string ]: GeometryDescriptor }; - primitives: { [ key: string ]: Entity }; - registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; - registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometry: GeometryDefinition): GeometryConstructor; - registerPrimitive(name: string, primitive: PrimitiveDefinition): void; - registerShader(name: string, shader: T): ShaderConstructor; - registerSystem(name: string, definition: SystemDefinition): SystemConstructor; - schema: SchemaUtils; - shaders: { [ key: string ]: ShaderDescriptor }; - systems: { [key: string]: SystemConstructor }; - THREE: typeof THREE; - TWEEN: typeof TWEEN; - utils: Utils; - version: string; - } +export interface ANode extends HTMLElement { + // Only public APIs added. Many methods intentionally left out. + // createdCallback + // attachedCallback + // attributeChangedCallback + closestScene(): Scene; + closest(selector: string): ANode; + // detachedCallback + hasLoaded: boolean; + load(cb?: () => void, childFilter?: (el: Element) => boolean): void; + // updateMixins + registerMixin(id: string): void; + setAttribute(type: string, newValue: any): void; + unregisterMixin(id: string): void; + removeMixinListener(id: string): void; + attachMixinListener(mixin: HTMLElement): void; + emit(name: string, detail?: any, bubbles?: boolean): void; + emitter(name: string, detail?: any, bubbles?: boolean): () => void; +} - interface Animation { - attribute: string; - begin: string | number; - delay: number; - direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse'; - dur: number; - easing(): void; - end: string; - fill: 'backwards' | 'both' | 'forwards' | 'none'; - from: any; // TODO type - repeat: number | 'indefinite'; - to: number; - } +export interface Behavior { + tick(): void; +} - interface ANode extends HTMLElement { - // Only public APIs added. Many methods intentionally left out. - // createdCallback - // attachedCallback - // attributeChangedCallback - closestScene(): Scene; - closest(selector: string): ANode; - // detachedCallback - hasLoaded: boolean; - load(cb?: () => void, childFilter?: (el: Element) => boolean): void; - // updateMixins - registerMixin(id: string): void; - setAttribute(type: string, newValue: any): void; - unregisterMixin(id: string): void; - removeMixinListener(id: string): void; - attachMixinListener(mixin: HTMLElement): void; - emit(name: string, detail?: any, bubbles?: boolean): void; - emitter(name: string, detail?: any, bubbles?: boolean): () => void; - } +export interface Component { + attrName?: string; + data: T; + dependencies?: string[]; + el: Entity; + id: string; + multiple?: boolean; + name: string; + schema: Schema; + system: S | undefined; - interface Behavior { - tick(): void; - } + init(data?: T): void; + pause(): void; + play(): void; + remove(): void; + tick?(time: number, timeDelta: number): void; + update(oldData: T): void; + updateSchema?(): void; - interface Component { - attrName?: string; - data: T; - dependencies?: string[]; - el: Entity; - id: string; - multiple?: boolean; + extendSchema(update: Schema): void; + flushToDOM(): void; +} + +export interface ComponentConstructor { + new (el: Entity, attrValue: string, id: string): T & Component; + prototype: T & { name: string; - schema: Schema; - system: S | undefined; - - 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(this: this, update: Schema): void; - flushToDOM(this: this): void; - } - - interface ComponentConstructor { - new (el: Entity, attrValue: string, id: string): T; - } - - type ComponentDefinition = Partial; - - interface ComponentDescriptor { - Component: ComponentConstructor; - dependencies: string[] | undefined; - multiple: boolean | undefined; - - // internal APIs2 - // parse - // parseAttrValueForCache - // schema - // stringify - // type - } - - interface Coordinate { - x: number; - y: number; - z: number; - } - - interface DefaultComponents { - position: Component; - rotation: Component; - scale: Component; - } - - interface Entity> extends ANode { - components: C & DefaultComponents; - isPlaying: boolean; - object3D: THREE.Object3D; - object3DMap: ObjectMap; - sceneEl?: Scene; - - addState(name: string): void; - flushToDOM(recursive?: boolean): void; - /** - * @deprecated since 0.4.0 - */ - getComputedAttribute(attr: string): Component; - getDOMAttribute(attr: string): any; - getObject3D(type: string): THREE.Object3D; - getOrCreateObject3D(type: string, construct: any): THREE.Object3D; - is(stateName: string): boolean; - pause(): void; + system: System; play(): void; - setObject3D(type: string, obj: THREE.Object3D): void; - removeAttribute(attr: string, property?: string): void; - removeObject3D(type: string): void; - removeState(stateName: string): void; - - // getAttribute specific usages - getAttribute(type: string): any; - getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; - - // setAttribute specific usages - setAttribute(attr: string, value: any): void; - setAttribute(attr: string, property: string, componentAttrValue?: any): void; - setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void; - - // addEventListener specific usages - addEventListener(type: K, listener: (event: Event & EntityEventMap[K]) => void, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - } - - type DetailEvent = Event & { - detail: D; - target: EventTarget & Entity; + pause(): void; }; +} - interface EntityEventMap { - 'child-attached': DetailEvent<{ el: Element | Entity }>; - 'child-detached': DetailEvent<{ el: Element | Entity }>; - 'componentchanged': DetailEvent<{ - name: string, - id: string - }>; - 'componentremoved': DetailEvent<{ - name: string, - id: string, - newData: any, - oldData: any - }>; - 'loaded': EventListener; - 'pause': EventListener; - 'play': EventListener; - 'stateadded': DetailEvent<{ state: string }>; - 'stateremoved': DetailEvent<{ state: string }>; - 'schemachanged': DetailEvent<{ componentName: string }>; - } +export interface ComponentDescriptor { + Component: ComponentConstructor; + dependencies: string[] | undefined; + multiple: boolean | undefined; - interface Geometry { + // internal APIs2 + // parse + // parseAttrValueForCache + // schema + // stringify + // type +} + +export interface Coordinate { + x: number; + y: number; + z: number; +} + +export interface DefaultComponents { + position: Component; + rotation: Component; + scale: Component; +} + +export interface Entity> extends ANode { + components: C & DefaultComponents; + isPlaying: boolean; + object3D: THREE.Object3D; + object3DMap: ObjectMap; + sceneEl?: Scene; + + addState(name: string): void; + flushToDOM(recursive?: boolean): void; + /** + * @deprecated since 0.4.0 + */ + getComputedAttribute(attr: string): Component; + getDOMAttribute(attr: string): any; + getObject3D(type: string): THREE.Object3D; + getOrCreateObject3D(type: string, construct: any): THREE.Object3D; + is(stateName: string): boolean; + pause(): void; + play(): void; + setObject3D(type: string, obj: THREE.Object3D): void; + removeAttribute(attr: string, property?: string): void; + removeObject3D(type: string): void; + removeState(stateName: string): void; + + // getAttribute specific usages + getAttribute(type: string): any; + getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; + + // setAttribute specific usages + setAttribute(attr: string, value: any): void; + setAttribute(attr: string, property: string, componentAttrValue?: any): void; + setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void; + + // addEventListener specific usages + addEventListener( + type: K, + listener: (event: Event & EntityEventMap[K]) => void, + useCapture?: boolean + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + useCapture?: boolean + ): void; +} + +export type DetailEvent = Event & { + detail: D; + target: EventTarget & Entity; +}; + +export interface EntityEventMap { + 'child-attached': DetailEvent<{ el: Element | Entity }>; + 'child-detached': DetailEvent<{ el: Element | Entity }>; + componentchanged: DetailEvent<{ name: string; - geometry: THREE.Geometry; - schema: Schema; + id: string; + }>; + componentremoved: DetailEvent<{ + name: string; + id: string; + newData: any; + oldData: any; + }>; + loaded: EventListener; + pause: EventListener; + play: EventListener; + stateadded: DetailEvent<{ state: string }>; + stateremoved: DetailEvent<{ state: string }>; + schemachanged: DetailEvent<{ componentName: string }>; +} - 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. - } +export interface Geometry { + data: T; + name: string; + geometry: THREE.Geometry; + schema: Schema; - interface GeometryConstructor { - new (): T; - } + init(data: any): void; +} - type GeometryDefinition = Partial; +export interface GeometryConstructor { + new (): T & Geometry; +} - interface GeometryDescriptor { - Geometry: GeometryConstructor; - schema: Schema; - } +export interface GeometryDescriptor { + Geometry: GeometryConstructor; + schema: Schema; +} - type MultiPropertySchema = { - [P in keyof T]: SinglePropertySchema | T[P]; +export type MultiPropertySchema = { + [P in keyof T]: SinglePropertySchema | T[P] +}; + +export type PropertyTypes = + | 'array' + | 'asset' + | 'audio' + | 'boolean' + | 'color' + | 'int' + | 'map' + | 'model' + | 'number' + | 'selector' + | 'selectorAll' + | 'string' + | 'vec2' + | 'vec3' + | 'vec4'; + +export type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; + +export interface Scene extends Entity { + behaviors: Behavior[]; + camera: THREE.Camera; + canvas: HTMLCanvasElement; + effect: THREE.VREffect; + isMobile: boolean; + object3D: THREE.Scene; + renderer: THREE.WebGLRenderer; + renderStarted: boolean; + systems: ObjectMap; + time: number; + + enterVR(): Promise | void; + exitVR(): Promise | void; + reload(): void; + + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + useCapture?: boolean + ): void; + addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; +} + +export type Schema = SinglePropertySchema | MultiPropertySchema; + +export interface SchemaUtils { + isSingleProperty(schema: Schema): boolean; + process(schema: Schema): boolean; +} + +export interface Shader { + name: string; + data: object; + schema: Schema; + material: THREE.Material; + vertexShader: string; + fragmentShader: string; + + init(data?: this['data']): void; + tick?(time: number, timeDelta: number): void; + update(oldData: this['data']): void; +} + +export interface ShaderConstructor { + new (): T; +} + +export interface ShaderDescriptor { + Shader: ShaderConstructor; + schema: Schema; +} + +export interface SinglePropertySchema { + type?: PropertyTypes; + default?: T; + parse?(value: string): T; + stringify?(value: T): string; +} + +export interface System { + data: T; + schema: Schema; + init(): void; + pause(): void; + play(): void; + tick?(t: number, dt: number): void; +} + +export interface SystemConstructor { + new (scene: Scene): T & System; +} + +export interface Utils { + coordinates: { + isCoordinate(value: string): boolean; + parse(value: string): Coordinate; + stringify(coord: Coordinate): string; }; + entity: { + getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any; + setComponentProperty( + entity: Entity, + componentName: string, + value: any, + delimiter?: string + ): void; + }; + styleParser: { + parse(value: string): object; + stringify(data: object): string; + }; + deepEqual(a: any, b: any): boolean; + diff(a: object, b: object): object; + extend(target: object, ...source: object[]): object; + extendDeep(target: object, ...source: object[]): object; - interface PrimitiveDefinition { - defaultComponents?: any; // TODO cleanup type - deprecated?: boolean; - mappings?: any; // TODO cleanup type - transforms?: any; // TODO cleanup type - } + 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; +} - type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' | - 'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' | - 'string' | 'vec2' | 'vec3' | 'vec4'; +// Definitions +// used as mixins to register functions to create classes (newable functions) in A-Frame +export type ComponentDefinition = T & Partial; +export type GeometryDefinition = T & Partial>; +export type NodeDefinition = T & Partial; +export interface PrimitiveDefinition { + defaultComponents?: any; // TODO cleanup type + deprecated?: boolean; + mappings?: any; // TODO cleanup type + transforms?: any; // TODO cleanup type +} +export interface MinimalShaderDefinition { + schema: Shader['schema']; +} +export type ShaderDefinition = T & + Partial; +export type SystemDefinition = T & Partial; - type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; +// root export +export interface AFrame { + AComponent: Component; + AEntity: Entity; + ANode: ANode; + AScene: Scene; - interface Scene extends Entity { - behaviors: Behavior[]; - camera: THREE.Camera; - canvas: HTMLCanvasElement; - effect: THREE.VREffect; - isMobile: boolean; - object3D: THREE.Scene; - renderer: THREE.WebGLRenderer; - renderStarted: boolean; - systems: ObjectMap; - time: number; - - enterVR(): Promise | void; - exitVR(): Promise | void; - reload(): void; - - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; - } - - type Schema = SinglePropertySchema | MultiPropertySchema; - - interface SchemaUtils { - isSingleProperty(schema: Schema): boolean; - process(schema: Schema): boolean; - } - - interface Shader { - name: string; - 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 ShaderConstructor { - new (): T; - } - - type ShaderDefinition = Partial; - - interface ShaderDescriptor { - Shader: ShaderConstructor; - schema: Schema; - } - - interface SinglePropertySchema { - type?: PropertyTypes; - 'default'?: T; - parse?(value: string): T; - stringify?(value: T): string; - } - - interface System { - 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 SystemConstructor { - new (scene: Scene): T; - } - - type SystemDefinition = Partial; - - interface Utils { - coordinates: { - isCoordinate(value: string): boolean; - parse(value: string): Coordinate; - stringify(coord: Coordinate): string; + components: ObjectMap; + geometries: ObjectMap; + primitives: { + getMeshMixin(): { + defaultComponents: { material: object }; + mappings: { [key: string]: any }; // TODO improve any type }; - entity: { - getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any; - setComponentProperty(entity: Entity, componentName: string, value: any, delimiter?: string): void; - }; - styleParser: { - parse(value: string): object; - stringify(data: object): string; - }; - deepEqual(a: any, b: any): boolean; - diff(a: object, b: object): object; - extend(target: object, ... source: object[]): object; - extendDeep(target: object, ... source: object[]): object; + primitives: ObjectMap; + }; + scenes: Scene[]; + schema: SchemaUtils; + shaders: ObjectMap; + systems: ObjectMap; + THREE: ThreeLib; + TWEEN: TweenLib; + utils: Utils; + version: string; - 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; + registerComponent( + name: string, + component: ComponentDefinition + ): ComponentConstructor; + registerElement(name: string, element: object): void; + registerGeometry( + name: string, + geometry: GeometryDefinition + ): GeometryConstructor; + registerPrimitive(name: string, primitive: PrimitiveDefinition): void; + registerShader( + name: string, + shader: ShaderDefinition + ): ShaderConstructor; + registerSystem( + name: string, + definition: SystemDefinition + ): SystemConstructor; +} + +// module.exports +export const AComponent: AFrame['AComponent']; +export const AEntity: AFrame['AEntity']; +export const ANode: AFrame['ANode']; +export const AScene: AFrame['AScene']; +export const components: AFrame['components']; +export const geometries: AFrame['geometries']; +export const primitives: AFrame['primitives']; +export const scenes: AFrame['scenes']; +export const schema: AFrame['schema']; +export const shaders: AFrame['shaders']; +export const systems: AFrame['systems']; +export const THREE: AFrame['THREE']; +export const TWEEN: AFrame['TWEEN']; +export const utils: AFrame['utils']; +export const version: AFrame['version']; +export const registerComponent: AFrame['registerComponent']; +export const registerElement: AFrame['registerElement']; +export const registerGeometry: AFrame['registerGeometry']; +export const registerPrimitive: AFrame['registerPrimitive']; +export const registerShader: AFrame['registerShader']; +export const registerSystem: AFrame['registerSystem']; + +// global exports +declare global { + var hasNativeWebVRImplementation: boolean; + + namespace AFRAME { + const AComponent: AFrame['AComponent']; + const AEntity: AFrame['AEntity']; + const ANode: AFrame['ANode']; + const AScene: AFrame['AScene']; + const components: AFrame['components']; + const geometries: AFrame['geometries']; + const primitives: AFrame['primitives']; + const scenes: AFrame['scenes']; + const schema: AFrame['schema']; + const shaders: AFrame['shaders']; + const systems: AFrame['systems']; + const THREE: AFrame['THREE']; + const TWEEN: AFrame['TWEEN']; + const utils: AFrame['utils']; + const version: string; + + const registerComponent: AFrame['registerComponent']; + const registerElement: AFrame['registerElement']; + const registerGeometry: AFrame['registerGeometry']; + const registerPrimitive: AFrame['registerPrimitive']; + const registerShader: AFrame['registerShader']; + const registerSystem: AFrame['registerSystem']; + } + + /** + * Custom elements augment document methods to return custom HTML + */ + interface Document { + createElement(tagName: string): Entity; + querySelector(selectors: 'a-scene'): Scene; + querySelector(selectors: string): Entity; + querySelectorAll(selectors: string): NodeListOf | Element>; + } + + interface HTMLCollection extends HTMLCollectionBase { + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element | Entity | null; + item(index: number): Element | Entity; + [index: number]: Element | Entity; } } diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts new file mode 100644 index 0000000000..77fe716390 --- /dev/null +++ b/types/aframe/test/aframe-io-tests.ts @@ -0,0 +1,1044 @@ +import { Component, Coordinate, Entity, Scene, THREE, ANode } from 'aframe'; + +/** + * These tests are examples from https://aframe.io pulled directly from the sample gallery. + * Types and some formatting have been added, but for the most part they remain unchanged. + */ + +// disable checks for things done in the original, JS examples +/* tslint:disable:object-literal-shorthand */ +/* tslint:disable:no-var-keyword */ +/* tslint:disable:prefer-const */ +/* tslint:disable:only-arrow-functions */ +/* tslint:disable:one-variable-per-declaration */ + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// 360 picture gallery +// Taken from https://glitch.com/edit/#!/aframe-gallery + +/** + * Component that listens to an event, fades out an entity, swaps the texture, and fades it + * back in. + */ +AFRAME.registerComponent('set-image', { + schema: { + on: { type: 'string' }, + target: { type: 'selector' }, + src: { type: 'string' }, + dur: { type: 'number', default: 300 } + }, + + init: function() { + var data = this.data; + var el = this.el!; + + this.setupFadeAnimation(); + + el.addEventListener(data.on, function() { + // Fade out image. + data.target.emit('set-image-fade'); + // Wait for fade to complete. + setTimeout(function() { + // Set image. + data.target.setAttribute('material', 'src', data.src); + }, data.dur); + }); + }, + + /** + * Setup fade-in + fade-out. + */ + setupFadeAnimation: function() { + var data = this.data; + var targetEl = this.data.target; + + // Only set up once. + if (targetEl.dataset.setImageFadeSetup) { + return; + } + targetEl.dataset.setImageFadeSetup = true; + + // Create animation. + targetEl.setAttribute('animation__fade', { + property: 'material.color', + startEvents: 'set-image-fade', + dir: 'alternate', + dur: data.dur, + from: '#FFF', + to: '#000' + }); + } +}); + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// 360 video example +// Taken from https://glitch.com/edit/#!/aframe-360-video-example + +AFRAME.registerComponent('arrow-key-rotation', { + directionX: 0, + directionY: 0, + + schema: { + enabled: { default: true }, + dx: { default: 2.0 }, + dy: { default: 2.0 } + }, + init: function() { + this.onKeyDown = this.onKeyDown.bind(this); + this.onKeyUp = this.onKeyUp.bind(this); + this.directionX = 0; + this.directionY = 0; + }, + play: function() { + window.addEventListener('keydown', this.onKeyDown); + window.addEventListener('keyup', this.onKeyUp); + }, + pause: function() { + window.removeEventListener('keydown', this.onKeyDown); + window.removeEventListener('keyup', this.onKeyUp); + }, + onKeyDown: function(evt: KeyboardEvent) { + switch (evt.keyCode) { + case 37: + this.directionX = 1; + break; + case 38: + this.directionY = 1; + break; + case 39: + this.directionX = -1; + break; + case 40: + this.directionY = -1; + break; + } + }, + onKeyUp: function(evt: KeyboardEvent) { + switch (evt.keyCode) { + case 37: + this.directionX = 0; + break; + case 38: + this.directionY = 0; + break; + case 39: + this.directionX = 0; + break; + case 40: + this.directionY = 0; + break; + } + }, + tick: function() { + if (!this.data.enabled) { + return; + } + var rotation = this.el!.getAttribute('rotation'); + if (!rotation) { + return; + } + if (this.directionX || this.directionY) { + rotation.x += this.data.dx * this.directionY; + rotation.y += this.data.dy * this.directionX; + this.el!.setAttribute('rotation', rotation); + } + } +}); + +AFRAME.registerComponent('hide-once-playing', { + schema: { type: 'selector' }, + init: function() { + this.onPlaying = this.onPlaying.bind(this); + this.onPause = this.onPause.bind(this); + }, + play: function() { + if (this.data) { + this.data.addEventListener('playing', this.onPlaying); + this.data.addEventListener('pause', this.onPause); + } + }, + pause: function() { + if (this.data) { + this.data.removeEventListener('playing', this.onPlaying); + this.data.removeEventListener('pause', this.onPause); + } + }, + onPlaying: function() { + this.el!.setAttribute('visible', false); + }, + onPause: function() { + this.el!.setAttribute('visible', true); + } +}); + +AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { + init: function() { + this.playVideo = this.playVideo.bind(this); + this.playVideoNextTick = this.playVideoNextTick.bind(this); + }, + play: function() { + window.addEventListener('vrdisplayactivate', this.playVideo); + this.el!.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); + }, + pause: function() { + this.el!.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); + window.removeEventListener('vrdisplayactivate', this.playVideo); + }, + playVideoNextTick: function() { + setTimeout(this.playVideo); + }, + playVideo: function() { + // TODO improve type + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.play(); + } +}); + +AFRAME.registerComponent('play-on-window-click', { + init: function() { + this.onClick = this.onClick.bind(this); + }, + play: function() { + window.addEventListener('click', this.onClick); + }, + pause: function() { + window.removeEventListener('click', this.onClick); + }, + onClick: function() { + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.play(); + } +}); + +AFRAME.registerComponent('toggle-play-on-window-click', { + init: function() { + this.onClick = this.onClick.bind(this); + }, + play: function() { + window.addEventListener('click', this.onClick); + }, + pause: function() { + window.removeEventListener('click', this.onClick); + }, + onClick: function() { + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.paused ? video.play() : video.pause(); + } +}); + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Animation +// Taken from https://github.com/processprocess/lazerGlazer_Viz + +interface Appender extends HTMLElement { + // append is part of living standard HTML + append(n: Node): void; +} +let scene = document.querySelector('a-scene') as Scene & Appender; +let sky = document.querySelector('a-sky'); +let objectContainer = document.querySelector('#object-container'); + +// random num generator +function getRandomNumber(x: number, y: number) { + return Math.floor(Math.random() * x + y); +} + +// get random hex color +function getRandomColor() { + let letters = '0123456789abcdef'; + let randomColor = ''; + for (let i = 0; i < 6; i++) { + randomColor += letters[Math.floor(Math.random() * 16)]; + } + return randomColor; +} + +// set sky values +sky.setAttribute('color', `#${getRandomColor()}`); +sky.setAttribute( + 'animation__color', + `property: color; dir: alternate; dur: 2000; easing: easeInOutSine; loop: true; to: #${getRandomColor()}` +); + +// change this value for more or less rings +let totalRingElements = 10; + +function generateAllElements() { + for (let a = 0; a < totalRingElements; a++) { + // element params + let totalCircleElements = getRandomNumber(10, 3); + let elementScale = getRandomNumber(3, 1); + let scaleDuration = getRandomNumber(3000, 1000); + + // path params + let pathValOne = getRandomNumber(21, -10); + let pathValTwo = getRandomNumber(11, -20); + let pathDuration = getRandomNumber(6000, 5000); + + for (let i = 1; i <= totalCircleElements; i++) { + let currentRotation = (360 / totalCircleElements) * i; + let rotateContainer = document.createElement('a-entity'); + rotateContainer.setAttribute('rotation', `0 0 ${currentRotation}`); + + // generate circle element and set params + let circleElementContainer = document.createElement('a-entity'); + circleElementContainer.setAttribute('position', `0 1 0`); + let circleElement = document.createElement('a-entity'); + circleElement.setAttribute('class', `circleElement`); + circleElement.setAttribute('scale', `${elementScale} ${elementScale} ${elementScale}`); + circleElement.setAttribute( + 'material', + `color:#${getRandomColor()}; metalness: 0; roughness: 0` + ); + circleElement.setAttribute('geometry', `primitive: sphere; radius: 1.5`); + circleElement.setAttribute( + 'animation__yoyo', + `property: scale; dir: alternate; dur: ${scaleDuration}; easing: easeInOutSine; loop: true; to: 0 0 0` + ); + circleElementContainer.appendChild(circleElement); + rotateContainer.appendChild(circleElementContainer); + + // generate path and apply it + let track1: Appender = document.createElement('a-curve') as any; + track1.setAttribute('class', `track${a}`); + scene.append(track1); + let point1 = document.createElement('a-curve-point'); + point1.setAttribute('position', '0 0 0'); + track1.append(point1); + let point2 = document.createElement('a-curve-point'); + point2.setAttribute('position', `${pathValOne} ${pathValTwo} ${pathValOne}`); + track1.append(point2); + let point3 = document.createElement('a-curve-point'); + point3.setAttribute('position', `${pathValTwo} ${pathValOne} ${pathValTwo}`); + track1.append(point3); + let point4 = document.createElement('a-curve-point'); + point4.setAttribute('position', '0 0 0'); + track1.append(point4); + circleElement.setAttribute( + `alongpath`, + `curve: .track${a}; dur: ${pathDuration}; loop: true` + ); + + // append element to main container + objectContainer.appendChild(rotateContainer); + } + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Audio Visualization +// Taken from https://github.com/ngokevin/kframe/tree/b78fb6a17d39556fcf61d00f5afb8b835651e473/components/audioanalyser +/** + * Scale children based on audio frequency levels. + */ +AFRAME.registerComponent('audioanalyser-levels-scale', { + schema: { + analyserEl: { type: 'selector' }, + max: { default: 20 }, + multiplier: { default: 100 } + }, + + tick: function(time) { + var analyserEl; + var children; + var data = this.data; + var levels; + + analyserEl = data.analyserEl || this.el; + levels = analyserEl.components.audioanalyser.levels; + if (!levels) { + return; + } + + children = this.el!.children; + for (var i = 0; i < children.length; i++) { + (children[i] as ANode).setAttribute('scale', { + x: 1, + y: Math.min(data.max, Math.max(levels[i] * data.multiplier, 0.05)), + z: 1 + }); + } + } +}); + +AFRAME.registerComponent('audioanalyser-volume-bind', { + schema: { + analyserEl: { type: 'selector' }, + component: { type: 'string' }, + property: { type: 'string' }, + max: { type: 'number' }, + multiplier: { type: 'number' } + }, + + tick: function() { + var analyserComponent; + var data = this.data; + var el = this.el!; + var value; + + analyserComponent = data.analyserEl.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + value = Math.min(data.max, analyserComponent.volume * data.multiplier); + el.setAttribute(data.component, data.property, value); + } +}); + +AFRAME.registerComponent('audioanalyser-volume-scale', { + schema: { + analyserEl: { type: 'selector' }, + multiplier: { type: 'number', default: 1 } + }, + + tick: function() { + var analyserEl = this.data.analyserEl || this.el; + var analyserComponent; + var el = this.el!; + var volume; + + analyserComponent = analyserEl.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + volume = analyserComponent.volume * this.data.multiplier; + el.setAttribute('scale', { + x: volume, + y: volume, + z: volume + }); + } +}); + +var perlin = ImprovedNoise(); + +var RINGCOUNT = 160; +var SEGMENTS = 512; + +interface AnalyserComponent extends Component { + analyser: any; + volume: number; + waveform: number[]; +} + +/** + * Generate rings (THREE.Line) and transform them using audioanalyser waveform data. + * Adapted from https://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/ + */ +AFRAME.registerComponent('audioanalyser-waveform', { + dependencies: ['audioanalyser'], + + schema: { + maxHeight: { default: 0.2 }, + multiplier: { default: 0.01 }, + radius: { default: 1 } + }, + + init: function(this: any /* TODO improve types */) { + this.colors = []; + this.geometry; + this.levels = []; + this.noisePos = 0; + this.rings = []; + }, + + update: function(this: any /* TODO improve types */) { + var data = this.data; + var el = this.el; + var i; + var lineMesh; + var loopShape; + var material; + var scale; + + // Create ring geometries. + loopShape = new THREE.Shape(); + loopShape.absarc(0, 0, data.radius, 0, Math.PI * 2, false); + this.geometry = loopShape.createPointsGeometry(SEGMENTS / 2); + this.geometry.dynamic = true; + + // Create container object. + el.setObject3D('waveformContainer', new THREE.Object3D()); + + // Create rings. + scale = 1; + for (i = 0; i < RINGCOUNT; i++) { + material = new THREE.LineBasicMaterial({ + color: 0xffffff, + linewidth: 1, + opacity: 0.7, + blending: THREE.AdditiveBlending, + depthTest: true, + transparent: true + }); + lineMesh = new THREE.Line(this.geometry, material); + + scale *= 1.05; + lineMesh.scale.x = scale; + lineMesh.scale.y = scale; + el.getObject3D('waveformContainer').add(lineMesh); + + this.rings.push(lineMesh); + this.levels.push(0); + this.colors.push(0); + } + }, + + tick: function(this: any /* TODO improve types */) { + var VOL_SENS; + var analyserComponent: AnalyserComponent; + var colors = this.colors; + var data = this.data; + var el = this.el; + var levels = this.levels; + var rings = this.rings; + + analyserComponent = el.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + VOL_SENS = 2; + levels.push((analyserComponent.volume / 256) * VOL_SENS); // 256 is max level. + levels.shift(1); + + // Add a new color onto the list. + this.noisePos += 0.005; + colors.push(Math.abs(perlin.noise(this.noisePos, 0, 0))); + colors.shift(1); + + // Write current waveform into all rings. + this.geometry.vertices.forEach(function(vertex: { z: number }, index: number) { + vertex.z = Math.min( + analyserComponent.waveform[index] * data.multiplier, + data.maxHeight + ); + }); + + // Link up last segment. + this.geometry.vertices[this.geometry.vertices.length - 1].z = this.geometry.vertices[0].z; + this.geometry.verticesNeedUpdate = true; + + rings.forEach(function transformRing(ring: THREE.Line, index: number) { + var normLevel; + normLevel = levels[RINGCOUNT - index - 1] + 0.01; // Avoid scaling by 0. + (ring.material as THREE.LineBasicMaterial).color.setHSL(colors[index], 1, normLevel); + ring.material.linewidth = normLevel * 3; + ring.material.opacity = normLevel; + ring.scale.z = normLevel; + }); + }, + + remove: function() { + this.el!.removeObject3D('waveformContainer'); + } +}); + +/** + * http://mrl.nyu.edu/~perlin/noise/ + */ +function ImprovedNoise() { + var p = [ + 151, + 160, + 137, + 91, + 90, + 15, + 131, + 13, + 201, + 95, + 96, + 53, + 194, + 233, + 7, + 225, + 140, + 36, + 103, + 30, + 69, + 142, + 8, + 99, + 37, + 240, + 21, + 10, + 23, + 190, + 6, + 148, + 247, + 120, + 234, + 75, + 0, + 26, + 197, + 62, + 94, + 252, + 219, + 203, + 117, + 35, + 11, + 32, + 57, + 177, + 33, + 88, + 237, + 149, + 56, + 87, + 174, + 20, + 125, + 136, + 171, + 168, + 68, + 175, + 74, + 165, + 71, + 134, + 139, + 48, + 27, + 166, + 77, + 146, + 158, + 231, + 83, + 111, + 229, + 122, + 60, + 211, + 133, + 230, + 220, + 105, + 92, + 41, + 55, + 46, + 245, + 40, + 244, + 102, + 143, + 54, + 65, + 25, + 63, + 161, + 1, + 216, + 80, + 73, + 209, + 76, + 132, + 187, + 208, + 89, + 18, + 169, + 200, + 196, + 135, + 130, + 116, + 188, + 159, + 86, + 164, + 100, + 109, + 198, + 173, + 186, + 3, + 64, + 52, + 217, + 226, + 250, + 124, + 123, + 5, + 202, + 38, + 147, + 118, + 126, + 255, + 82, + 85, + 212, + 207, + 206, + 59, + 227, + 47, + 16, + 58, + 17, + 182, + 189, + 28, + 42, + 223, + 183, + 170, + 213, + 119, + 248, + 152, + 2, + 44, + 154, + 163, + 70, + 221, + 153, + 101, + 155, + 167, + 43, + 172, + 9, + 129, + 22, + 39, + 253, + 19, + 98, + 108, + 110, + 79, + 113, + 224, + 232, + 178, + 185, + 112, + 104, + 218, + 246, + 97, + 228, + 251, + 34, + 242, + 193, + 238, + 210, + 144, + 12, + 191, + 179, + 162, + 241, + 81, + 51, + 145, + 235, + 249, + 14, + 239, + 107, + 49, + 192, + 214, + 31, + 181, + 199, + 106, + 157, + 184, + 84, + 204, + 176, + 115, + 121, + 50, + 45, + 127, + 4, + 150, + 254, + 138, + 236, + 205, + 93, + 222, + 114, + 67, + 29, + 24, + 72, + 243, + 141, + 128, + 195, + 78, + 66, + 215, + 61, + 156, + 180 + ]; + for (var i = 0; i < 256; i++) { + p[256 + i] = p[i]; + } + function fade(t: number) { + return t * t * t * (t * (t * 6 - 15) + 10); + } + function lerp(t: number, a: number, b: number) { + return a + t * (b - a); + } + function grad(hash: number, x: number, y: number, z: number) { + var h = hash & 15; + var u = h < 8 ? x : y, + v = h < 4 ? y : h === 12 || h === 14 ? x : z; + return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); + } + return { + noise: function(x: number, y: number, z: number) { + var floorX = ~~x, + floorY = ~~y, + floorZ = ~~z; + var X = floorX & 255, + Y = floorY & 255, + Z = floorZ & 255; + x -= floorX; + y -= floorY; + z -= floorZ; + var xMinus1 = x - 1, + yMinus1 = y - 1, + zMinus1 = z - 1; + var u = fade(x), + v = fade(y), + w = fade(z); + var A = p[X] + Y, + AA = p[A] + Z, + AB = p[A + 1] + Z, + B = p[X + 1] + Y, + BA = p[B] + Z, + BB = p[B + 1] + Z; + return lerp( + w, + lerp( + v, + lerp(u, grad(p[AA], x, y, z), grad(p[BA], xMinus1, y, z)), + lerp(u, grad(p[AB], x, yMinus1, z), grad(p[BB], xMinus1, yMinus1, z)) + ), + lerp( + v, + lerp(u, grad(p[AA + 1], x, y, zMinus1), grad(p[BA + 1], xMinus1, y, z - 1)), + lerp( + u, + grad(p[AB + 1], x, yMinus1, zMinus1), + grad(p[BB + 1], xMinus1, yMinus1, zMinus1) + ) + ) + ); + } + }; +} + +AFRAME.registerComponent('color-on-beat', { + schema: { + analyserEl: { type: 'selector' } + }, + + init: function() { + var analyserEl = this.data.analyserEl || this.el; + var el = this.el!; + + analyserEl.addEventListener('audioanalyser-beat', function() { + el.setAttribute( + 'material', + 'color', + '#' + new THREE.Color(Math.random(), Math.random(), Math.random()).getHexString() + ); + }); + } +}); + +AFRAME.registerComponent('remove-on-event', { + schema: { + el: { type: 'selector' }, + event: { type: 'string' } + }, + + init: function() { + this._removeEntity = this._removeEntity.bind(this); + }, + + update: function() { + var data = this.data; + var el = data.el || this.el; + this.removeEventListener(); + el.addEventListener(data.event, this._removeEntity); + }, + + remove: function() { + this.removeEventListener(); + }, + + removeEventListener: function() { + var data = this.data; + var el = this.el!; + el.removeEventListener(data.event, this._removeEntity); + }, + + _removeEntity: function() { + var el = this.el!; + if ((el as any).parentEl) { + (el as any).parentEl.removeChild(el); + } + if (el.parentNode) { + el.parentNode.removeChild(el); + } + } +}); + +/** + * Create expanding ring on audioanalyser beat. + */ +AFRAME.registerComponent('ring-on-beat', { + schema: { + analyserEl: { type: 'selector' } + }, + + init: function(this: any) { + var analyserEl = this.data.analyserEl || this.el; + var el = this.el; + var rings: Entity[] = (this.rings = []); + + analyserEl.addEventListener('audioanalyser-beat', function() { + var ringEl = document.createElement('a-ring'); + ringEl.setAttribute('material', 'opacity', '0.6'); + ringEl.setAttribute('position', '0 0.1 0'); + ringEl.setAttribute('rotation', '-90 0 0'); + el.appendChild(ringEl); + + ringEl.addEventListener('loaded', function() { + rings.push(ringEl); + setTimeout(function() { + el.removeChild(ringEl); + rings.splice(rings.indexOf(ringEl), 1); + }, 2000); + }); + }); + }, + + /** + * Expand ring radii. + */ + tick: function(this: any) { + this.rings.forEach(function(ringEl: Entity) { + var scale = ringEl.getComputedAttribute('scale') as Component & Coordinate; + ringEl.setAttribute('scale', { + x: scale.x * 1.06 + 0.05, + y: scale.y * 1.06 + 0.05, + z: scale.z + }); + }); + } +}); + +/* + * Change color at different levels of scale. + */ +AFRAME.registerComponent('scale-y-color', { + schema: { + from: { type: 'vec3', default: { x: 0, y: 0, z: 0 } }, + to: { type: 'vec3', default: { x: 255, y: 255, z: 255 } }, + maxScale: { default: 20 } + }, + + tick: function(this: any, time: number) { + var data = this.data; + var el = this.el; + + if (time - this.time < 50) { + return; + } + this.time = time; + + var scaleY = el.getComputedAttribute('scale').y; + var percentage = scaleY / data.maxScale; + el.setAttribute( + 'material', + 'color', + '#' + + rgbToHex( + (data.to.x - data.from.x) * percentage, + (data.to.y - data.from.y) * percentage, + (data.to.z - data.from.z) * percentage + ) + ); + } +}); + +function rgbToHex(r: number, g: number, b: number) { + var bin = (r << 16) | (g << 8) | b; + return (function(h) { + return new Array(7 - h.length).join('0') + h; + })(bin.toString(16).toUpperCase()); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Lights +// Taken from https://github.com/aframevr/aframe/blob/master/examples/showcase/dynamic-lights/index.html + +AFRAME.registerComponent('random-material', { + init: function() { + this.el!.setAttribute('material', { + color: this.getRandomColor(), + metalness: Math.random(), + roughness: Math.random() + }); + }, + getRandomColor: function() { + var letters = '0123456789ABCDEF'.split(''); + var color = '#'; + for (var i = 0; i < 6; i++) { + color += letters[Math.floor(Math.random() * 16)]; + } + return color; + } +}); + +AFRAME.registerComponent('random-torus-knot', { + init: function() { + this.el!.setAttribute('geometry', { + primitive: 'torusKnot', + radius: Math.random() * 10, + radiusTubular: Math.random() * 0.75, + p: Math.round(Math.random() * 10), + q: Math.round(Math.random() * 10) + }); + } +}); diff --git a/types/aframe/aframe-tests.ts b/types/aframe/test/aframe-tests.ts similarity index 67% rename from types/aframe/aframe-tests.ts rename to types/aframe/test/aframe-tests.ts index 5e2bd23e36..2d6ff5bb7e 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/test/aframe-tests.ts @@ -1,3 +1,14 @@ +import { + Component, + Entity, + MultiPropertySchema, + System, + SystemDefinition, + THREE, + Geometry, + registerComponent +} from 'aframe'; + // Global const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -16,7 +27,7 @@ entity.setAttribute('material', 'color', 'red'); entity.components['geometry'].data; -type MyEntity = AFrame.Entity<{ +type MyEntity = Entity<{ camera: THREE.Camera; material: THREE.Material; sound: { pause(): void }; @@ -33,29 +44,31 @@ entity.setAttribute('light', { intensity: 2.0 }); -entity.addEventListener('child-detached', (event) => { +entity.addEventListener('child-detached', event => { event.detail; }); // Components -interface TestComponent extends AFrame.Component { - multiply: (f: number) => number; +// interface TestComponent extends Component { +// multiply: (f: number) => number; +// +// data: { +// myProperty: any[], +// string: string, +// num: number +// }; +// +// system: TestSystem; +// } - data: { - myProperty: any[], - string: string, - num: number - }; - - system: TestSystem; -} - -const Component = AFRAME.registerComponent('test-component', { +const Component = registerComponent('test-component', { schema: { myProperty: { default: [], - parse() { return [true]; }, + parse() { + return [true]; + } }, string: { type: 'string' }, num: 0 @@ -69,9 +82,9 @@ const Component = AFRAME.registerComponent('test-component', { pause() {}, play() {}, - multiply(this: TestComponent, f: number) { + multiply(f: number) { // Reference to system because both were registered with the same name. - return f * this.data.num * this.system.data.counter; + return f * this.data.num * this.system!.data.counter; } }); @@ -81,13 +94,7 @@ scene.hasLoaded; // System -interface TestSystem extends AFrame.System { - data: { - counter: number; - }; -} - -const testSystem: AFrame.SystemDefinition = { +const testSystem: SystemDefinition = { schema: { counter: 0 }, @@ -101,13 +108,7 @@ AFRAME.registerSystem('test-component', testSystem); // Register Custom Geometry -interface TestGeometry extends AFrame.Geometry { - schema: AFrame.MultiPropertySchema<{ - groupIndex: number; - }>; -} - -AFRAME.registerGeometry('a-test-geometry', { +AFRAME.registerGeometry('a-test-geometry', { schema: { groupIndex: { default: 0 } }, diff --git a/types/aframe/tsconfig.json b/types/aframe/tsconfig.json index 3385a8aca7..d92e791ebd 100755 --- a/types/aframe/tsconfig.json +++ b/types/aframe/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "index.d.ts", - "aframe-tests.ts" + "test/aframe-tests.ts", + "test/aframe-io-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 0c2d244b05..71684995a4 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1128,7 +1128,7 @@ declare namespace algoliasearch { * default: "" * https://github.com/algolia/algoliasearch-client-js#facets */ - facets?: string; + facets?: string | string[]; /** * Limit the number of facet values returned for each facet. * default: "" @@ -1375,7 +1375,7 @@ declare namespace algoliasearch { * Filter the query by a set of facets. * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated */ - facetFilters?: string; + facetFilters?: string | string[] /** * If set to false, this query will not be taken into account in the analytics feature. * default true @@ -1421,6 +1421,10 @@ declare namespace algoliasearch { * The query for the search in this facet */ facetQuery: string; + /** + * The maximum number of facets to fetch + */ + maxFacetHits?: number; } interface Response { diff --git a/types/bip32/bip32-tests.ts b/types/bip32/bip32-tests.ts new file mode 100644 index 0000000000..4256ca6366 --- /dev/null +++ b/types/bip32/bip32-tests.ts @@ -0,0 +1,9 @@ +import { fromBase58 } from 'bip32'; + +const node = fromBase58("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"); + +const child = node.derivePath('m/0'); + +const grandchild = child.derive(2); + +grandchild.toWIF() === 'Kxtby4wzfHeCaRXma16dBNLgUE7Ct3Xkb6sRs3aZ56Bmtf1rcNWs'; diff --git a/types/bip32/index.d.ts b/types/bip32/index.d.ts new file mode 100644 index 0000000000..99a1b8dffd --- /dev/null +++ b/types/bip32/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for bip32 1.0 +// Project: https://github.com/bitcoinjs/bip32#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +export interface NetworkType { + wif: number; // UInt8 + bip32: { + public: number; // UInt32 + private: number; // UInt32 + }; +} + +export class BIP32 { + private constructor(d: Buffer, Q: Buffer, chainCode: Buffer, network: NetworkType); + + identifier: Buffer; + fingerprint: Buffer; + privateKey: Buffer; + publicKey: Buffer; + + private depth: number; + private index: number; + private parentFingerprint: number; + private network: NetworkType; + + isNeutered(): boolean; + neutered(): BIP32; + toBase58(): string; + toWIF(): string; + derive(index: number): BIP32; + deriveHardened(index: number): BIP32; + derivePath(path: string): BIP32; + sign(hash: Buffer): Buffer; + verify(hash: Buffer, signature: Buffer): boolean; +} + +/** + * Returns a node + * @param string base58 encoded string + * @param network network type of the node + */ +export function fromBase58(string: string, network?: NetworkType): BIP32; + +/** + * Returns a hardened node + * @param privateKey node private key + * @param chainCode 256-bits entropy extension + * @param network network type of the node + */ +export function fromPrivateKey(privateKey: Buffer, chainCode: Buffer, network?: NetworkType): BIP32; + +/** + * Returns a non-hardened node + * @param publicKey node public key + * @param chainCode 256-bits entropy extension + * @param network network type of the node + */ +export function fromPublicKey(publicKey: Buffer, chainCode: Buffer, network?: NetworkType): BIP32; + +/** + * Returns a hardened node + * @param seed seed encoding node info + * @param network network type of the node + */ +export function fromSeed(seed: Buffer, network?: NetworkType): BIP32; diff --git a/types/bip32/tsconfig.json b/types/bip32/tsconfig.json new file mode 100644 index 0000000000..ca18bb2a82 --- /dev/null +++ b/types/bip32/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", + "bip32-tests.ts" + ] +} diff --git a/types/bip32/tslint.json b/types/bip32/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bip32/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index 3ea9745ebd..398d05ad33 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -797,6 +797,22 @@ declare namespace Cesium { isLeapSecond: boolean; } + class HeadingPitchRoll { + heading: number; + pitch: number; + roll: number; + constructor(heading?: number, pitch?: number, roll?: number); + static clone(headingPitchRoll: HeadingPitchRoll, result?: HeadingPitchRoll): HeadingPitchRoll; + static equals(left: HeadingPitchRoll | null | undefined, right: HeadingPitchRoll | null | undefined): boolean; + static equalsEpsilon(left: HeadingPitchRoll | null | undefined, right: HeadingPitchRoll | null | undefined, relativeEpsilon: number, absoluteEpsilon?: number): boolean; + static fromDegrees(heading: number, pitch: number, roll: number, result?: HeadingPitchRoll): HeadingPitchRoll; + static fromQuaternion(quaternion: Quaternion, result?: HeadingPitchRoll): HeadingPitchRoll; + clone(result?: HeadingPitchRoll): HeadingPitchRoll; + equals(right: HeadingPitchRoll | null | undefined): boolean; + equalsEpsilon(right: HeadingPitchRoll | null | undefined, relativeEpsilon: number, absoluteEpsilon?: number): boolean; + toString(): string; + } + class HeightmapTerrainData { waterMask: Uint8Array | HTMLImageElement | HTMLCanvasElement; constructor(options: { @@ -959,6 +975,7 @@ declare namespace Cesium { static fromArray(array: number[], startingIndex?: number, result?: Matrix3): Matrix3; static fromColumnMajorArray(values: number[], result?: Matrix3): Matrix3; static fromRowMajorArray(values: number[], result?: Matrix3): Matrix3; + static fromHeadingPitchRoll(headingPitchRoll: HeadingPitchRoll, result?: Matrix3): Matrix3; static fromQuaternion(quaternion: Quaternion): Matrix3; static fromScale(scale: Cartesian3, result?: Matrix3): Matrix3; static fromUniformScale(scale: number, result?: Matrix3): Matrix3; @@ -1236,7 +1253,7 @@ declare namespace Cesium { toString(): string; static fromAxisAngle(axis: Cartesian3, angle: number, result?: Quaternion): Quaternion; static fromRotationMatrix(matrix: Matrix3, result?: Quaternion): Quaternion; - static fromHeadingPitchRoll(heading: number, pitch: number, roll: number, result: Quaternion): Quaternion; + static fromHeadingPitchRoll(headingPitchRoll: HeadingPitchRoll, result?: Quaternion): Quaternion; static pack(value: Quaternion, array: number[], startingIndex?: number): number[]; static unpack(array: number[], startingIndex?: number, result?: Quaternion): Quaternion; static convertPackedArrayForInterpolation(packedArray: number[], startingIndex?: number, lastIndex?: number, result?: number[]): void; @@ -4880,13 +4897,15 @@ declare namespace Cesium { function eastNorthUpToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; function northEastDownToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; function northUpEastToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; - function headingPitchRollToFixedFrame(origin: Cartesian3, heading: number, pitch: number, roll: number, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; - function headingPitchRollQuaternion(origin: Cartesian3, heading: number, pitch: number, roll: number, ellipsoid?: Ellipsoid, result?: Quaternion): Quaternion; + function headingPitchRollToFixedFrame(origin: Cartesian3, headingPitchRoll: HeadingPitchRoll, ellipsoid?: Ellipsoid, fixedFrameTransform?: LocalFrameToFixedFrame, result?: Matrix4): Matrix4; + function headingPitchRollQuaternion(origin: Cartesian3, headingPitchRoll: HeadingPitchRoll, ellipsoid?: Ellipsoid, fixedFrameTransform?: LocalFrameToFixedFrame, + result?: Quaternion): Quaternion; function computeTemeToPseudoFixedMatrix(date: JulianDate, result?: Matrix3): Matrix3; function preloadIcrfFixed(timeInterval: TimeInterval): Promise; function computeIcrfToFixedMatrix(date: JulianDate, result?: Matrix3): Matrix3; function computeFixedToIcrfMatrix(date: JulianDate, result?: Matrix3): Matrix3; function pointToWindowCoordinates(modelViewProjectionMatrix: Matrix4, viewportTransformation: Matrix4, point: Cartesian3, result?: Cartesian2): Cartesian2; + type LocalFrameToFixedFrame = (origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4) => Matrix4; } namespace TridiagonalSystemSolver { diff --git a/types/cesium/test/cesium-global.test.ts b/types/cesium/test/cesium-global.test.ts index 8974e56542..512f977344 100644 --- a/types/cesium/test/cesium-global.test.ts +++ b/types/cesium/test/cesium-global.test.ts @@ -46,3 +46,7 @@ const entity = new Cesium.Entity({ }) }); viewer.entities.add(entity); + +const hpr = new Cesium.HeadingPitchRoll(1.0, 2.2, 3.4); +const quat: Cesium.Quaternion = Cesium.Quaternion.fromHeadingPitchRoll(hpr); +const matrix: Cesium.Matrix3 = Cesium.Matrix3.fromHeadingPitchRoll(hpr); diff --git a/types/cesium/test/cesium-module.test.ts b/types/cesium/test/cesium-module.test.ts index 726daf7df2..2fe8f6cdb8 100644 --- a/types/cesium/test/cesium-module.test.ts +++ b/types/cesium/test/cesium-module.test.ts @@ -48,3 +48,7 @@ const entity = new Cesium.Entity({ }) }); viewer.entities.add(entity); + +const hpr = new Cesium.HeadingPitchRoll(1.0, 2.2, 3.4); +const quat: Cesium.Quaternion = Cesium.Quaternion.fromHeadingPitchRoll(hpr); +const matrix: Cesium.Matrix3 = Cesium.Matrix3.fromHeadingPitchRoll(hpr); diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 23feb61d45..aa6cd54eb7 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -158,6 +158,8 @@ interface Model { tension: number; x: number; y: number; + base: number; + head: number; } declare namespace Chart { diff --git a/types/d3-delaunay/d3-delaunay-tests.ts b/types/d3-delaunay/d3-delaunay-tests.ts new file mode 100644 index 0000000000..7f3103f60e --- /dev/null +++ b/types/d3-delaunay/d3-delaunay-tests.ts @@ -0,0 +1,118 @@ +/** + * TypeScript definition tests for d3-delaunay module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3 from 'd3-delaunay'; + +// Test Delaunay class + +const constructedDelaunay = new d3.Delaunay([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); +const defaultDelaunayFromArray: d3.Delaunay<[number, number]> = d3.Delaunay.from([[0, 0], [1, 0], [0, 1], [1, 1]]); +const defaultDelaunayFromIterator = d3.Delaunay.from((function*() { + yield [0, 0]; + yield [1, 0]; + yield [0, 1]; + yield [1, 1]; +})()); +const customDelaunayFromArray = d3.Delaunay.from({length: 4}, (d, i) => i & 1, (d, i) => (i >> 1) & 1); +const customDelaunayFromIterator = d3.Delaunay.from((function*() { + yield {x: 0, y: 0}; + yield {x: 1, y: 0}; + yield {x: 0, y: 1}; + yield {x: 1, y: 1}; +})(), p => p.x, p => p.y); + +const {points, halfedges, hull, triangles} = defaultDelaunayFromArray; +for (let i = 0, l = points.length; i < l; i++) { + typeof(points[i]); +} +for (let i = 0, l = halfedges.length; i < l; i++) { + const j = halfedges[i]; + const ti = triangles[i]; + const tj = triangles[j]; + const pix = points[ti * 2]; + const piy = points[ti * 2 + 1]; + const pjx = points[tj * 2]; + const pjy = points[tj * 2 + 1]; +} +for (let n = hull.next; n !== hull; n = n.next) { + const i: number = n.i; + const x: number = n.x; + const y: number = n.y; + const t: number = n.t; + const next: d3.Delaunay.Node = n.next; + const prev: d3.Delaunay.Node = n.prev; + const removed: boolean = n.removed; +} +for (let i = 0, l = triangles.length; i < l; i++) { + const t0 = triangles[i * 3 + 0]; + const t1 = triangles[i * 3 + 1]; + const t2 = triangles[i * 3 + 2]; + const p0x = points[t0 * 2]; + const p0y = points[t0 * 2 + 1]; + const p1x = points[t1 * 2]; + const p1y = points[t1 * 2 + 1]; + const p2x = points[t2 * 2]; + const p2y = points[t2 * 2 + 1]; +} +const findClosest = defaultDelaunayFromArray.find(0.5, 0.5); +for (const neighbor of defaultDelaunayFromArray.neighbors(0)) { + typeof(neighbor); +} +const render: string = defaultDelaunayFromArray.render(); +const renderHull: string = defaultDelaunayFromArray.renderHull(); +const renderTriangle: string = defaultDelaunayFromArray.renderTriangle(0); +const renderPoints: string = defaultDelaunayFromArray.renderPoints(); +const renderPointsRadius: string = defaultDelaunayFromArray.renderPoints(void 0, 3); +for (const p of defaultDelaunayFromArray.hullPolygon()) { + const x = p[0]; + const y = p[1]; +} +for (const poly of defaultDelaunayFromArray.trianglePolygons()) { + for (const p of poly) { + const x = p[0]; + const y = p[1]; + } +} +for (const p of defaultDelaunayFromArray.trianglePolygon(0)) { + const x = p[0]; + const y = p[1]; +} + +// Test Voronoi class + +const v = defaultDelaunayFromArray.voronoi(); +const {circumcenters, vectors} = v; +const d: d3.Delaunay<[number, number]> = v.delaunay; +for (let i = 0, l = circumcenters.length; i < l; i++) { + const x: number = circumcenters[i * 2]; + const y: number = circumcenters[i * 2 + 1]; +} +for (let i = 0, l = vectors.length; i < l; i++) { + const vx: number = vectors[i * 4]; + const vy: number = vectors[i * 4 + 1]; + const wx: number = vectors[i * 4 + 2]; + const wy: number = vectors[i * 4 + 3]; +} +const xmin: number = v.xmin; +const ymin: number = v.ymin; +const xmax: number = v.xmax; +const ymax: number = v.ymax; +const contains: boolean = v.contains(0, 0.5, 0.5); +const vrender: string = v.render(); +const vrenderBounds: string = v.renderBounds(); +const renderCell: string = v.renderCell(0); +for (const poly of v.cellPolygons()) { + for (const p of poly) { + const x = p[0]; + const y = p[1]; + } +} +for (const p of v.cellPolygon(0)) { + const x = p[0]; + const y = p[1]; +} diff --git a/types/d3-delaunay/index.d.ts b/types/d3-delaunay/index.d.ts new file mode 100644 index 0000000000..c5d10e8aa3 --- /dev/null +++ b/types/d3-delaunay/index.d.ts @@ -0,0 +1,359 @@ +// Type definitions for d3-delaunay 4.1 +// Project: https://github.com/d3/d3-delaunay +// Definitions by: Bradley Odell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Delaunay triangulation + */ +export class Delaunay

{ + /** + * The coordinates of the points as an array [x0, y0, x1, y1, ...]. + * Typically, this is a Float64Array, however you can use any array-like type in the constructor. + */ + points: ArrayLike; + + /** + * The halfedge indices as an Int32Array [j0, j1, ...]. + * For each index 0 <= i < halfedges.length, there is a halfedge from triangle vertex j = halfedges[i] to triangle vertex i. + */ + halfedges: Int32Array; + + /** + * An arbitrary node on the convex hull. + * The convex hull is represented as a circular doubly-linked list of nodes. + */ + hull: Delaunay.Node; + + /** + * The triangle vertex indices as an Uint32Array [i0, j0, k0, i1, j1, k1, ...]. + * Each contiguous triplet of indices i, j, k forms a counterclockwise triangle. + * The coordinates of the triangle's points can be found by going through 'points'. + */ + triangles: Uint32Array; + + /** + * The incoming halfedge indexes as a Int32Array [e0, e1, e2, ...]. + * For each point i, inedges[i] is the halfedge index e of an incoming halfedge. + * For coincident points, the halfedge index is -1; for points on the convex hull, the incoming halfedge is on the convex hull; for other points, the choice of incoming halfedge is arbitrary. + */ + inedges: Int32Array; + + /** + * The outgoing halfedge indexes as a Int32Array [e0, e1, e2, ...]. + * For each point i on the convex hull, outedges[i] is the halfedge index e of the corresponding outgoing halfedge; for other points, the halfedge index is -1. + */ + outedges: Int32Array; + + /** + * Returns the Delaunay triangulation for the given flat array [x0, y0, x1, y1, …] of points. + */ + constructor(points: ArrayLike); + + /** + * Returns the Delaunay triangulation for the given array or iterable of points where each point is an array in the form: [x, y]. + */ + static from(points: ArrayLike|Iterable): Delaunay; + + /** + * Returns the Delaunay triangulation for the given array or iterable of points. + * Otherwise, the getX and getY functions are invoked for each point in order, and must return the respective x- and y-coordinate for each point. + * If that is specified, the functions getX and getY are invoked with that as this. + * (See Array.from for reference.) + */ + static from

(points: ArrayLike

|Iterable

, + getX: Delaunay.GetCoordinate|Iterable

>, + getY: Delaunay.GetCoordinate|Iterable

>, + that?: any): Delaunay

; + + /** + * Returns the index of the input point that is closest to the specified point ⟨x, y⟩. + * The search is started at the specified point i. If i is not specified, it defaults to zero. + */ + find(x: number, y: number, i?: number): number; + + /** + * Returns an iterable over the indexes of the neighboring points to the specified point i. + * The iterable is empty if i is a coincident point. + */ + neighbors(i: number): IterableIterator; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the convex hull. + */ + hullPolygon(): Delaunay.Polygon; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing the triangle i. + */ + trianglePolygon(i: number): Delaunay.Triangle; + + /** + * Returns an iterable over the polygons for each triangle, in order. + */ + trianglePolygons(): IterableIterator; + + /** + * Renders the edges of the Delaunay triangulation to an SVG path string. + */ + render(): string; + + /** + * Renders the edges of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the convex hull of the Delaunay triangulation to an SVG path string. + */ + renderHull(): string; + + /** + * Renders the convex hull of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + renderHull(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders triangle i of the Delaunay triangulation to an SVG path string. + */ + renderTriangle(i: number): string; + + /** + * Renders triangle i of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo, context.lineTo and context.closePath methods from the CanvasPathMethods API. + */ + renderTriangle(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; + + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with radius 2. + */ + renderPoints(): string; + + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with the specified radius. + */ + renderPoints(context: undefined, radius: number): string; + + /** + * Renders the input points of the Delaunay triangulation to the specified context as circles with the specified radius. + * If radius is not specified, it defaults to 2. + * The specified context must implement the context.moveTo and context.arc methods from the CanvasPathMethods API. + */ + renderPoints(context: Delaunay.MoveContext & Delaunay.ArcContext, radius?: number): void; + + /** + * Returns the Voronoi diagram for the associated points. + * When rendering, the diagram will be clipped to the specified bounds = [xmin, ymin, xmax, ymax]. + * If bounds is not specified, it defaults to [0, 0, 960, 500]. + * See To Infinity and Back Again for an interactive explanation of Voronoi cell clipping. + */ + voronoi(bounds?: Delaunay.Bounds): Voronoi

; +} + +export namespace Delaunay { + /** + * A point represented as an array tuple [x, y]. + */ + type Point = number[]; + + /** + * A closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing a triangle. + */ + type Triangle = Point[]; + + /** + * A closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]]. + */ + type Polygon = Point[]; + + /** + * A rectangular area [x, y, width, height]. + */ + type Bounds = number[]; + + /** + * A function to extract a x- or y-coordinate from the specified point. + */ + type GetCoordinate = (point: P, i: number, points: PS) => number; + + /** + * A point node on a convex hull (represented as a circular linked list). + */ + interface Node { + /** + * The index of the associated point. + */ + i: number; + + /** + * The x-coordinate of the associated point. + */ + x: number; + + /** + * The y-coordinate of the associated point. + */ + y: number; + + /** + * The index of the (incoming or outgoing?) associated halfedge. + */ + t: number; + + /** + * The previous node on the hull. + */ + prev: Node; + + /** + * The next node on the hull. + */ + next: Node; + + /** + * Whether the node has been removed from the linked list. + */ + removed: boolean; + } + + /** + * An interface for the rect() method of the CanvasPathMethods API. + */ + interface RectContext { + /** + * rect() method of the CanvasPathMethods API. + */ + rect(x: number, y: number, width: number, height: number): void; + } + + /** + * An interface for the moveTo() method of the CanvasPathMethods API. + */ + interface MoveContext { + /** + * moveTo() method of the CanvasPathMethods API. + */ + moveTo(x: number, y: number): void; + } + + /** + * An interface for the lineTo() method of the CanvasPathMethods API. + */ + interface LineContext { + /** + * lineTo() method of the CanvasPathMethods API. + */ + lineTo(x: number, y: number): void; + } + + /** + * An interface for the arc() method of the CanvasPathMethods API. + */ + interface ArcContext { + /** + * arc() method of the CanvasPathMethods API. + */ + arc(x: number, y: number, radius: number, + startAngle: number, endAngle: number, + counterclockwise?: boolean): void; + } + + /** + * An interface for the closePath() method of the CanvasPathMethods API. + */ + interface ClosableContext { + /** + * closePath() method of the CanvasPathMethods API. + */ + closePath(): void; + } +} + +/** + * Voronoi regions + */ +export class Voronoi

{ + /** + * The Voronoi diagram’s associated Delaunay triangulation. + */ + delaunay: Delaunay

; + + /** + * The circumcenters of the Delaunay triangles [cx0, cy0, cx1, cy1, ...]. + * Each contiguous pair of coordinates cx, cy is the circumcenter for the corresponding triangle. + * These circumcenters form the coordinates of the Voronoi cell polygons. + */ + circumcenters: Float64Array; + + /** + * An array [vx0, vy0, wx0, wy0, ...] where each non-zero quadruple describes an open (infinite) cell + * on the outer hull, giving the directions of two open half-lines. + */ + vectors: Float64Array; + + /** + * The bounds of the viewport [xmin, ymin, xmax, ymax] for rendering the Voronoi diagram. + * These values only affect the rendering methods (voronoi.render, voronoi.renderBounds, cell.render). + */ + xmin: number; + ymin: number; + xmax: number; + ymax: number; + + /** + * Internally used to implement Delaunay#voronoi. + */ + constructor(delaunay: Delaunay

, bounds: Delaunay.Bounds); + + /** + * Returns true if the cell with the specified index i contains the specified point ⟨x, y⟩. + * (This method is not affected by the associated Voronoi diagram’s viewport bounds.) + */ + contains(i: number, x: number, y: number): boolean; + + /** + * Returns the convex, closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the cell for the specified point i. + */ + cellPolygon(i: number): Delaunay.Polygon; + + /** + * Returns an iterable over the polygons for each cell, in order. + */ + cellPolygons(): IterableIterator; + + /** + * Renders the mesh of Voronoi cells to an SVG path string. + */ + render(): string; + + /** + * Renders the mesh of Voronoi cells to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the viewport extent to an SVG path string. + */ + renderBounds(): string; + + /** + * Renders the viewport extent to the specified context. + * The specified context must implement the context.rect method from the CanvasPathMethods API. + * Equivalent to context.rect(voronoi.xmin, voronoi.ymin, voronoi.xmax - voronoi.xmin, voronoi.ymax - voronoi.ymin). + */ + renderBounds(context: Delaunay.RectContext): void; + + /** + * Renders the cell with the specified index i to an SVG path string. + */ + renderCell(i: number): string; + + /** + * Renders the cell with the specified index i to the specified context. + * The specified context must implement the context.moveTo, context.lineTo, and context.closePath methods from the CanvasPathMethods API. + */ + renderCell(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; +} diff --git a/types/d3-delaunay/tsconfig.json b/types/d3-delaunay/tsconfig.json new file mode 100644 index 0000000000..ab2a753d44 --- /dev/null +++ b/types/d3-delaunay/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-delaunay-tests.ts" + ] +} \ No newline at end of file diff --git a/types/d3-delaunay/tslint.json b/types/d3-delaunay/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/d3-delaunay/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/delaunator/delaunator-tests.ts b/types/delaunator/delaunator-tests.ts index 1d50e0273a..6310448c83 100644 --- a/types/delaunator/delaunator-tests.ts +++ b/types/delaunator/delaunator-tests.ts @@ -1,9 +1,12 @@ import * as Delaunator from 'delaunator'; -import { Points, GetPoint } from 'delaunator'; + +// Zipped points [x0, y0, x1, y1, ...] +const zippedPoints = [168, 180, 168, 178, 168, 179, 168, 181, 168, 183, 167, 183, 167, 184]; +const zipped = new Delaunator(zippedPoints); // Default [x, y] -const points: Points = [[168, 180], [168, 178], [168, 179], [168, 181], [168, 183], [167, 183], [167, 184]]; -const d = new Delaunator(points); +const defaultPoints = [[168, 180], [168, 178], [168, 179], [168, 181], [168, 183], [167, 183], [167, 184]]; +const d = Delaunator.from(defaultPoints); // Custom getX & getY interface CustomPoint { @@ -15,17 +18,18 @@ const customPoints = [{x: 168, y: 180}, {x: 168, y: 178}, {x: 168, y: 179}, {x: const getX = (point: CustomPoint) => point.x; const getY = (point: CustomPoint) => point.y; -new Delaunator(customPoints, point => point.x, point => point.y); -new Delaunator(customPoints, getX, getY); +Delaunator.from(customPoints, point => point.x, point => point.y); +Delaunator.from(customPoints, getX, getY); // To get the coordinates of all triangles, use: const triangles = d.triangles; const halfedges = d.halfedges; +const hull = d.hull; const coordinates: number[][][] = []; for (let i = 0; i < triangles.length; i += 3) { coordinates.push([ - points[triangles[i]], - points[triangles[i + 1]], - points[triangles[i + 2]] + defaultPoints[triangles[i]], + defaultPoints[triangles[i + 1]], + defaultPoints[triangles[i + 2]] ]); } diff --git a/types/delaunator/index.d.ts b/types/delaunator/index.d.ts index 5761fec4a8..c717feec95 100644 --- a/types/delaunator/index.d.ts +++ b/types/delaunator/index.d.ts @@ -1,13 +1,14 @@ -// Type definitions for delaunator 1.0 +// Type definitions for delaunator 2.0 // Project: https://github.com/mapbox/delaunator#readme // Definitions by: Denis Carriere +// Bradley Odell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Delaunator { +declare class Delaunator

{ /** - * A flat Int32Array array of triangle vertex indices (each group of three numbers forms a triangle). All triangles are directed counterclockwise. + * A flat Uint32Array array of triangle vertex indices (each group of three numbers forms a triangle). All triangles are directed counterclockwise. */ - triangles: Int32Array; + triangles: Uint32Array; /** * A flat Int32Array array of triangle half-edge indices that allows you to traverse the triangulation. @@ -19,17 +20,36 @@ declare class Delaunator { halfedges: Int32Array; /** - * Constructs a delaunay triangulation object given an array of points ([x, y] by default). Duplicate points are skipped. + * A circular doubly-linked list that holds a convex hull of the delaunay triangulation. */ - constructor(points: Delaunator.Points); - constructor(points: T[], getX: Delaunator.GetPoint, getY: Delaunator.GetPoint); + hull: Delaunator.Node; + + /** + * Constructs a delaunay triangulation object given a typed array of point coordinates of the form: [x0, y0, x1, y1, ...]. + */ + constructor(points: ArrayLike); + + /** + * Constructs a delaunay triangulation object given an array of points (e.g. [x, y]). Duplicate points are skipped. + */ + static from(points: ArrayLike>): Delaunator>; + + /** + * Constructs a delaunay triangulation object given an array of custom points. Duplicate points are skipped. + */ + static from

(points: ArrayLike

, getX: (point: P) => number, getY: (point: P) => number): Delaunator

; } declare namespace Delaunator { - type Point = number[]; - type Points = Point[]; - type Triangles = Int32Array; - type HalfEdges = Int32Array; - type GetPoint = (point: T) => number; + interface Node { + i: number; + x: number; + y: number; + t: number; + prev: Node|null; + next: Node|null; + removed: boolean; + } } + export = Delaunator; diff --git a/types/delaunator/tslint.json b/types/delaunator/tslint.json index f2ffe2445b..b4b47a0378 100644 --- a/types/delaunator/tslint.json +++ b/types/delaunator/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-duplicate-imports": false - } + "extends": "dtslint/dt.json" } diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 06cb8f55f2..aea132cb3d 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -8,6 +8,7 @@ // Willis Plummer // Santiago Vilar // Ulf Schwekendiek +// Pablo Varela // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -950,6 +951,7 @@ import Editor = Draft.Component.Base.DraftEditor; import EditorProps = Draft.Component.Base.DraftEditorProps; import EditorBlock = Draft.Component.Components.DraftEditorBlock; import EditorState = Draft.Model.ImmutableData.EditorState; +import EditorChangeType = Draft.Model.ImmutableData.EditorChangeType; import CompositeDecorator = Draft.Model.Decorators.CompositeDraftDecorator; import Entity = Draft.Model.Entity.DraftEntity; @@ -999,6 +1001,7 @@ export { EditorProps, EditorBlock, EditorState, + EditorChangeType, CompositeDecorator, Entity, diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index aa676aaf41..fe784dae8b 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1708,14 +1708,18 @@ declare module 'ember' { /** * Sets the provided key or path to the value. */ - set(key: K, value: UnwrapComputedPropertySetter): UnwrapComputedPropertySetter; + set(key: K, value: this[K]): this[K]; + set(key: keyof this, value: T): T; /** * Sets a list of properties at once. These properties are set inside * a single `beginPropertyChanges` and `endPropertyChanges` batch, so * observers will be buffered. */ setProperties( - hash: Pick, K> + hash: Pick + ): Pick< UnwrapComputedPropertySetters, K>; + setProperties( + hash: {[KK in K]: any} ): Pick< UnwrapComputedPropertySetters, K>; /** * Convenience method to call `propertyWillChange` and `propertyDidChange` in @@ -3118,22 +3122,22 @@ declare module 'ember' { /** * A value is blank if it is empty or a whitespace string. */ - function isBlank(obj: any): boolean; + function isBlank(obj?: any): boolean; /** * Verifies that a value is `null` or an empty string, empty array, * or empty function. */ - function isEmpty(obj: any): boolean; + function isEmpty(obj?: any): boolean; /** * Returns true if the passed value is null or undefined. This avoids errors * from JSLint complaining about use of ==, which can be technically * confusing. */ - function isNone(obj: any): obj is null | undefined; + function isNone(obj?: any): obj is null | undefined; /** * A value is present if it not `isBlank`. */ - function isPresent(obj: any): boolean; + function isPresent(obj?: any): boolean; /** * Merge the contents of two objects together into the first object. * @deprecated Use Object.assign @@ -3282,7 +3286,7 @@ declare module 'ember' { /** * Returns a consistent type for the passed object. */ - function typeOf(item: any): string; + function typeOf(item?: any): string; /** * Copy properties from a source object to a target object. * @deprecated Use Object.assign @@ -3865,7 +3869,6 @@ declare module '@ember/string' { export const classify: typeof Ember.String.classify; export const dasherize: typeof Ember.String.dasherize; export const decamelize: typeof Ember.String.decamelize; - export const fmt: typeof Ember.String.fmt; export const htmlSafe: typeof Ember.String.htmlSafe; export const isHTMLSafe: typeof Ember.String.isHTMLSafe; export const loc: typeof Ember.String.loc; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index e1eefb75e9..7446d5e3ef 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -25,3 +25,27 @@ class MyObject31 extends Ember.Object { super(properties); } } + +class Foo extends Ember.Object.extend({ + a: Ember.computed({ + get() { return ''; }, + set(key: string, newVal: string) { return ''; } + }) +}) { + b = 5; + baz() { + let y = this.b; // $ExpectType number + let z = this.a; // $ExpectType ComputedProperty + this.b = 10; + this.get('b').toFixed(4); // $ExpectType string + this.set('a', 'abc').split(','); // $ExpectType string[] + this.set('b', 10).toFixed(4); // $ExpectType string + + this.setProperties({ b: 11 }); + // this.setProperties({ b: '11' }); // $ExpectError + this.setProperties({ + a: 'def', + b: 11 + }); + } +} diff --git a/types/ember/test/utils.ts b/types/ember/test/utils.ts index d729d472b8..9ddc2b361e 100755 --- a/types/ember/test/utils.ts +++ b/types/ember/test/utils.ts @@ -2,6 +2,11 @@ import Ember from 'ember'; import * as utils from '@ember/utils'; import { assertType } from "./lib/assert"; +function testTypeOf() { + utils.typeOf(); // $ExpectType string + utils.typeOf({}); // $ExpectType string +} + function testIsNoneType() { const maybeUndefined: string | undefined = 'not actually undefined'; if (utils.isNone(maybeUndefined)) { @@ -9,6 +14,31 @@ function testIsNoneType() { } const anotherString = maybeUndefined + 'another string'; + utils.isNone(); // $ExpectType boolean +} + +function testIsBlank() { + utils.isBlank(); // $ExpectType boolean + utils.isBlank(''); // $ExpectType boolean + utils.isBlank('', ''); // $ExpectError +} + +function testIsEmpty() { + utils.isEmpty(); // $ExpectType boolean + utils.isEmpty(''); // $ExpectType boolean + utils.isEmpty('', ''); // $ExpectError +} + +function testIsPresent() { + utils.isPresent(); // $ExpectType boolean + utils.isPresent(''); // $ExpectType boolean + utils.isPresent('', ''); // $ExpectError +} + +function testIsNone() { + utils.isNone(); // $ExpectType boolean + utils.isNone(''); // $ExpectType boolean + utils.isNone('', ''); // $ExpectError } function testMerge() { diff --git a/types/feathersjs__feathers/feathersjs__feathers-tests.ts b/types/feathersjs__feathers/feathersjs__feathers-tests.ts index a624187c68..7d0e961700 100644 --- a/types/feathersjs__feathers/feathersjs__feathers-tests.ts +++ b/types/feathersjs__feathers/feathersjs__feathers-tests.ts @@ -1,4 +1,4 @@ -import feathers, { Application } from '@feathersjs/feathers'; +import feathers, { Application, HookContext } from '@feathersjs/feathers'; interface User { id: number; @@ -14,3 +14,12 @@ const app = feathers() as Application; app.service('users').get(0).then(u => { const user: User = u; }); + +app.service('users').hooks({ + before: { + all: (context: HookContext) => { + context.statusCode = 200; + context.dispatch = { test: 'true' }; + } + } +}); diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 1e448dbf4f..53cdf182a1 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for @feathersjs/feathers 3.0 // Project: http://feathersjs.com/ -// Definitions by: Jan Lohage , Abraao Alves +// Definitions by: Jan Lohage +// Abraao Alves +// Tim Mensch // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.3 @@ -51,16 +53,71 @@ export type Hook = (hook: HookContext) => (Promise { - app?: Application; + /** + * A read only property that contains the Feathers application object. This can be used to + * retrieve other services (via context.app.service('name')) or configuration values. + */ + readonly app: Application; + /** + * A writeable property containing the data of a create, update and patch service + * method call. + */ data?: T; + /** + * A writeable property with the error object that was thrown in a failed method call. + * It is only available in error hooks. + */ error?: any; + /** + * A writeable property and the id for a get, remove, update and patch service + * method call. For remove, update and patch context.id can also be null when + * modifying multiple entries. In all other cases it will be undefined. + */ id?: string | number; - method?: string; - params?: Params; - path?: string; + /** + * A read only property with the name of the service method (one of find, get, + * create, update, patch, remove). + */ + readonly method: string; + /** + * A writeable property that contains the service method parameters (including + * params.query). + */ + params: Params; + /** + * A read only property and contains the service name (or path) without leading or + * trailing slashes. + */ + readonly path: string; + /** + * A writeable property containing the result of the successful service method call. + * It is only available in after hooks. + * + * `context.result` can also be set in + * + * - A before hook to skip the actual service method (database) call + * - An error hook to swallow the error and return a result instead + */ result?: T; - service: Service; - type: 'before' | 'after' | 'error'; + /** + * A read only property and contains the service this hook currently runs on. + */ + readonly service: Service; + /** + * A writeable, optional property and contains a "safe" version of the data that + * should be sent to any client. If context.dispatch has not been set context.result + * will be sent to the client instead. + */ + dispatch?: T; + /** + * A writeable, optional property that allows to override the standard HTTP status + * code that should be returned. + */ + statusCode?: number; + /** + * A read only property with the hook type (one of before, after or error). + */ + readonly type: "before" | "after" | "error"; } export interface HookMap { diff --git a/types/feathersjs__feathers/tslint.json b/types/feathersjs__feathers/tslint.json index f93cf8562a..702f9354fc 100644 --- a/types/feathersjs__feathers/tslint.json +++ b/types/feathersjs__feathers/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } } diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts index 53f3b5a928..a2d9f0bda0 100644 --- a/types/firefox-webext-browser/firefox-webext-browser-tests.ts +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -5,7 +5,7 @@ browser.nonexistentNS.unknownMethod(); // $ExpectError browser.runtime.getManifest(); // $ExpectType WebExtensionManifest browser.test; // $ExpectError browser.manifest; // $ExpectError -browser._manifest; // $ExpectType typeof _manifest +browser._manifest; // $ExpectError browser._manifest.WebExtensionLangpackManifest; // $ExpectError browser._manifest.NativeManifest; // $ExpectError diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index 1ce4024f4d..47035f4f87 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -2,7 +2,7 @@ // Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions // Definitions by: Jacob Bom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.9 // Generated using script at github.com/bomjacob/definitelytyped-firefox-webext-browser interface WebExtEventBase any, TCallback> { @@ -434,114 +434,102 @@ declare namespace browser._manifest { type KeyName = string; - enum _OptionalPermission { - browserSettings = "browserSettings", - cookies = "cookies", - clipboardRead = "clipboardRead", - clipboardWrite = "clipboardWrite", - geolocation = "geolocation", - idle = "idle", - notifications = "notifications", - topSites = "topSites", - webNavigation = "webNavigation", - webRequest = "webRequest", - webRequestBlocking = "webRequestBlocking", - bookmarks = "bookmarks", - find = "find", - history = "history", - activeTab = "activeTab", - tabs = "tabs" - } + type _OptionalPermission = + "browserSettings" + | "cookies" + | "clipboardRead" + | "clipboardWrite" + | "geolocation" + | "idle" + | "notifications" + | "topSites" + | "webNavigation" + | "webRequest" + | "webRequestBlocking" + | "bookmarks" + | "find" + | "history" + | "activeTab" + | "tabs"; - enum _Permission { - contextualIdentities = "contextualIdentities", - downloads = "downloads", - downloadsopen = "downloads.open", - identity = "identity", - management = "management", - alarms = "alarms", - mozillaAddons = "mozillaAddons", - storage = "storage", - unlimitedStorage = "unlimitedStorage", - privacy = "privacy", - proxy = "proxy", - nativeMessaging = "nativeMessaging", - theme = "theme", - browsingData = "browsingData", - devtools = "devtools", - geckoProfiler = "geckoProfiler", - menus = "menus", - contextMenus = "contextMenus", - pkcs11 = "pkcs11", - sessions = "sessions" - } + type _Permission = + "contextualIdentities" + | "downloads" + | "downloads.open" + | "identity" + | "management" + | "alarms" + | "mozillaAddons" + | "storage" + | "unlimitedStorage" + | "privacy" + | "proxy" + | "nativeMessaging" + | "theme" + | "browsingData" + | "devtools" + | "geckoProfiler" + | "menus" + | "contextMenus" + | "pkcs11" + | "sessions"; - enum _ProtocolHandlerProtocol { - bitcoin = "bitcoin", - geo = "geo", - gopher = "gopher", - im = "im", - irc = "irc", - ircs = "ircs", - magnet = "magnet", - mailto = "mailto", - mms = "mms", - news = "news", - nntp = "nntp", - sip = "sip", - sms = "sms", - smsto = "smsto", - ssh = "ssh", - tel = "tel", - urn = "urn", - webcal = "webcal", - wtai = "wtai", - xmpp = "xmpp" - } + type _ProtocolHandlerProtocol = + "bitcoin" + | "geo" + | "gopher" + | "im" + | "irc" + | "ircs" + | "magnet" + | "mailto" + | "mms" + | "news" + | "nntp" + | "sip" + | "sms" + | "smsto" + | "ssh" + | "tel" + | "urn" + | "webcal" + | "wtai" + | "xmpp"; - enum _WebExtensionManifestIncognito { - spanning = "spanning" - } + type _WebExtensionManifestIncognito = "spanning"; /** Defines the location the browserAction will appear by default. The default location is navbar. */ - enum _WebExtensionManifestBrowserActionDefaultArea { - navbar = "navbar", - menupanel = "menupanel", - tabstrip = "tabstrip", - personaltoolbar = "personaltoolbar" - } + type _WebExtensionManifestBrowserActionDefaultArea = + "navbar" + | "menupanel" + | "tabstrip" + | "personaltoolbar"; - enum _MatchPattern { - all_urls = "" - } + type _MatchPattern = ""; - enum _MatchPatternInternal { - all_urls = "" - } + type _MatchPatternInternal = ""; - enum _ThemeTypeAdditionalBackgroundsAlignment { - bottom = "bottom", - center = "center", - left = "left", - right = "right", - top = "top", - centerbottom = "center bottom", - centercenter = "center center", - centertop = "center top", - leftbottom = "left bottom", - leftcenter = "left center", - lefttop = "left top", - rightbottom = "right bottom", - rightcenter = "right center", - righttop = "right top" - } + type _ThemeTypeAdditionalBackgroundsAlignment = + "bottom" + | "center" + | "left" + | "right" + | "top" + | "center bottom" + | "center center" + | "center top" + | "left bottom" + | "left center" + | "left top" + | "right bottom" + | "right center" + | "right top"; - enum _ThemeTypeAdditionalBackgroundsTiling { - norepeat = "no-repeat", - repeat = "repeat", - repeatx = "repeat-x", - repeaty = "repeat-y" - } + type _ThemeTypeAdditionalBackgroundsTiling = + "no-repeat" + | "repeat" + | "repeat-x" + | "repeat-y"; } /** @@ -555,11 +543,10 @@ declare namespace browser.browserSettings { /* browserSettings types */ /** How images should be animated in the browser. */ - enum ImageAnimationBehavior { - normal = "normal", - none = "none", - once = "once" - } + type ImageAnimationBehavior = + "normal" + | "none" + | "once"; /* browserSettings properties */ /** Allows or disallows pop-up windows from opening in response to user events. */ @@ -596,10 +583,7 @@ declare namespace browser.clipboard { type ArrayBuffer = any; /** The type of imageData. */ - enum _SetImageData { - jpeg = "jpeg", - png = "png" - } + type _SetImageData = "jpeg" | "png"; /* clipboard functions */ /** @@ -766,13 +750,12 @@ declare namespace browser.cookies { * will be "evicted". If a cookie was automatically removed due to a "set" call that overwrote it, "cause" will be * "overwrite". Plan your response accordingly. */ - enum OnChangedCause { - evicted = "evicted", - expired = "expired", - explicit = "explicit", - expired_overwrite = "expired_overwrite", - overwrite = "overwrite" - } + type OnChangedCause = + "evicted" + | "expired" + | "explicit" + | "expired_overwrite" + | "overwrite"; /* cookies functions */ /** @@ -911,38 +894,36 @@ declare namespace browser.cookies { */ declare namespace browser.downloads { /* downloads types */ - enum FilenameConflictAction { - uniquify = "uniquify", - overwrite = "overwrite", - prompt = "prompt" - } + type FilenameConflictAction = + "uniquify" + | "overwrite" + | "prompt"; - enum InterruptReason { - FILE_FAILED = "FILE_FAILED", - FILE_ACCESS_DENIED = "FILE_ACCESS_DENIED", - FILE_NO_SPACE = "FILE_NO_SPACE", - FILE_NAME_TOO_LONG = "FILE_NAME_TOO_LONG", - FILE_TOO_LARGE = "FILE_TOO_LARGE", - FILE_VIRUS_INFECTED = "FILE_VIRUS_INFECTED", - FILE_TRANSIENT_ERROR = "FILE_TRANSIENT_ERROR", - FILE_BLOCKED = "FILE_BLOCKED", - FILE_SECURITY_CHECK_FAILED = "FILE_SECURITY_CHECK_FAILED", - FILE_TOO_SHORT = "FILE_TOO_SHORT", - NETWORK_FAILED = "NETWORK_FAILED", - NETWORK_TIMEOUT = "NETWORK_TIMEOUT", - NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED", - NETWORK_SERVER_DOWN = "NETWORK_SERVER_DOWN", - NETWORK_INVALID_REQUEST = "NETWORK_INVALID_REQUEST", - SERVER_FAILED = "SERVER_FAILED", - SERVER_NO_RANGE = "SERVER_NO_RANGE", - SERVER_BAD_CONTENT = "SERVER_BAD_CONTENT", - SERVER_UNAUTHORIZED = "SERVER_UNAUTHORIZED", - SERVER_CERT_PROBLEM = "SERVER_CERT_PROBLEM", - SERVER_FORBIDDEN = "SERVER_FORBIDDEN", - USER_CANCELED = "USER_CANCELED", - USER_SHUTDOWN = "USER_SHUTDOWN", - CRASH = "CRASH" - } + type InterruptReason = + "FILE_FAILED" + | "FILE_ACCESS_DENIED" + | "FILE_NO_SPACE" + | "FILE_NAME_TOO_LONG" + | "FILE_TOO_LARGE" + | "FILE_VIRUS_INFECTED" + | "FILE_TRANSIENT_ERROR" + | "FILE_BLOCKED" + | "FILE_SECURITY_CHECK_FAILED" + | "FILE_TOO_SHORT" + | "NETWORK_FAILED" + | "NETWORK_TIMEOUT" + | "NETWORK_DISCONNECTED" + | "NETWORK_SERVER_DOWN" + | "NETWORK_INVALID_REQUEST" + | "SERVER_FAILED" + | "SERVER_NO_RANGE" + | "SERVER_BAD_CONTENT" + | "SERVER_UNAUTHORIZED" + | "SERVER_CERT_PROBLEM" + | "SERVER_FORBIDDEN" + | "USER_CANCELED" + | "USER_SHUTDOWN" + | "CRASH"; /** * *file*: @@ -958,16 +939,15 @@ declare namespace browser.downloads { * * These string constants will never change, however the set of DangerTypes may change. */ - enum DangerType { - file = "file", - url = "url", - content = "content", - uncommon = "uncommon", - host = "host", - unwanted = "unwanted", - safe = "safe", - accepted = "accepted" - } + type DangerType = + "file" + | "url" + | "content" + | "uncommon" + | "host" + | "unwanted" + | "safe" + | "accepted"; /** * *in_progress*: @@ -979,11 +959,10 @@ declare namespace browser.downloads { * * These string constants will never change, however the set of States may change. */ - enum State { - in_progress = "in_progress", - interrupted = "interrupted", - complete = "complete" - } + type State = + "in_progress" + | "interrupted" + | "complete"; interface DownloadItem { /** An identifier that is persistent across browser sessions. */ @@ -1106,10 +1085,9 @@ declare namespace browser.downloads { } /** The HTTP method to use if the URL uses the HTTP[S] protocol. */ - enum _DownloadMethod { - GET = "GET", - POST = "POST" - } + type _DownloadMethod = + "GET" + | "POST"; /* downloads functions */ /** @@ -1431,11 +1409,10 @@ declare namespace browser.extension { /* extension types */ /** The type of extension view. */ - enum ViewType { - tab = "tab", - popup = "popup", - sidebar = "sidebar" - } + type ViewType = + "tab" + | "popup" + | "sidebar"; /* extension properties */ /** @@ -1532,10 +1509,9 @@ declare namespace browser.extensionTypes { /* extensionTypes types */ /** The format of an image. */ - enum ImageFormat { - jpeg = "jpeg", - png = "png" - } + type ImageFormat = + "jpeg" + | "png"; /** Details about the format and quality of an image. */ interface ImageDetails { @@ -1550,17 +1526,15 @@ declare namespace browser.extensionTypes { } /** The soonest that the JavaScript or CSS will be injected into the tab. */ - enum RunAt { - document_start = "document_start", - document_end = "document_end", - document_idle = "document_idle" - } + type RunAt = + "document_start" + | "document_end" + | "document_idle"; /** The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet. */ - enum CSSOrigin { - user = "user", - author = "author" - } + type CSSOrigin = + "user" + | "author"; /** * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be @@ -1732,10 +1706,9 @@ declare namespace browser.identity { */ declare namespace browser.idle { /* idle types */ - enum IdleState { - active = "active", - idle = "idle" - } + type IdleState = + "active" + | "idle"; /* idle functions */ /** @@ -1783,16 +1756,14 @@ declare namespace browser.management { } /** A reason the item is disabled. */ - enum ExtensionDisabledReason { - unknown = "unknown", - permissions_increase = "permissions_increase" - } + type ExtensionDisabledReason = + "unknown" + | "permissions_increase"; /** The type of this extension. Will always be 'extension'. */ - enum ExtensionType { - extension = "extension", - theme = "theme" - } + type ExtensionType = + "extension" + | "theme"; /** * How the extension was installed. One of @@ -1801,12 +1772,11 @@ declare namespace browser.management { * `sideload`: The extension was installed by other software on the machine, * `other`: The extension was installed by other means. */ - enum ExtensionInstallType { - development = "development", - normal = "normal", - sideload = "sideload", - other = "other" - } + type ExtensionInstallType = + "development" + | "normal" + | "sideload" + | "other"; /** Information about an installed extension. */ interface ExtensionInfo { @@ -1906,17 +1876,15 @@ declare namespace browser.management { */ declare namespace browser.notifications { /* notifications types */ - enum TemplateType { - basic = "basic", - image = "image", - list = "list", - progress = "progress" - } + type TemplateType = + "basic" + | "image" + | "list" + | "progress"; - enum PermissionLevel { - granted = "granted", - denied = "denied" - } + type PermissionLevel = + "granted" + | "denied"; interface NotificationItem { /** Title of one item of a list notification. */ @@ -2145,12 +2113,11 @@ declare namespace browser.privacy.network { /* privacy.network types */ /** The IP handling policy of WebRTC. */ - enum IPHandlingPolicy { - default = "default", - default_public_and_private_interfaces = "default_public_and_private_interfaces", - default_public_interface_only = "default_public_interface_only", - disable_non_proxied_udp = "disable_non_proxied_udp" - } + type IPHandlingPolicy = + "default" + | "default_public_and_private_interfaces" + | "default_public_interface_only" + | "disable_non_proxied_udp"; /* privacy.network properties */ /** @@ -2198,11 +2165,10 @@ declare namespace browser.privacy.websites { /* privacy.websites types */ /** The mode for tracking protection. */ - enum TrackingProtectionModeOption { - always = "always", - never = "never", - private_browsing = "private_browsing" - } + type TrackingProtectionModeOption = + "always" + | "never" + | "private_browsing"; /* privacy.websites properties */ /** @@ -2333,21 +2299,19 @@ declare namespace browser.runtime { } /** The operating system the browser is running on. */ - enum PlatformOs { - mac = "mac", - win = "win", - android = "android", - cros = "cros", - linux = "linux", - openbsd = "openbsd" - } + type PlatformOs = + "mac" + | "win" + | "android" + | "cros" + | "linux" + | "openbsd"; /** The machine's processor architecture. */ - enum PlatformArch { - arm = "arm", - x8632 = "x86-32", - x8664 = "x86-64" - } + type PlatformArch = + "arm" + | "x86-32" + | "x86-64"; /** An object containing information about the current platform. */ interface PlatformInfo { @@ -2375,18 +2339,16 @@ declare namespace browser.runtime { } /** Result of the update check. */ - enum RequestUpdateCheckStatus { - throttled = "throttled", - no_update = "no_update", - update_available = "update_available" - } + type RequestUpdateCheckStatus = + "throttled" + | "no_update" + | "update_available"; /** The reason that this event is being dispatched. */ - enum OnInstalledReason { - install = "install", - update = "update", - browser_update = "browser_update" - } + type OnInstalledReason = + "install" + | "update" + | "browser_update"; /** * The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the @@ -2394,11 +2356,10 @@ declare namespace browser.runtime { * is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in * the enterprise policy. */ - enum OnRestartRequiredReason { - app_update = "app_update", - os_update = "os_update", - periodic = "periodic" - } + type OnRestartRequiredReason = + "app_update" + | "os_update" + | "periodic"; type PlatformNaclArch = any; @@ -2834,12 +2795,11 @@ declare namespace browser.types { * * Only `regular` is supported by Firefox at this time. */ - enum SettingScope { - regular = "regular", - regular_only = "regular_only", - incognito_persistent = "incognito_persistent", - incognito_session_only = "incognito_session_only" - } + type SettingScope = + "regular" + | "regular_only" + | "incognito_persistent" + | "incognito_session_only"; /** * One of @@ -2849,12 +2809,11 @@ declare namespace browser.types { * * `controllable_by_this_extension`: can be controlled by this extension * * `controlled_by_this_extension`: controlled by this extension */ - enum LevelOfControl { - not_controllable = "not_controllable", - controlled_by_other_extensions = "controlled_by_other_extensions", - controllable_by_this_extension = "controllable_by_this_extension", - controlled_by_this_extension = "controlled_by_this_extension" - } + type LevelOfControl = + "not_controllable" + | "controlled_by_other_extensions" + | "controllable_by_this_extension" + | "controlled_by_this_extension"; interface Setting { /** @@ -2934,26 +2893,24 @@ declare namespace browser.webNavigation { * transition types as defined in the history API except with `"start_page"` in place of `"auto_toplevel"` (for * backwards compatibility). */ - enum TransitionType { - link = "link", - typed = "typed", - auto_bookmark = "auto_bookmark", - auto_subframe = "auto_subframe", - manual_subframe = "manual_subframe", - generated = "generated", - start_page = "start_page", - form_submit = "form_submit", - reload = "reload", - keyword = "keyword", - keyword_generated = "keyword_generated" - } + type TransitionType = + "link" + | "typed" + | "auto_bookmark" + | "auto_subframe" + | "manual_subframe" + | "generated" + | "start_page" + | "form_submit" + | "reload" + | "keyword" + | "keyword_generated"; - enum TransitionQualifier { - client_redirect = "client_redirect", - server_redirect = "server_redirect", - forward_back = "forward_back", - from_address_bar = "from_address_bar" - } + type TransitionQualifier = + "client_redirect" + | "server_redirect" + | "forward_back" + | "from_address_bar"; interface EventUrlFilters { url: events.UrlFilter[]; @@ -3263,65 +3220,52 @@ declare namespace browser.webNavigation { */ declare namespace browser.webRequest { /* webRequest types */ - enum ResourceType { - main_frame = "main_frame", - sub_frame = "sub_frame", - stylesheet = "stylesheet", - script = "script", - image = "image", - object = "object", - object_subrequest = "object_subrequest", - xmlhttprequest = "xmlhttprequest", - xbl = "xbl", - xslt = "xslt", - ping = "ping", - beacon = "beacon", - xml_dtd = "xml_dtd", - font = "font", - media = "media", - websocket = "websocket", - csp_report = "csp_report", - imageset = "imageset", - web_manifest = "web_manifest", - other = "other" - } + type ResourceType = + "main_frame" + | "sub_frame" + | "stylesheet" + | "script" + | "image" + | "object" + | "object_subrequest" + | "xmlhttprequest" + | "xbl" + | "xslt" + | "ping" + | "beacon" + | "xml_dtd" + | "font" + | "media" + | "websocket" + | "csp_report" + | "imageset" + | "web_manifest" + | "other"; - enum OnBeforeRequestOptions { - blocking = "blocking", - requestBody = "requestBody" - } + type OnBeforeRequestOptions = + "blocking" + | "requestBody"; - enum OnBeforeSendHeadersOptions { - requestHeaders = "requestHeaders", - blocking = "blocking" - } + type OnBeforeSendHeadersOptions = + "requestHeaders" + | "blocking"; - enum OnSendHeadersOptions { - requestHeaders = "requestHeaders" - } + type OnSendHeadersOptions = "requestHeaders"; - enum OnHeadersReceivedOptions { - blocking = "blocking", - responseHeaders = "responseHeaders" - } + type OnHeadersReceivedOptions = + "blocking" + | "responseHeaders"; - enum OnAuthRequiredOptions { - responseHeaders = "responseHeaders", - blocking = "blocking", - asyncBlocking = "asyncBlocking" - } + type OnAuthRequiredOptions = + "responseHeaders" + | "blocking" + | "asyncBlocking"; - enum OnResponseStartedOptions { - responseHeaders = "responseHeaders" - } + type OnResponseStartedOptions = "responseHeaders"; - enum OnBeforeRedirectOptions { - responseHeaders = "responseHeaders" - } + type OnBeforeRedirectOptions = "responseHeaders"; - enum OnCompletedOptions { - responseHeaders = "responseHeaders" - } + type OnCompletedOptions = "responseHeaders"; /** An object describing filters to apply to webRequest events. */ interface RequestFilter { @@ -3860,16 +3804,10 @@ declare namespace browser.bookmarks { * by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the * user and the extension (default). */ - enum BookmarkTreeNodeUnmodifiable { - managed = "managed" - } + type BookmarkTreeNodeUnmodifiable = "managed"; /** Indicates the type of a BookmarkTreeNode, which can be one of bookmark, folder or separator. */ - enum BookmarkTreeNodeType { - bookmark = "bookmark", - folder = "folder", - separator = "separator" - } + type BookmarkTreeNodeType = "bookmark" | "folder" | "separator"; /** * A node (either a bookmark or a folder) in the bookmark tree. Child nodes are ordered within their parent folder. @@ -4756,18 +4694,17 @@ declare namespace browser.find { */ declare namespace browser.geckoProfiler { /* geckoProfiler types */ - enum ProfilerFeature { - java = "java", - js = "js", - leaf = "leaf", - mainthreadio = "mainthreadio", - memory = "memory", - privacy = "privacy", - restyle = "restyle", - stackwalk = "stackwalk", - tasktracer = "tasktracer", - threads = "threads" - } + type ProfilerFeature = + "java" + | "js" + | "leaf" + | "mainthreadio" + | "memory" + | "privacy" + | "restyle" + | "stackwalk" + | "tasktracer" + | "threads"; /* geckoProfiler functions */ /** Starts the profiler with the specified settings. */ @@ -4833,19 +4770,18 @@ declare namespace browser.history { /* history types */ /** The transition type for this visit from its referrer. */ - enum TransitionType { - link = "link", - typed = "typed", - auto_bookmark = "auto_bookmark", - auto_subframe = "auto_subframe", - manual_subframe = "manual_subframe", - generated = "generated", - auto_toplevel = "auto_toplevel", - form_submit = "form_submit", - reload = "reload", - keyword = "keyword", - keyword_generated = "keyword_generated" - } + type TransitionType = + "link" + | "typed" + | "auto_bookmark" + | "auto_subframe" + | "manual_subframe" + | "generated" + | "auto_toplevel" + | "form_submit" + | "reload" + | "keyword" + | "keyword_generated"; /** An object encapsulating one result of a history query. */ interface HistoryItem { @@ -4976,30 +4912,28 @@ declare namespace browser.contextMenus { * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other * contexts except for 'tab' and 'tools_menu'. */ - enum ContextType { - all = "all", - page = "page", - frame = "frame", - selection = "selection", - link = "link", - editable = "editable", - password = "password", - image = "image", - video = "video", - audio = "audio", - launcher = "launcher", - browser_action = "browser_action", - page_action = "page_action", - tab = "tab" - } + type ContextType = + "all" + | "page" + | "frame" + | "selection" + | "link" + | "editable" + | "password" + | "image" + | "video" + | "audio" + | "launcher" + | "browser_action" + | "page_action" + | "tab"; /** The type of menu item. */ - enum ItemType { - normal = "normal", - checkbox = "checkbox", - radio = "radio", - separator = "separator" - } + type ItemType = + "normal" + | "checkbox" + | "radio" + | "separator"; /** Information sent when a context menu item is clicked. */ interface OnClickData { @@ -5036,13 +4970,12 @@ declare namespace browser.contextMenus { modifiers: _OnClickDataModifiers[]; } - enum _OnClickDataModifiers { - Shift = "Shift", - Alt = "Alt", - Command = "Command", - Ctrl = "Ctrl", - MacCtrl = "MacCtrl" - } + type _OnClickDataModifiers = + "Shift" + | "Alt" + | "Command" + | "Ctrl" + | "MacCtrl"; /* contextMenus properties */ /** @@ -5169,31 +5102,29 @@ declare namespace browser.menus { * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other * contexts except for 'tab' and 'tools_menu'. */ - enum ContextType { - all = "all", - page = "page", - frame = "frame", - selection = "selection", - link = "link", - editable = "editable", - password = "password", - image = "image", - video = "video", - audio = "audio", - launcher = "launcher", - browser_action = "browser_action", - page_action = "page_action", - tab = "tab", - tools_menu = "tools_menu" - } + type ContextType = + "all" + | "page" + | "frame" + | "selection" + | "link" + | "editable" + | "password" + | "image" + | "video" + | "audio" + | "launcher" + | "browser_action" + | "page_action" + | "tab" + | "tools_menu"; /** The type of menu item. */ - enum ItemType { - normal = "normal", - checkbox = "checkbox", - radio = "radio", - separator = "separator" - } + type ItemType = + "normal" + | "checkbox" + | "radio" + | "separator"; /** Information sent when a context menu item is clicked. */ interface OnClickData { @@ -5230,13 +5161,12 @@ declare namespace browser.menus { modifiers: _OnClickDataModifiers[]; } - enum _OnClickDataModifiers { - Shift = "Shift", - Alt = "Alt", - Command = "Command", - Ctrl = "Ctrl", - MacCtrl = "MacCtrl" - } + type _OnClickDataModifiers = + "Shift" + | "Alt" + | "Command" + | "Ctrl" + | "MacCtrl"; /* menus properties */ /** @@ -5399,22 +5329,20 @@ declare namespace browser.omnibox { /* omnibox types */ /** The style type. */ - enum DescriptionStyleType { - url = "url", - match = "match", - dim = "dim" - } + type DescriptionStyleType = + "url" + | "match" + | "dim"; /** * The window disposition for the omnibox query. This is the recommended context to display results. For example, * if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation * should take place in a new selected tab. */ - enum OnInputEnteredDisposition { - currentTab = "currentTab", - newForegroundTab = "newForegroundTab", - newBackgroundTab = "newBackgroundTab" - } + type OnInputEnteredDisposition = + "currentTab" + | "newForegroundTab" + | "newBackgroundTab"; /** A suggest result. */ interface SuggestResult { @@ -5843,14 +5771,13 @@ declare namespace browser.tabs { /* tabs types */ /** An event that caused a muted state change. */ - enum MutedInfoReason { + type MutedInfoReason = /** A user input action has set/overridden the muted state. */ - user = "user", - /** Tab capture started, forcing a muted state change. */ - capture = "capture", - /** An extension, identified by the extensionId field, set the muted state. */ - extension = "extension" - } + "user" +/** Tab capture started, forcing a muted state change. */ + | "capture" +/** An extension, identified by the extensionId field, set the muted state. */ + | "extension"; /** Tab muted state and the reason for the last state change. */ interface MutedInfo { @@ -5942,41 +5869,39 @@ declare namespace browser.tabs { * Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; * defaults to `automatic`. */ - enum ZoomSettingsMode { + type ZoomSettingsMode = /** Zoom changes are handled automatically by the browser. */ - automatic = "automatic", + "automatic" /** * Overrides the automatic handling of zoom changes. The `onZoomChange` event will still be dispatched, and it * is the responsibility of the extension to listen for this event and manually scale the page. This mode does * not support `per-origin` zooming, and will thus ignore the `scope` zoom setting and assume `per-tab`. */ - manual = "manual", + | "manual" /** * Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom * changes will be ignored. */ - disabled = "disabled" - } + | "disabled"; /** * Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to * `per-origin` when in `automatic` mode, and `per-tab` otherwise. */ - enum ZoomSettingsScope { + type ZoomSettingsScope = /** * Zoom changes will persist in the zoomed page's origin, i.e. all other tabs navigated to that same origin * will be zoomed as well. Moreover, `per-origin` zoom changes are saved with the origin, meaning that when * navigating to other pages in the same origin, they will all be zoomed to the same zoom factor. The * `per-origin` scope is only available in the `automatic` mode. */ - perorigin = "per-origin", + | "per-origin" /** * Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of * this tab. Also, `per-tab` zoom changes are reset on navigation; navigating a tab will always load pages with * their `per-origin` zoom factors. */ - pertab = "per-tab" - } + | "per-tab"; /** Defines how zoom changes in a tab are handled and at what scope. */ interface ZoomSettings { @@ -6035,19 +5960,17 @@ declare namespace browser.tabs { } /** Whether the tabs have completed loading. */ - enum TabStatus { - loading = "loading", - complete = "complete" - } + type TabStatus = + "loading" + | "complete"; /** The type of window. */ - enum WindowType { - normal = "normal", - popup = "popup", - panel = "panel", - app = "app", - devtools = "devtools" - } + type WindowType = + "normal" + | "popup" + | "panel" + | "app" + | "devtools"; /* tabs properties */ /** An ID which represents the absence of a browser tab. */ @@ -6549,25 +6472,18 @@ declare namespace browser.windows { * The type of browser window this is. Under some circumstances a Window may not be assigned type property, for * example when querying closed windows from the `sessions` API. */ - enum WindowType { - normal = "normal", - popup = "popup", - panel = "panel", - app = "app", - devtools = "devtools" - } + type WindowType = "normal" | "popup" | "panel" | "app" | "devtools"; /** * The state of this browser window. Under some circumstances a Window may not be assigned state property, for * example when querying closed windows from the `sessions` API. */ - enum WindowState { - normal = "normal", - minimized = "minimized", - maximized = "maximized", - fullscreen = "fullscreen", - docked = "docked" - } + type WindowState = + "normal" + | "minimized" + | "maximized" + | "fullscreen" + | "docked"; interface Window { /** @@ -6618,12 +6534,7 @@ declare namespace browser.windows { * Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless * the '--enable-panels' flag is set. */ - enum CreateType { - normal = "normal", - popup = "popup", - panel = "panel", - detached_panel = "detached_panel" - } + type CreateType = "normal" | "popup" | "panel" | "detached_panel"; /* windows properties */ /** The windowId value that represents the absence of a browser window. */ diff --git a/types/ftpd/index.d.ts b/types/ftpd/index.d.ts index cd325109ee..e919e4b48a 100644 --- a/types/ftpd/index.d.ts +++ b/types/ftpd/index.d.ts @@ -130,20 +130,20 @@ export declare class FtpConnection extends events.EventEmitter { */ export interface FtpFileSystem { unlink: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; - readdir: (path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void) => void; + readdir: (path: string, callback?: (err?: NodeJS.ErrnoException, files?: string[]) => void) => void; mkdir: ((path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void) | ((path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void) => void) | ((path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void) => void); - open: ((path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) - | ((path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) - | ((path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void); + open: ((path: string, flags: string, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void) + | ((path: string, flags: string, mode: number, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void) + | ((path: string, flags: string, mode: string, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void); close: (fd: number, callback?: (err?: NodeJS.ErrnoException) => void) => void; rmdir: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; rename: (oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; /** * specific object properties: { mode, isDirectory(), size, mtime } */ - stat: (path: string, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any) => void; + stat: (path: string, callback?: (err?: NodeJS.ErrnoException, stats?: fs.Stats) => any) => void; /** * if useReadFile option is not set or is false */ diff --git a/types/google-translate-api/google-translate-api-tests.ts b/types/google-translate-api/google-translate-api-tests.ts new file mode 100644 index 0000000000..25149c2660 --- /dev/null +++ b/types/google-translate-api/google-translate-api-tests.ts @@ -0,0 +1,3 @@ +import translate = require('google-translate-api'); + +translate('hello', { from: 'en', to: 'zh-tw' }); // $ExpectType Promise diff --git a/types/google-translate-api/index.d.ts b/types/google-translate-api/index.d.ts new file mode 100644 index 0000000000..1a53eacc4d --- /dev/null +++ b/types/google-translate-api/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for google-translate-api 2.3 +// Project: https://github.com/matheuss/google-translate-api#readme +// Definitions by: maple3142 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface TranslateOption { + from?: string; + to?: string; + raw?: boolean; +} +interface TranslateResult { + text: string; + from: { + language: { + didYouMean: boolean; + iso: string; + } + text: { + autoCorrected: boolean; + value: string; + didYouMean: boolean; + } + }; + raw: string; +} +declare function translate(text: string, options?: TranslateOption): Promise; +export = translate; diff --git a/types/google-translate-api/tsconfig.json b/types/google-translate-api/tsconfig.json new file mode 100644 index 0000000000..21eb234d62 --- /dev/null +++ b/types/google-translate-api/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "google-translate-api-tests.ts"] +} diff --git a/types/google-translate-api/tslint.json b/types/google-translate-api/tslint.json new file mode 100644 index 0000000000..381c23f5c5 --- /dev/null +++ b/types/google-translate-api/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "semicolon": true + } +} diff --git a/types/hammerjs/index.d.ts b/types/hammerjs/index.d.ts index 587a3c89a0..d1bb8ffd85 100644 --- a/types/hammerjs/index.d.ts +++ b/types/hammerjs/index.d.ts @@ -263,19 +263,15 @@ interface Recognizer canEmit():boolean; canRecognizeWith( otherRecognizer:Recognizer ):boolean; - dropRecognizeWith( otherRecognizer:Recognizer ):Recognizer; - dropRecognizeWith( otherRecognizer:string ):Recognizer; - dropRequireFailure( otherRecognizer:Recognizer ):Recognizer; - dropRequireFailure( otherRecognizer:string ):Recognizer; + dropRecognizeWith( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; + dropRequireFailure( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; emit( input:HammerInput ):void; getTouchAction():any[]; hasRequireFailures():boolean; process( inputData:HammerInput ):string; recognize( inputData:HammerInput ):void; - recognizeWith( otherRecognizer:Recognizer ):Recognizer; - recognizeWith( otherRecognizer:string ):Recognizer; - requireFailure( otherRecognizer:Recognizer ):Recognizer; - requireFailure( otherRecognizer:string ):Recognizer; + recognizeWith( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; + requireFailure( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; reset():void; set( options?:RecognizerOptions ):Recognizer; tryEmit( input:HammerInput ):void; diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index b400af2497..329bf438b2 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -156,7 +156,6 @@ declare namespace Knex { // Others first: Select; - debug(enabled?: boolean): QueryBuilder; pluck(column: string): QueryBuilder; insert(data: any, returning?: string | string[]): QueryBuilder; @@ -169,9 +168,6 @@ declare namespace Knex { delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - transacting(trx?: Transaction): QueryBuilder; - connection(connection: any): QueryBuilder; - clone(): QueryBuilder; } @@ -390,12 +386,14 @@ declare namespace Knex { interface ChainableInterface extends Bluebird { toQuery(): string; - options(options: any): QueryBuilder; - stream(callback: (readable: stream.PassThrough) => any): Bluebird; + options(options: { [key: string]: any }): this; + connection(connection: any): this; + debug(enabled: boolean): this; + transacting(trx: Transaction): this; + stream(handler: (readable: stream.PassThrough) => any): Bluebird; + stream(options: { [key: string]: any }, handler: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; - stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird; - pipe(writable: any): stream.PassThrough; - exec(callback: Function): QueryBuilder; + pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; } interface Transaction extends Knex { @@ -408,7 +406,7 @@ declare namespace Knex { // Schema builder // - interface SchemaBuilder extends Bluebird { + interface SchemaBuilder extends ChainableInterface { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; alterTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index e7fb3e1b81..461e1738fe 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -982,19 +982,11 @@ knex.select('name').from('users') .where('id', '>', 20) .andWhere('id', '<', 200) .limit(10) - .offset(x) - .exec(function(err: any, rows: any[]) { - if (err) return console.error(err); - knex.select('id').from('nicknames').whereIn('nickname', rows.map((r: any) => r.name)) - .exec(function(err: any, rows: any[]) { - if (err) return console.error(err); - console.log(rows); - }); - }); + .offset(x); // Retrieve the stream: var stream = knex.select('*').from('users').stream(); -var writableStream: any; +var writableStream: NodeJS.WritableStream; stream.pipe(writableStream); // With options: diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 215d38e7f1..4e2f3b1519 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -5,7 +5,8 @@ // Clément Bourgeois , // Matt Brooks , // Benjamin Eckardt , -// Mathias Lorenzen +// Mathias Lorenzen , +// Leonardo Lombardi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -22,29 +23,108 @@ interface KnockoutObservableFunctions { interface KnockoutObservableArrayFunctions { // General Array functions + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ slice(start: number, end?: number): T[]; + /** + * Removes and returns all the remaining elements starting from a given index. + * @param start The zero-based location in the array from which to start removing elements. + */ splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param ...items Elements to insert into the array in place of the deleted elements. + */ splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Removes the last value from the array and returns it. + */ pop(): T; + /** + * Adds a new item to the end of array. + * @param ...items Items to be added + */ push(...items: T[]): void; + /** + * Removes the first value from the array and returns it. + */ shift(): T; + /** + * Inserts a new item at the beginning of the array. + * @param ...items Items to be added + */ unshift(...items: T[]): number; + /** + * Reverses the order of the array and returns the observableArray (not the underlying array). + */ reverse(): KnockoutObservableArray; + /** + * Sorts the array contents and returns the observableArray. + */ sort(): KnockoutObservableArray; + /** + * Sorts the array contents and returns the observableArray. + * @param compareFunction A function that returns negative value if first argument is smaller, positive value if second is smaller, or zero to treat them as equal. + */ sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray; // Ko specific + /** + * Replaces the first value that equals oldItem with newItem + * @param oldItem Item to be replaced + * @param newItem Replacing item + */ replace(oldItem: T, newItem: T): void; - + /** + * Removes all values that equal item and returns them as an array. + * @param item The item to be removed + */ remove(item: T): T[]; + /** + * Removes all values and returns them as an array. + * @param removeFunction A function used to determine true if item should be removed and fasle otherwise + */ remove(removeFunction: (item: T) => boolean): T[]; + /** + * Removes all values that equal any of the supplied items + * @param items Items to be removed + */ removeAll(items: T[]): T[]; + /** + * Removes all values and returns them as an array. + */ removeAll(): T[]; + // Ko specific Usually relevant to Ruby on Rails developers only + /** + * Finds any objects in the array that equal someItem and gives them a special property called _destroy with value true. + * @param item Items to be marked with the property. + */ destroy(item: T): void; + /** + * Finds any objects in the array filtered by a function and gives them a special property called _destroy with value true. + * @param destroyFunction A function used to determine which items should be marked with the property. + */ destroy(destroyFunction: (item: T) => boolean): void; + /** + * Finds any objects in the array that equal suplied items and gives them a special property called _destroy with value true. + * @param items + */ destroyAll(items: T[]): void; + /** + * Gives a special property called _destroy with value true to all objects in the array. + */ destroyAll(): void; } @@ -116,16 +196,16 @@ interface KnockoutObservable extends KnockoutSubscribable, KnockoutObserva (value: T): void; peek(): T; - valueHasMutated?:{(): void;}; - valueWillMutate?:{(): void;}; + valueHasMutated?: { (): void; }; + valueWillMutate?: { (): void; }; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable; } interface KnockoutComputedDefine { read(): T; - write? (value: T): void; + write?(value: T): void; disposeWhenNodeIsRemoved?: Node; - disposeWhen? (): boolean; + disposeWhen?(): boolean; owner?: any; deferEvaluation?: boolean; pure?: boolean; @@ -206,17 +286,17 @@ interface KnockoutMemoization { parseMemoText(memoText: string): string; } -interface KnockoutVirtualElement {} +interface KnockoutVirtualElement { } interface KnockoutVirtualElements { allowedBindings: { [bindingName: string]: boolean; }; - emptyNode(node: KnockoutVirtualElement ): void; - firstChild(node: KnockoutVirtualElement ): KnockoutVirtualElement; - insertAfter( container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node ): void; + emptyNode(node: KnockoutVirtualElement): void; + firstChild(node: KnockoutVirtualElement): KnockoutVirtualElement; + insertAfter(container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node): void; nextSibling(node: KnockoutVirtualElement): Node; - prepend(node: KnockoutVirtualElement, toInsert: Node ): void; - setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; } ): void; - childNodes(node: KnockoutVirtualElement ): Node[]; + prepend(node: KnockoutVirtualElement, toInsert: Node): void; + setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; }): void; + childNodes(node: KnockoutVirtualElement): Node[]; } interface KnockoutExtenders { @@ -365,12 +445,12 @@ interface KnockoutTemplateSources { domElement: { prototype: KnockoutTemplateSourcesDomElement - new (element: Element): KnockoutTemplateSourcesDomElement + new(element: Element): KnockoutTemplateSourcesDomElement }; anonymousTemplate: { prototype: KnockoutTemplateAnonymous; - new (element: Element): KnockoutTemplateAnonymous; + new(element: Element): KnockoutTemplateAnonymous; }; } @@ -478,7 +558,7 @@ interface KnockoutStatic { prototype: KnockoutTemplateEngine; - new (): KnockoutTemplateEngine; + new(): KnockoutTemplateEngine; }; ////////////////////////////////// @@ -503,7 +583,7 @@ interface KnockoutStatic { prototype: KnockoutNativeTemplateEngine; - new (): KnockoutNativeTemplateEngine; + new(): KnockoutNativeTemplateEngine; instance: KnockoutNativeTemplateEngine; }; @@ -572,7 +652,7 @@ interface KnockoutStatic { bindingProvider: { instance: KnockoutBindingProvider; - new (): KnockoutBindingProvider; + new(): KnockoutBindingProvider; } ///////////////////////////////// @@ -631,7 +711,7 @@ declare namespace KnockoutComponentTypes { interface Config { viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; - template: string | Node[]| DocumentFragment | TemplateElement | AMDModule; + template: string | Node[] | DocumentFragment | TemplateElement | AMDModule; synchronous?: boolean; } @@ -672,16 +752,16 @@ declare namespace KnockoutComponentTypes { } interface Loader { - getConfig? (componentName: string, callback: (result: ComponentConfig | null) => void): void; - loadComponent? (componentName: string, config: ComponentConfig, callback: (result: Definition | null) => void): void; - loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[] | null) => void): void; - loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void; + getConfig?(componentName: string, callback: (result: ComponentConfig | null) => void): void; + loadComponent?(componentName: string, config: ComponentConfig, callback: (result: Definition | null) => void): void; + loadTemplate?(componentName: string, templateConfig: any, callback: (result: Node[] | null) => void): void; + loadViewModel?(componentName: string, viewModelConfig: any, callback: (result: any) => void): void; suppressLoaderExceptions?: boolean; } interface Definition { template: Node[]; - createViewModel? (params: any, options: { element: Node; }): any; + createViewModel?(params: any, options: { element: Node; }): any; } } diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index 4305c662a8..a29a6adeda 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -33,6 +33,7 @@ export class Document { constructor(version?: number, encoding?: string); errors: SyntaxError[]; + validationErrors: ValidationError[]; child(idx: number): Element|null; childNodes(): Element[]; @@ -45,6 +46,7 @@ export class Document { root(newRoot: Node): Node; toString(formatted?: boolean): string; type(): 'document'; + validate(xsdDoc: Document): boolean; version(): string; setDtd(name: string, ext: string, sys: string): void; getDtd(): { @@ -169,3 +171,15 @@ export interface SyntaxError { str3: number|null; int1: number|null; } + +export interface ValidationError extends Error { + domain: number|null; + code: number|null; + level: number|null; + + line: number|null; + /** + * 1-based column number, 0 if not applicable/available. + */ + column: number; +} diff --git a/types/libxmljs/libxmljs-tests.ts b/types/libxmljs/libxmljs-tests.ts index fe720cc242..3975257307 100644 --- a/types/libxmljs/libxmljs-tests.ts +++ b/types/libxmljs/libxmljs-tests.ts @@ -62,3 +62,7 @@ const xmlDocWithNs = libxmljs.parseXml(xmlWithNs); const gchildWithNs = xmlDocWithNs.get('//a:grandchild', {a: 'http://test.com/test'})!; console.log(gchildWithNs.text()); // prints "grandchild content" + +const validated: boolean = doc.validate(doc); +doc.validationErrors[0].message; // inherited from Error +doc.validationErrors[0].line; diff --git a/types/mali-onerror/index.d.ts b/types/mali-onerror/index.d.ts new file mode 100644 index 0000000000..c9600d50f0 --- /dev/null +++ b/types/mali-onerror/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for mali-onerror 0.1 +// Project: https://github.com/malijs/onerror +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { Context } from "mali"; + +declare function onError( + fn: (err: Error, ctx: Context) => void +): (ctx: Context, next: () => Promise) => Promise; // ? next (I know it s a function) + +export = onError; diff --git a/types/mali-onerror/mali-onerror-tests.ts b/types/mali-onerror/mali-onerror-tests.ts new file mode 100644 index 0000000000..19c8a5ab55 --- /dev/null +++ b/types/mali-onerror/mali-onerror-tests.ts @@ -0,0 +1,13 @@ +import onError = require('mali-onerror'); +import Mali = require('mali'); +import path = require('path'); + +// Example mali app from Mali docs +const PROTO_PATH = path.resolve(__dirname, '../protos/helloworld.proto'); + +function errorLogger(err: Error, ctx: Mali.Context) { + console.log('Error on %s: %s', ctx.name, err.toString()); +} + +const app = new Mali(PROTO_PATH); +app.use(onError(errorLogger)); diff --git a/types/mali-onerror/tsconfig.json b/types/mali-onerror/tsconfig.json new file mode 100644 index 0000000000..a47d002aab --- /dev/null +++ b/types/mali-onerror/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mali-onerror-tests.ts" + ] +} diff --git a/types/mali-onerror/tslint.json b/types/mali-onerror/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/mali-onerror/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/meteor/index.d.ts b/types/meteor/index.d.ts index 0822bab8e7..dfa14ebc59 100644 --- a/types/meteor/index.d.ts +++ b/types/meteor/index.d.ts @@ -8,6 +8,7 @@ // Arda TANRIKULU // Stefan Holzapfel // Andrey Markeev +// Leon Machens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/meteor/server-render.d.ts b/types/meteor/server-render.d.ts index 0f78cac1c0..9c30def0f8 100644 --- a/types/meteor/server-render.d.ts +++ b/types/meteor/server-render.d.ts @@ -11,6 +11,7 @@ declare module "meteor/server-render" { appendToBody?(html: string): void; appendToElementById?(id: string, html: string): void; renderIntoElementById?(id: string, html: string): void; + renderIntoElementById?(id: string, html: NodeJS.ReadableStream): void; } type Callback = (sink: Sink) => Promise | any; diff --git a/types/meteor/test/meteor-tests-module-only.ts b/types/meteor/test/meteor-tests-module-only.ts index 3591b90635..716d0a7e74 100644 --- a/types/meteor/test/meteor-tests-module-only.ts +++ b/types/meteor/test/meteor-tests-module-only.ts @@ -1,7 +1,6 @@ // This file is for tests that involve modules that don't have corresponding // globals. -import { onPageLoad } from "meteor/server-render"; import { ServiceConfiguration } from "meteor/service-configuration"; import { WebApp } from "meteor/webapp"; diff --git a/types/meteor/test/server-render.tsx b/types/meteor/test/server-render.tsx new file mode 100644 index 0000000000..f6adb72f32 --- /dev/null +++ b/types/meteor/test/server-render.tsx @@ -0,0 +1,15 @@ +import { onPageLoad } from "meteor/server-render"; +import * as React from 'react'; +import { renderToString, renderToNodeStream } from 'react-dom/server'; + +onPageLoad(sink => { + if (sink.renderIntoElementById) { + sink.renderIntoElementById("app", renderToString(

Hello World
)); + } +}); + +onPageLoad(sink => { + if (sink.renderIntoElementById) { + sink.renderIntoElementById("app", renderToNodeStream(
Hello World
)); + } +}); \ No newline at end of file diff --git a/types/meteor/tsconfig.json b/types/meteor/tsconfig.json index 7ad451fd56..ed6a9e0e77 100644 --- a/types/meteor/tsconfig.json +++ b/types/meteor/tsconfig.json @@ -15,7 +15,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" }, "files": [ "accounts-base.d.ts", @@ -61,6 +62,7 @@ "index.d.ts", "test/meteor-tests.ts", "test/globals/meteor-tests.ts", - "test/meteor-tests-module-only.ts" + "test/meteor-tests-module-only.ts", + "test/server-render.tsx" ] } diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index 1d05b96f36..0f2d68cb57 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -58,7 +58,7 @@ declare module "moment" { interface Moment { tz(): string | undefined; - tz(timezone: string, keepLocalTime?: boolean): Moment; + tz(timezone: string, keepLocalTime?: boolean): moment.Moment; zoneAbbr(): string; zoneName(): string; } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 5791b906f1..3cbc3af64a 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -14,6 +14,7 @@ // Wan Bachtiar // Geraldine Lemeur // Jimmy Shimizu +// Angela-1 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -208,6 +209,10 @@ export interface SocketOptions { keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; + // Version of IP stack. Can be 4, 6 or null. default: null. + // If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + // refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + family?: 4 | 6 | null; // TCP Socket timeout setting. default 0 socketTimeoutMS?: number; } @@ -896,7 +901,7 @@ export interface CollectionAggregationOptions { readPreference?: ReadPreference | string; // Return the query as cursor, on 2.6 > it returns as a real cursor // on pre 2.6 it returns as an emulated cursor. - cursor?: { batchSize: number }; + cursor?: { batchSize?: number }; // Explain returns the aggregation execution plan (requires mongodb 2.6 >). explain?: boolean; // lets the server know if it can use disk to store diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index 5ffaf6818f..e1f8a767fa 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -17,6 +17,7 @@ let options: mongodb.MongoClientOptions = { poolSize: 1, socketOptions: {}, + family: 4, reconnectTries: 123456, reconnectInterval: 123456, diff --git a/types/nodemailer/lib/addressparser.d.ts b/types/nodemailer/lib/addressparser.d.ts index be42c1deed..a687a21560 100644 --- a/types/nodemailer/lib/addressparser.d.ts +++ b/types/nodemailer/lib/addressparser.d.ts @@ -16,7 +16,6 @@ declare namespace addressparser { * * [{name: 'Name', address: 'address@domain'}] * - * @param str Address field * @return An array of address objects */ declare function addressparser(address: string): addressparser.Address[]; diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index 1215409b46..fefce90819 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'events'; import * as net from 'net'; -import { Writable } from 'stream'; +import { Readable } from 'stream'; import * as tls from 'tls'; import * as shared from './shared'; @@ -181,7 +181,7 @@ declare class SMTPConnection extends EventEmitter { /** Authenticate user */ login(auth: SMTPConnection.AuthenticationCredentials | SMTPConnection.AuthenticationOAuth2 | SMTPConnection.Credentials, callback: (err: SMTPConnection.SMTPError | null) => void): void; /** Sends a message */ - send(envelope: SMTPConnection.Envelope, message: string | Buffer | Writable, callback: (err: SMTPConnection.SMTPError | null, info: SMTPConnection.SentMessageInfo) => void): void; + send(envelope: SMTPConnection.Envelope, message: string | Buffer | Readable, callback: (err: SMTPConnection.SMTPError | null, info: SMTPConnection.SentMessageInfo) => void): void; /** Resets connection state */ reset(callback: (err: Error | null) => void): void; @@ -191,6 +191,14 @@ declare class SMTPConnection extends EventEmitter { emit(event: 'connect' | 'end'): boolean; emit(event: 'error', error: Error): boolean; + listenerCount(event: 'connect' | 'end' | 'error'): number; + + listeners(event: 'connect' | 'end'): Array<() => void>; + listeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + + off(event: 'connect' | 'end', listener: () => void): this; + off(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; + on(event: 'connect' | 'end', listener: () => void): this; on(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; @@ -203,8 +211,13 @@ declare class SMTPConnection extends EventEmitter { prependOnceListener(event: 'connect' | 'end', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; - listeners(event: 'connect' | 'end'): Array<() => void>; - listeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + rawListeners(event: 'connect' | 'end'): Array<() => void>; + rawListeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + + removeAllListener(event: 'connect' | 'end' | 'error'): this; + + removeListener(event: 'connect' | 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; } export = SMTPConnection; diff --git a/types/passport-kakao/index.d.ts b/types/passport-kakao/index.d.ts index b005b45d98..dbb4c2f07b 100644 --- a/types/passport-kakao/index.d.ts +++ b/types/passport-kakao/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for passport-kakao 0.1 +// Type definitions for passport-kakao 0.2 // Project: https://github.com/rotoshine/passport-kakao // Definitions by: Park9eon +// ZeroCho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -24,11 +25,18 @@ export interface StrategyOption { customHeaders?: string; } +export interface StrategyOptionWithRequest extends StrategyOption { + passReqToCallback: boolean; +} + export type VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export type VerifyFunctionWithRequest = + (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; export class Strategy extends passport.Strategy { constructor(options: StrategyOption, verify: VerifyFunction); + constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest); authenticate(req: express.Request, options?: any): void; userProfile: (accessToken: string, done: (error: any, user?: any) => void) => void; diff --git a/types/passport-kakao/passport-kakao-tests.ts b/types/passport-kakao/passport-kakao-tests.ts index 595404cc5b..5f104f6c41 100644 --- a/types/passport-kakao/passport-kakao-tests.ts +++ b/types/passport-kakao/passport-kakao-tests.ts @@ -1,10 +1,11 @@ -import {Strategy as KakaoStrategy } from 'passport-kakao'; +import { Strategy as KakaoStrategy } from 'passport-kakao'; new KakaoStrategy({ clientID: 'client', clientSecret: 'clientSecret', - callbackURL: 'callbackUrl' + callbackURL: 'callbackUrl', }, (accessToken: string, refreshToken: string, profile: any, done: any) => { // signUp or signIn - }); + }, +); diff --git a/types/passport-naver/index.d.ts b/types/passport-naver/index.d.ts index 8bd022cd21..1366a4b791 100644 --- a/types/passport-naver/index.d.ts +++ b/types/passport-naver/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for passport-naver 0.1 +// Type definitions for passport-naver 0.2 // Project: https://github.com/naver/passport-naver // Definitions by: Park9eon +// ZeroCho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -34,11 +35,16 @@ export interface StrategyOption { profileURL?: string; } -export type VerifyFunction = - (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export interface StrategyOptionWithRequest extends StrategyOption { + passReqToCallback: boolean; +} + +export type VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; export class Strategy extends passport.Strategy { constructor(options: StrategyOption, verify: VerifyFunction); + constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest); authenticate(req: express.Request, options?: any): void; authorizationParams: (options: any) => any; diff --git a/types/passport-naver/passport-naver-tests.ts b/types/passport-naver/passport-naver-tests.ts index 72e76d32e7..d2bfe26fc6 100644 --- a/types/passport-naver/passport-naver-tests.ts +++ b/types/passport-naver/passport-naver-tests.ts @@ -1,10 +1,11 @@ -import {Strategy as NaverStrategy } from 'passport-naver'; +import { Strategy as NaverStrategy } from 'passport-naver'; new NaverStrategy({ clientID: 'client', clientSecret: 'clientSecret', - callbackURL: 'callbackUrl' + callbackURL: 'callbackUrl', }, (accessToken: string, refreshToken: string, profile: any, done: any) => { // signUp or signIn - }); + }, +); diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 0eda9a4eff..d1fd85f4ba 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -186,7 +186,8 @@ export class Quill implements EventEmitter { blur(): void; focus(): void; getBounds(index: number, length?: number): BoundsStatic; - getSelection(focus?: boolean): RangeStatic; + getSelection(focus: true): RangeStatic; + getSelection(focus?: false): RangeStatic | null; hasFocus(): boolean; setSelection(index: number, length: number, source?: Sources): void; setSelection(range: RangeStatic, source?: Sources): void; diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 60db9a20f9..b4d23c1e49 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -4,6 +4,7 @@ // Austin Turner // Krzysztof Bezrąk // Sebastian Silbermann +// Paul Potsides // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -14,76 +15,85 @@ export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; export type Navigate = 'PREV' | 'NEXT' | 'TODAY' | 'DATE'; export type Event = object; -export interface Format { +export interface DateRange { + start: Date; + end: Date; +} + +export type DateFormatFunction = (date: Date, culture?: string, localizer?: object) => string; +export type DateRangeFormatFunction = (range: DateRange, culture?: string, localizer?: object) => string; +export type DateFormat = string | DateFormatFunction; + +export interface Formats { /** * Format for the day of the month heading in the Month view. * e.g. "01", "02", "03", etc */ - dateFormat?: string; + dateFormat?: DateFormat; /** * A day of the week format for Week and Day headings, * e.g. "Wed 01/04" * */ - dayFormat?: string; + dayFormat?: DateFormat; /** * Week day name format for the Month week day headings, * e.g: "Sun", "Mon", "Tue", etc * */ - weekdayFormat?: string; + weekdayFormat?: DateFormat; /** * The timestamp cell formats in Week and Time views, e.g. "4:00 AM" */ - timeGutterFormat?: string; + timeGutterFormat?: DateFormat; /** * Toolbar header format for the Month view, e.g "2015 April" * */ - monthHeaderFormat?: string; + monthHeaderFormat?: DateFormat; /** * Toolbar header format for the Week views, e.g. "Mar 29 - Apr 04" */ - dayRangeHeaderFormat?: string; + dayRangeHeaderFormat?: DateRangeFormatFunction; /** * Toolbar header format for the Day view, e.g. "Wednesday Apr 01" */ - dayHeaderFormat?: string; + dayHeaderFormat?: DateFormat; /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ - agendaHeaderFormat?: string; + agendaHeaderFormat?: DateFormat; /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" */ - selectRangeFormat?: string; + selectRangeFormat?: DateRangeFormatFunction; - agendaDateFormat?: string; - agendaTimeFormat?: string; - agendaTimeRangeFormat?: string; + agendaDateFormat?: DateFormat; + agendaTimeFormat?: DateFormat; + agendaTimeRangeFormat?: DateRangeFormatFunction; /** * Time range displayed on events. */ - eventTimeRangeFormat?: string; + eventTimeRangeFormat?: DateRangeFormatFunction; /** * An optional event time range for events that continue onto another day */ - eventTimeRangeStartFormat?: string; + eventTimeRangeStartFormat?: DateRangeFormatFunction; /** * An optional event time range for events that continue from another day */ - eventTimeRangeEndFormat?: string; + eventTimeRangeEndFormat?: DateRangeFormatFunction; } export interface HeaderProps { @@ -179,7 +189,7 @@ export interface BigCalendarProps extends React.Props string); diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index fe0ba7fe7c..3f2ec34c39 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; import * as ReactDOMServer from "react-dom/server"; -import BigCalendar, { BigCalendarProps, Navigate, View } from "react-big-calendar"; +import BigCalendar, { BigCalendarProps, Navigate, View, DateRange } from "react-big-calendar"; // Don't want to add this as a dependency, because it is only used for tests. declare const moment: any; @@ -81,7 +81,11 @@ class FullAPIExample extends React.Component> { min={new Date()} max={new Date()} scrollToTime={new Date()} - formats={{}} + formats={{ + dateFormat: "h a", + agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", + dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" + }} messages={{}} timeslots={24} defaultView={'month'} diff --git a/types/react-currency-formatter/index.d.ts b/types/react-currency-formatter/index.d.ts new file mode 100644 index 0000000000..d0f8e217ad --- /dev/null +++ b/types/react-currency-formatter/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for react-currency-formatter 1.1 +// Project: https://github.com/xDae/react-currency-formatter; +// Definitions by: Yury Pastushenko +// Evgeniy Vasiliev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface CurrencyFormatterProps { + quantity: number; + currency?: string; + locale?: string; + pattern?: string; + decimal?: string; + group?: string; +} + +declare const reactCurrencyFormatter: React.ComponentClass; +export = reactCurrencyFormatter; diff --git a/types/react-currency-formatter/react-currency-formatter-tests.tsx b/types/react-currency-formatter/react-currency-formatter-tests.tsx new file mode 100644 index 0000000000..06cc4ec9a2 --- /dev/null +++ b/types/react-currency-formatter/react-currency-formatter-tests.tsx @@ -0,0 +1,13 @@ +import * as React from 'react'; +import * as CurrencyFormatter from 'react-currency-formatter'; + +interface Props { + price: number; + currency: string; +} + +const ProductionPrice: React.SFC = (props: Props) => ( + +); + +export default ProductionPrice; diff --git a/types/react-currency-formatter/tsconfig.json b/types/react-currency-formatter/tsconfig.json new file mode 100644 index 0000000000..2dee5017b3 --- /dev/null +++ b/types/react-currency-formatter/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-currency-formatter-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-currency-formatter/tslint.json b/types/react-currency-formatter/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-currency-formatter/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-hammerjs/index.d.ts b/types/react-hammerjs/index.d.ts index e3bb4a826c..03f3f36f98 100644 --- a/types/react-hammerjs/index.d.ts +++ b/types/react-hammerjs/index.d.ts @@ -1,21 +1,30 @@ -// Type definitions for react-hammerjs 0.5 +// Type definitions for react-hammerjs 1.0 // Project: https://github.com/JedWatson/react-hammerjs#readme // Definitions by: Jason Unger +// Cecchi MacNaughton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as Hammer from 'hammerjs'; -import * as React from 'react'; +import * as Hammer from "hammerjs"; +import * as React from "react"; type Omit = Pick>; -type HammerOptionsWithRecognizers = Omit & { +type HammerOptionsWithRecognizers = Omit & { recognizers?: { [gesture: string]: RecognizerOptions }; }; declare namespace ReactHammer { interface ReactHammerProps { - direction?: number; + direction?: + | "DIRECTION_NONE" + | "DIRECTION_LEFT" + | "DIRECTION_RIGHT" + | "DIRECTION_UP" + | "DIRECTION_DOWN" + | "DIRECTION_HORIZONTAL" + | "DIRECTION_VERTICAL" + | "DIRECTION_ALL"; options?: HammerOptionsWithRecognizers; recognizeWith?: { [gesture: string]: Recognizer | string }; vertical?: boolean; diff --git a/types/react-hammerjs/v0/index.d.ts b/types/react-hammerjs/v0/index.d.ts new file mode 100644 index 0000000000..e3bb4a826c --- /dev/null +++ b/types/react-hammerjs/v0/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for react-hammerjs 0.5 +// Project: https://github.com/JedWatson/react-hammerjs#readme +// Definitions by: Jason Unger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as Hammer from 'hammerjs'; +import * as React from 'react'; + +type Omit = Pick>; + +type HammerOptionsWithRecognizers = Omit & { + recognizers?: { [gesture: string]: RecognizerOptions }; +}; + +declare namespace ReactHammer { + interface ReactHammerProps { + direction?: number; + options?: HammerOptionsWithRecognizers; + recognizeWith?: { [gesture: string]: Recognizer | string }; + vertical?: boolean; + action?: HammerListener; + onDoubleTap?: HammerListener; + onPan?: HammerListener; + onPanCancel?: HammerListener; + onPanEnd?: HammerListener; + onPanStart?: HammerListener; + onPinch?: HammerListener; + onPinchCancel?: HammerListener; + onPinchEnd?: HammerListener; + onPinchIn?: HammerListener; + onPinchStart?: HammerListener; + onPress?: HammerListener; + onPressUp?: HammerListener; + onRotate?: HammerListener; + onRotateCancel?: HammerListener; + onRotateEnd?: HammerListener; + onRotateMove?: HammerListener; + onRotateStart?: HammerListener; + onSwipe?: HammerListener; + onTap?: HammerListener; + } +} +declare const ReactHammer: React.ComponentClass; +export = ReactHammer; diff --git a/types/react-hammerjs/v0/react-hammerjs-tests.tsx b/types/react-hammerjs/v0/react-hammerjs-tests.tsx new file mode 100644 index 0000000000..7743cf3a4b --- /dev/null +++ b/types/react-hammerjs/v0/react-hammerjs-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import Hammer from 'react-hammerjs'; + +class ReactHammer extends React.Component { + swipe: Hammer.ReactHammerProps['onSwipe'] = input => { + console.log(input.deltaX); + } + + render() { + const { children, ...props } = this.props; + return ( + + {children} + + ); + } +} diff --git a/types/react-hammerjs/v0/tsconfig.json b/types/react-hammerjs/v0/tsconfig.json new file mode 100644 index 0000000000..f8a95be3c6 --- /dev/null +++ b/types/react-hammerjs/v0/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "react-hammerjs": ["react-hammerjs/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "esModuleInterop": true + }, + "files": ["index.d.ts", "react-hammerjs-tests.tsx"] +} diff --git a/types/react-hammerjs/v0/tslint.json b/types/react-hammerjs/v0/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-hammerjs/v0/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-material-ui/index.d.ts b/types/react-native-material-ui/index.d.ts index 91ae62a3fb..b215820f2b 100644 --- a/types/react-native-material-ui/index.d.ts +++ b/types/react-native-material-ui/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for react-native-material-ui 1.30 +// Type definitions for react-native-material-ui 1.31 // Project: https://github.com/xotahal/react-native-material-ui // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Component } from 'react'; -import { ViewStyle, TextStyle, Image } from 'react-native'; +import { StyleProp, ViewStyle as ViewStyleRaw, TextStyle as TextStyleRaw, Image } from 'react-native'; + +export type ViewStyle = StyleProp; +export type TextStyle = StyleProp; export interface ActionButtonProps { actions?: string[] | JSX.Element[] | Array<{ diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index f66e46cb1e..ad8abe57fd 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -8465,8 +8465,8 @@ export namespace Animated { export function parallel(animations: Array, config?: ParallelConfig): CompositeAnimation; type Mapping = { [key: string]: Mapping } | AnimatedValue; - interface EventConfig { - listener?: ValueListenerCallback; + interface EventConfig { + listener?: (event?: NativeSyntheticEvent) => void; useNativeDriver?: boolean; } @@ -8486,7 +8486,7 @@ export namespace Animated { * ]), *``` */ - export function event(argMapping: Array, config?: EventConfig): (...args: any[]) => void; + export function event(argMapping: Array, config?: EventConfig): (...args: any[]) => void; /** * Make any React component Animatable. Used to create `Animated.View`, etc. diff --git a/types/react-native/test/animated.tsx b/types/react-native/test/animated.tsx index c27af04bb9..40f8c37ee7 100644 --- a/types/react-native/test/animated.tsx +++ b/types/react-native/test/animated.tsx @@ -1,6 +1,6 @@ -import * as React from "react-native"; +import * as React from "react"; -import { Animated, View } from "react-native"; +import { Animated, View, NativeSyntheticEvent, NativeScrollEvent } from "react-native"; function TestAnimatedAPI() { // Value @@ -63,6 +63,17 @@ function TestAnimatedAPI() { Animated.stagger(100, [spring1, springXY]); + const listener = (e?: NativeSyntheticEvent) => { + if (e) { + console.warn(e.nativeEvent.contentOffset.y); + } + }; + + Animated.event( + [{ nativeEvent: { contentOffset: { y: v1 } } }], + { useNativeDriver: true, listener }, + ); + return ( = { dangerouslySetInnerHTML: { __html: "STRONG" }, + unselectable: 'on', 'aria-atomic': false, 'aria-checked': 'true', 'aria-colcount': 7, diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index a682ec6588..9493bc6435 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -7,6 +7,7 @@ // Kurt Preston // Tim Chen // Pat Gaffney +// Prabodh Tiwari // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -240,15 +241,18 @@ import { UncontrolledAlert as UncontrolledAlert_, UncontrolledButtonDropdown as UncontrolledButtonDropdown_, UncontrolledDropdown as UncontrolledDropdown_, - UncontrolledTooltip as UncontrolledTooltip_ + UncontrolledTooltip as UncontrolledTooltip_, + UncontrolledCollapse as UncontrolledCollapse_ } from './lib/Uncontrolled'; export class UncontrolledAlert extends UncontrolledAlert_ {} export class UncontrolledButtonDropdown extends UncontrolledButtonDropdown_ {} export class UncontrolledDropdown extends UncontrolledDropdown_ {} export class UncontrolledTooltip extends UncontrolledTooltip_ {} +export class UncontrolledCollapse extends UncontrolledCollapse_ {} export { UncontrolledButtonDropdownProps, UncontrolledAlertProps, UncontrolledDropdownProps, - UncontrolledTooltipProps + UncontrolledTooltipProps, + UncontrolledCollapseProps } from './lib/Uncontrolled'; diff --git a/types/reactstrap/lib/Collapse.d.ts b/types/reactstrap/lib/Collapse.d.ts index c3d6572ec9..12247962aa 100644 --- a/types/reactstrap/lib/Collapse.d.ts +++ b/types/reactstrap/lib/Collapse.d.ts @@ -20,5 +20,16 @@ export type CollapseProps = React.HTMLProps & { onExited?: () => void; } & T; +export type UncontrolledProps = React.HTMLProps & { + isOpen?: boolean; + className?: string; + cssModule?: CSSModule; + tag?: React.ReactType; + navbar?: boolean; + toggle?: () => void; +} & T; + +export type UncontrolledCollapseProps = UncontrolledProps; + declare class Collapse extends React.Component> {} export default Collapse; diff --git a/types/reactstrap/lib/Uncontrolled.d.ts b/types/reactstrap/lib/Uncontrolled.d.ts index f54652710c..118b76d0d1 100644 --- a/types/reactstrap/lib/Uncontrolled.d.ts +++ b/types/reactstrap/lib/Uncontrolled.d.ts @@ -4,13 +4,16 @@ import { UncontrolledAlertProps } from './Alert'; import { UncontrolledButtonDropdownProps } from './ButtonDropdown'; import { UncontrolledDropdownProps } from './Dropdown'; import { UncontrolledTooltipProps } from './Tooltip'; +import { UncontrolledCollapseProps } from './Collapse'; export class UncontrolledAlert extends React.Component> {} export class UncontrolledButtonDropdown extends React.Component> {} export class UncontrolledDropdown extends React.Component> {} export class UncontrolledTooltip extends React.Component> {} +export class UncontrolledCollapse extends React.Component> {} export { UncontrolledAlertProps } from './Alert'; export { UncontrolledButtonDropdownProps } from './ButtonDropdown'; export { UncontrolledDropdownProps } from './Dropdown'; export { UncontrolledTooltipProps } from './Tooltip'; +export { UncontrolledCollapseProps } from './Collapse'; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 65fb319704..48afb0ce31 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -74,6 +74,7 @@ import { UncontrolledButtonDropdown, UncontrolledDropdown, UncontrolledTooltip, + UncontrolledCollapse, TabContent, Table, Tag, @@ -3741,6 +3742,7 @@ function Example117() { ; ; ; + ; } function Example118() { @@ -3831,6 +3833,7 @@ import { UncontrolledAlert as UncontrolledAlert_ } from './lib/Uncontrolled'; /* import { UncontrolledButtonDropdown as UncontrolledButtonDropdown_ } from './lib/Uncontrolled'; /* tslint:disable-line: no-relative-import-in-test no-duplicate-imports */ import { UncontrolledDropdown as UncontrolledDropdown_ } from './lib/Uncontrolled'; /* tslint:disable-line: no-relative-import-in-test no-duplicate-imports */ import { UncontrolledTooltip as UncontrolledTooltip_ } from './lib/Uncontrolled'; /* tslint:disable-line: no-relative-import-in-test no-duplicate-imports */ +import { UncontrolledCollapse as UncontrolledCollapse_ } from './lib/Uncontrolled'; /* tslint:disable-line: no-relative-import-in-test no-duplicate-imports */ function AnyPropExample() { return ( @@ -3913,6 +3916,7 @@ function AnyPropExample() { + ); } @@ -4000,6 +4004,7 @@ class UncontrolledAlertGeneric extends UncontrolledAlert {} class UncontrolledButtonDropdownGeneric extends UncontrolledButtonDropdown {} class UncontrolledDropdownGeneric extends UncontrolledDropdown {} class UncontrolledTooltipGeneric extends UncontrolledTooltip {} +class UncontrolledCollapseGeneric extends UncontrolledCollapse {} function GenericPropExample() { return ( @@ -4082,6 +4087,7 @@ function GenericPropExample() { + ); } @@ -4264,3 +4270,22 @@ class Example122 extends React.Component { ); } } + +function Example123() { + return( +
+ + + + + Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt magni, voluptas debitis + similique porro a molestias consequuntur earum odio officiis natus, amet hic, iste sed + dignissimos esse fuga! Minus, alias. + + + +
+ ); +} diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index f0ad8596ab..a3f1a5625e 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -19,8 +19,8 @@ declare module 'recompose' { type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean - // Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 - type Omit = Pick; + // Diff / Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html + type Omit = Pick> interface Observer{ next(props: T): void; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index 51d03bf3fe..0fbce8ed44 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -29,12 +29,15 @@ let options: sanitize.IOptions = { allowedSchemesByTag: { 'a': ['http', 'https'] }, - allowProtocolRelative: false, - parser: { - decodeEntities: true - } + allowProtocolRelative: false }; let unsafe = '
'; let safe = sanitize(unsafe, options); + +options.parser = { + decodeEntities: true +}; + +safe = sanitize(unsafe, options); diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 16cf53fbd7..fcb008c07b 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -1350,7 +1350,7 @@ declare namespace Stripe { livemode: boolean; - metadata?: IMetadata; + metadata: IMetadata; /** * Shipping information associated with the customer. diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 9654334af2..426d86f1a9 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for styled-components 3.0 // Project: https://github.com/styled-components/styled-components // Definitions by: Igor Oleinikov +// Ihor Chulinda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -104,19 +105,20 @@ export interface ThemedBaseStyledInterface component: React.ComponentType

, ): ThemedStyledFunction>; } -export type BaseStyledInterface = ThemedBaseStyledInterface; -export type ThemedStyledInterface = ThemedBaseStyledInterface; -export type StyledInterface = ThemedStyledInterface; +export type ThemedStyledInterface = ThemedBaseStyledInterface extends never ? any : T>; +export type StyledInterface = ThemedStyledInterface; +// tslint:disable-next-line:no-empty-interface +export interface DefaultTheme {} export interface ThemeProviderProps { theme?: T | ((theme: T) => T); } -export type ThemeProviderComponent = React.ComponentClass< +export type BaseThemeProviderComponent = React.ComponentClass< ThemeProviderProps ->; - -export interface ThemedCssFunction { + >; +export type ThemeProviderComponent = BaseThemeProviderComponent extends never ? any : T>; +export interface BaseThemedCssFunction { ( strings: TemplateStringsArray, ...interpolations: SimpleInterpolation[] @@ -126,6 +128,7 @@ export interface ThemedCssFunction { ...interpolations: Array>> ): Array>>; } +export type ThemedCssFunction = BaseThemedCssFunction extends never ? any : T>; // Helper type operators type KeyofBase = keyof any; @@ -150,20 +153,20 @@ export interface ThemedStyledComponentsModule { strings: TemplateStringsArray, ...interpolations: SimpleInterpolation[] ): void; - withTheme

( - component: React.ComponentType

, - ): React.ComponentClass>; + withTheme: WithThemeFnInterface; ThemeProvider: ThemeProviderComponent; } declare const styled: StyledInterface; -export const css: ThemedCssFunction; +export const css: ThemedCssFunction; -export function withTheme

( - component: React.ComponentType

, -): React.ComponentClass>; +export type BaseWithThemeFnInterface =

( + component: React.ComponentType

, + ) => React.ComponentClass>; +export type WithThemeFnInterface = BaseWithThemeFnInterface extends never ? any : T>; +export const withTheme: WithThemeFnInterface; export function keyframes( strings: TemplateStringsArray, diff --git a/types/twilio-video/index.d.ts b/types/twilio-video/index.d.ts new file mode 100644 index 0000000000..cc65da2c2c --- /dev/null +++ b/types/twilio-video/index.d.ts @@ -0,0 +1,522 @@ +// Type definitions for twilio-video 2.0 +// Project: https://twilio.com/video +// Definitions by: MindDoc , Darío Blanco +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { EventEmitter } from 'events'; + +/** + * Classes + */ +export class AccessTokenExpiredError extends TwilioError { + code: 20104; + message: 'Access Token expired or expiration date invalid'; +} +export class AccessTokenGrantsInvalidError extends TwilioError { + code: 20106; + message: 'Invalid Access Token grants'; +} +export class AccessTokenHeaderInvalidError extends TwilioError { + code: 20102; + message: 'Invalid Access Token header'; +} +export class AccessTokenIssuerInvalidError extends TwilioError { + code: 20103; + message: 'Invalid Access Token issuer/subject'; +} +export class AccessTokenNotYetValidError extends TwilioError { + code: 20105; + message: 'Access Token not yet valid'; +} +export class AccessTokenSignatureInvalidError extends TwilioError { + code: 20107; + message: 'Invalid Access Token signature'; +} +export class AudioTrack extends Track { + isStarted: boolean; + isEnabled: boolean; + kind: 'audio'; + mediaStreamTrack: MediaStreamTrack; + + attach(element?: HTMLMediaElement | string): HTMLMediaElement; + detach(element?: HTMLMediaElement | string): HTMLMediaElement[]; +} +export class ConfigurationAcquireFailedError extends TwilioError { + code: 53500; + message: 'Unable to acquire configuration'; +} +export class ConfigurationAcquireTurnFailedError extends TwilioError { + code: 53501; + message: 'Unable to acquire TURN credentials'; +} +export class LocalAudioTrack extends AudioTrack { + constructor(mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions); + + id: Track.ID; + isStopped: boolean; + + disable(): LocalAudioTrack; + enable(enabled?: boolean): LocalAudioTrack; + stop(): LocalAudioTrack; +} +export class LocalAudioTrackPublication extends LocalTrackPublication { + kind: 'audio'; + track: LocalAudioTrack; + + unpublish(): LocalAudioTrackPublication; +} +export class LocalAudioTrackStats extends LocalTrackStats { + audioLevel: AudioLevel | null; + jitter: number | null; +} +export class LocalDataTrack extends Track { + constructor(options?: LocalDataTrackOptions); + + id: Track.ID; + kind: 'data'; + maxPacketLifeTime: number | null; + maxRetransmits: number | null; + ordered: boolean; + reliable: boolean; + + send(data: string | Blob | ArrayBuffer | ArrayBufferView): void; +} +export class LocalDataTrackPublication extends LocalTrackPublication { + kind: 'data'; + track: LocalDataTrack; + + unpublish(): LocalDataTrackPublication; +} +export class LocalParticipant extends Participant { + audioTracks: Map; + dataTracks: Map; + tracks: Map; + videoTracks: Map; + + publishTrack(localTrack: LocalTrack): Promise; + publishTrack( + mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions, + ): Promise; + publishTracks( + tracks: LocalTrack[] | MediaStreamTrack[], + ): Promise; + setParameters(encodingParameters?: EncodingParameters | null): LocalParticipant; +} +export class LocalTrackPublication extends TrackPublication { + isTrackEnabled: boolean; + kind: Track.Kind; + track: LocalTrack; + + unpublish(): LocalTrackPublication; +} +export class LocalTrackStats extends TrackStats { + bytesSent: number | null; + packetsSent: number | null; + roundTripTime: number | null; +} +export class LocalVideoTrack extends VideoTrack { + constructor(mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions); + + id: Track.ID; + isStopped: boolean; + + disable(): LocalVideoTrack; + enable(enabled?: boolean): LocalVideoTrack; + stop(): LocalVideoTrack; +} +export class LocalVideoTrackPublication extends LocalTrackPublication { + kind: 'video'; + track: LocalVideoTrack; + + unpublish(): LocalVideoTrackPublication; +} +export class LocalVideoTrackStats extends LocalTrackStats { + captureDimensions: VideoTrack.Dimensions | null; + dimensions: VideoTrack.Dimensions | null; + captureFrameRate: number | null; + frameRate: number | null; +} +export class MediaClientLocalDescFailedError extends TwilioError { + code: 53400; + message: 'Client is unable to create or apply a local media description'; +} +export class MediaClientRemoteDescFailedError extends TwilioError { + code: 53402; + message: 'Client is unable to apply a remote media description'; +} +export class MediaConnectionError extends TwilioError { + code: 53405; + message: 'Media connection failed'; +} +export class MediaNoSupportedCodecError extends TwilioError { + code: 53404; + message: 'No supported codec'; +} +export class MediaServerLocalDescFailedError extends TwilioError { + code: 53401; + message: 'Server is unable to create or apply a local media description'; +} +export class MediaServerRemoteDescFailedError extends TwilioError { + code: 53403; + message: 'Server is unable to apply a remote media description'; +} +export namespace Participant { + type Identity = string; + type SID = string; +} +export class Participant extends EventEmitter { + audioTracks: Map; + dataTracks: Map; + identity: Participant.Identity; + networkQualityLEvel: NetworkQualityLevel | null; + sid: Participant.SID; + state: string; + tracks: Map; + videoTracks: Map; +} +export class ParticipantDuplicateIdentityError extends TwilioError { + code: 53205; + message: 'Participant disconnected because of duplicate identity'; +} +export class ParticipantIdentityCharsInvalidError extends TwilioError { + code: 53202; + message: 'Participant identity contains invalid characters'; +} +export class ParticipantIdentityInvalidError extends TwilioError { + code: 53200; + message: 'Participant identity is invalid'; +} +export class ParticipantIdentityTooLongError extends TwilioError { + code: 53201; + message: 'Participant identity is too long'; +} +export class ParticipantMaxTracksExceededError extends TwilioError { + code: 53203; + message: 'Participant has too many Tracks'; +} +export class ParticipantNotFoundError extends TwilioError { + code: 53204; + message: 'Participant not found'; +} +export class RemoteAudioTrack extends AudioTrack { + sid: Track.SID; +} +export class RemoteAudioTrackPublication extends RemoteTrackPublication { + kind: 'audio'; + track: RemoteAudioTrack | null; +} +export class RemoteAudioTrackStats extends RemoteTrackStats { + audioLevel: AudioLevel | null; + jitter: number | null; +} +export class RemoteDataTrack extends Track { + isEnabled: boolean; + isSubscribed: boolean; + kind: 'data'; + maxPacketLifeTime: number | null; + maxRetransmits: number | null; + ordered: boolean; + reliable: boolean; + sid: Track.SID; +} +export class RemoteDataTrackPublication extends RemoteTrackPublication { + kind: 'data'; + track: RemoteDataTrack | null; +} +export class RemoteParticipant extends Participant { + audioTracks: Map; + dataTracks: Map; + tracks: Map; + videoTracks: Map; +} +export class RemoteTrackPublication extends TrackPublication { + isSubscribed: boolean; + isTrackEnabled: boolean; + kind: Track.Kind; + track: RemoteTrack | null; +} +export class RemoteTrackStats { + bytesReceived: number | null; + packetsReceived: number | null; +} +export class RemoteVideoTrack extends VideoTrack { + sid: Track.SID; +} +export class RemoteVideoTrackPublication extends RemoteTrackPublication { + kind: 'video'; + track: RemoteVideoTrack | null; +} +export class RemoteVideoTrackStats extends RemoteTrackStats { + dimensions: VideoTrack.Dimensions | null; + frameRate: number | null; +} +export namespace Room { + type SID = string; +} +export class Room extends EventEmitter { + dominantSpeaker: RemoteParticipant | null; + isRecording: boolean; + localParticipant: LocalParticipant; + name: string; + participants: Map; + sid: Room.SID; + state: string; + + disconnect(): Room; + getStats(): Promise; +} +export class RoomCompletedError extends TwilioError { + code: 53118; + message: 'Room completed'; +} +export class RoomConnectFailedError extends TwilioError { + code: 53104; + message: 'Unable to connect to Room'; +} +export class RoomCreateFailedError extends TwilioError { + code: 53103; + message: 'Unable to create Room'; +} +export class RoomInvalidParametersError extends TwilioError { + code: 53114; + message: 'Room creation parameter(s) incompatible with the Room type'; +} +export class RoomMaxParticipantsExceededError extends TwilioError { + code: 53105; + message: 'Room contains too many Participants'; +} +export class RoomMaxParticipantsOutOfRangeError extends TwilioError { + code: 53107; + message: 'MaxParticipants is out of range'; +} +export class RoomMediaRegionInvalidError extends TwilioError { + code: 53115; + message: 'MediaRegion is invalid'; +} +export class RoomMediaRegionUnavailableError extends TwilioError { + code: 53116; + message: 'There are no media servers available in the MediaRegion'; +} +export class RoomNameCharsInvalidError extends TwilioError { + code: 53102; + message: 'Room name contains invalid characters'; +} +export class RoomNameInvalidError extends TwilioError { + code: 53100; + message: 'Room name is invalid'; +} +export class RoomNameTooLongError extends TwilioError { + code: 53101; + message: 'Room name is too long'; +} +export class RoomNotFoundError extends TwilioError { + code: 53106; + message: 'Room not found'; +} +export class RoomRoomExistsError extends TwilioError { + code: 53113; + message: 'Room exists'; +} +export class RoomStatusCallbackInvalidError extends TwilioError { + code: 53111; + message: 'StatusCallback is invalid'; +} +export class RoomStatusCallbackMethodInvalidError extends TwilioError { + code: 53110; + message: 'StatusCallbackMethod is invalid'; +} +export class RoomStatusInvalidError extends TwilioError { + code: 53112; + message: 'Status is invalid'; +} +export class RoomSubscriptionOperationNotSupportedError extends TwilioError { + code: 53117; + message: 'The subscription operation requested is not supported for the Room type'; +} +export class RoomTimeoutOutOfRangeError extends TwilioError { + code: 53109; + message: 'Timeout is out of range'; +} +export class RoomTypeInvalidError extends TwilioError { + code: 53108; + message: 'RoomType is not valid'; +} +export class SignalingConnectionDisconnectedError extends TwilioError { + code: 53001; + message: 'Signaling connection disconnected'; +} +export class SignalingConnectionError extends TwilioError { + code: 53000; + message: 'Signaling connection error'; +} +export class SignalingConnectionTimeoutError extends TwilioError { + code: 53002; + message: 'Signaling connection timed out'; +} +export class SignalingIncomingMessageInvalidError extends TwilioError { + code: 53003; + message: 'Client received an invalid signaling message'; +} +export class SignalingOutgoingMessageInvalidError extends TwilioError { + code: 53004; + message: 'Client sent an invalid signaling message'; +} +export class StatsReport { + peerConnectionId: string; + localAudioTrackStats: LocalAudioTrackStats[]; + localVideoTrackStats: LocalVideoTrackStats[]; + remoteAudioTrackStats: RemoteAudioTrackStats[]; + remoteVideoTrackStats: RemoteVideoTrackStats[]; +} +export namespace Track { + type Kind = 'audio' | 'video' | 'data'; + type ID = string; + type SID = string; +} +export class Track extends EventEmitter { + kind: Track.Kind; + name: string; +} +export class TrackInvalidError extends TwilioError { + code: 53300; + message: 'Track is invalid'; +} +export class TrackNameCharsInvalidError extends TwilioError { + code: 53303; + message: 'Track name contains invalid characters'; +} +export class TrackNameInvalidError extends TwilioError { + code: 53301; + message: 'Track name is invalid'; +} +export class TrackNameIsDuplicatedError extends TwilioError { + code: 53304; + message: 'Track name is duplicated'; +} +export class TrackNameTooLongError extends TwilioError { + code: 53302; + message: 'Track name is too long'; +} +export class TrackPublication { + trackName: string; + trackSid: Track.SID; +} +export class TrackServerTrackCapacityReachedError extends TwilioError { + code: 53305; + message: 'The server has reached capacity and cannot fulfill this request.'; +} +export class TrackStats { + trackId: Track.ID; + trackSid: Track.SID; + timestamp: number; + ssrc: string; + packetsLost: number | null; + codec: string | null; +} +export class TwilioError extends Error { + code: number; + toString(): string; +} +export namespace VideoTrack { + interface Dimensions { + width: number | null; + height: number | null; + } +} +export class VideoTrack extends Track { + isStarted: boolean; + isEnabled: boolean; + dimensions: VideoTrack.Dimensions; + kind: 'video'; + mediaStreamTrack: MediaStreamTrack; + + attach(element?: HTMLMediaElement | string): HTMLVideoElement; + detach(element?: HTMLMediaElement | string): HTMLMediaElement[]; +} + +/** + * Global (https://media.twiliocdn.com/sdk/js/video/releases/2.0.0-beta1/docs/global.html) + */ +export const version: string; + +/** Members */ +export type AudioCodec = 'isac' | 'opus' | 'PCMA' | 'PCMU'; +export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off'; +export type VideoCodec = 'H264' | 'VP8' | 'VP9'; + +/** Methods */ +export function connect(token: string, options?: ConnectOptions): Promise; +export function createLocalAudioTrack(options?: CreateLocalTrackOptions): Promise; +export function createLocalTracks(options?: CreateLocalTracksOptions): Promise; +export function createLocalVideoTrack(options?: CreateLocalTrackOptions): Promise; +export function isSupported(): boolean; +export function rewriteLocalTrackIds(room: Room, trackStats: LocalTrackStats[]): LocalTrackStats[]; + +/** Type Definitions */ +export type AudioLevel = number; +export type AudioTrackPublication = LocalAudioTrackPublication | RemoteAudioTrackPublication; +export interface ConnectOptions { + abortOnIceServersTimeout?: boolean; + audio?: boolean | CreateLocalTrackOptions; + iceServers?: RTCIceServer[]; + iceServersTimeout?: number; + iceTransportPolicy?: RTCIceTransportPolicy; + insights?: boolean; + maxAudioBitRate?: number | null; + maxVideoBitRate?: number | null; + name?: string | null; + preferredAudioCodecs?: AudioCodec[]; + preferredVideoCodecs?: VideoCodec[] | VideoCodecSettings[]; + logLevel?: LogLevel | LogLevels; + tracks?: LocalTrack[] | MediaStreamTrack[]; + video?: boolean | CreateLocalTrackOptions; +} +export interface CreateLocalTrackOptions { + logLevel: LogLevel | LogLevels; + name?: string; + workaroundWebKitBug180748?: boolean; // Lol +} +export interface CreateLocalTracksOptions { + audio?: boolean | CreateLocalTrackOptions; + logLevel?: LogLevel | LogLevels; + video?: boolean | CreateLocalTrackOptions; +} +export type DataTrack = LocalDataTrack | RemoteDataTrack; +export type DataTrackPublication = LocalDataTrackPublication | RemoteDataTrackPublication; +export interface EncodingParameters { + maxAudioBitrate?: number | null; + maxVideoBitrate?: number | null; +} +export interface LocalDataTrackOptions { + maxPacketLifeTime?: number | null; + maxRetransmits?: number | null; + ordered?: boolean; +} +export type LocalTrack = LocalAudioTrack | LocalVideoTrack | LocalDataTrack; +export interface LocalTrackOptions { + logLevel: LogLevel | LogLevels; + name?: string; +} +export interface LogLevels { + default: LogLevel; + media: LogLevel; + signaling: LogLevel; + webrtc: LogLevel; +} +export type NetworkQualityLevel = number; +export type RemoteTrack = RemoteAudioTrack | RemoteVideoTrack | RemoteDataTrack; +export interface RemoteTrackPublicationOptions { + logLevel: LogLevel | LogLevels; +} +export interface TrackPublicationOptions { + logLevel: LogLevel | LogLevels; +} +export interface VideoCodecSettings { + codec: VideoCodec; +} +export type VideoTrackPublication = LocalVideoTrackPublication | RemoteVideoTrackPublication; +export interface VP8CodecSettings { + name: VideoCodec; + simulcast?: boolean; +} diff --git a/types/twilio-video/tsconfig.json b/types/twilio-video/tsconfig.json new file mode 100644 index 0000000000..763a8aad1b --- /dev/null +++ b/types/twilio-video/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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", + "twilio-video-tests.ts" + ] +} diff --git a/types/twilio-video/tslint.json b/types/twilio-video/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/twilio-video/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/twilio-video/twilio-video-tests.ts b/types/twilio-video/twilio-video-tests.ts new file mode 100644 index 0000000000..b5cfe43e01 --- /dev/null +++ b/types/twilio-video/twilio-video-tests.ts @@ -0,0 +1,45 @@ +import * as Video from 'twilio-video'; + +// Examples taken from https://twilio.github.io/twilio-video/ (v2.x) + +Video.connect('$TOKEN', { name: 'room-name' }).then(room => { + room.participants.forEach(participantConnected); + room.on('participantConnected', participantConnected); + room.on('participantDisconnected', participantDisconnected); + room.once('disconnected', error => room.participants.forEach(participantDisconnected)); +}); + +function participantConnected(participant: Video.Participant) { + participant.on('trackSubscribed', trackSubscribed); + participant.on('trackUnsubscribed', trackUnsubscribed); + + participant.tracks.forEach(publication => { + const remotePublication = publication as Video.RemoteTrackPublication; + if (remotePublication.isSubscribed) { + trackSubscribed(remotePublication.track as Video.VideoTrack | Video.AudioTrack); + } + }); +} + +function participantDisconnected(participant: Video.Participant) { + participant.tracks.forEach((publication) => { + const remotePublication = publication as Video.RemoteTrackPublication; + if (remotePublication.isSubscribed) { + const { track } = remotePublication; + if (track) trackUnsubscribed(track as Video.AudioTrack | Video.VideoTrack); + } + }); +} + +function trackSubscribed(track: Video.VideoTrack | Video.AudioTrack) { + const media = track.attach(); + insertDomElement(media); +} + +function trackUnsubscribed(track: Video.VideoTrack | Video.AudioTrack) { + track.detach().forEach(element => element.remove()); +} + +function insertDomElement(element: any) { + // Do something with the dom element +} diff --git a/types/twitch-ext/index.d.ts b/types/twitch-ext/index.d.ts index 279d17cd14..87bad1958d 100644 --- a/types/twitch-ext/index.d.ts +++ b/types/twitch-ext/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for twitch-ext 1.14 +// Type definitions for twitch-ext 1.15 // Project: https://dev.twitch.tv/docs/extensions/reference/#javascript-helper // Definitions by: Benedict Etzel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -137,6 +137,13 @@ interface TwitchExtActions { */ followChannel(channelName: string): void; + /** + * This function causes your video-component or video-overlay extension to be minimized. + * + * @see https://dev.twitch.tv/docs/extensions/reference/#minimize + */ + minimize(): void; + /** * This function registers a callback that is invoked whenever a user completes an interaction prompted by the followChannel action. * diff --git a/types/twitch-ext/twitch-ext-tests.ts b/types/twitch-ext/twitch-ext-tests.ts index d981367fd5..0284e0191c 100644 --- a/types/twitch-ext/twitch-ext-tests.ts +++ b/types/twitch-ext/twitch-ext-tests.ts @@ -32,6 +32,7 @@ window.Twitch.ext.actions.onFollow((didFollow, channelName) => { console.log(`You followed ${channelName}`); } }); +window.Twitch.ext.actions.minimize(); window.Twitch.ext.actions.followChannel("hearthsim"); window.Twitch.ext.actions.requestIdShare(); diff --git a/types/typography/index.d.ts b/types/typography/index.d.ts new file mode 100644 index 0000000000..2c5be43583 --- /dev/null +++ b/types/typography/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for typography 0.16 +// Project: https://github.com/KyleAMathews/typography.js +// Definitions by: Boye +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface BaseLine { + fontSize: string; + lineHeight: string; +} + +export interface VerticalRhythm { + rhythm: (value: number) => string; + scale: (value: number) => object; + adjustFontSizeTo: (value?: number | string) => object; + linesForFontSize: (fontSize: number) => number; + establishBaseline: () => BaseLine; +} + +export interface GoogleFont { + name: string; + styles: string[]; +} + +export interface TypographyOptions { + baseFontSize?: string; + baseLineHeight?: number; + scaleRatio?: number; + googleFonts?: GoogleFont[]; + headerFontFamily?: string[]; + bodyFontFamily?: string[]; + headerColor?: string; + bodyColor?: string; + headerWeight?: number | string; + bodyWeight?: number | string; + boldWeight?: number | string; + blockMarginBottom?: number; + includeNormalize?: boolean; + overrideStyles?: ( + VerticalRhythm: VerticalRhythm, + options: TypographyOptions, + styles: any + ) => object; + overrideThemeStyles?: ( + VerticalRhythm: VerticalRhythm, + options: TypographyOptions, + styles: any + ) => object; + plugins?: any[]; +} + +declare class Typography { + constructor(opts: TypographyOptions); + options: TypographyOptions; + createStyles(): string; + toJSON(): object; + injectStyles(): void; +} + +export default Typography; diff --git a/types/typography/tsconfig.json b/types/typography/tsconfig.json new file mode 100644 index 0000000000..cebfdd1e2b --- /dev/null +++ b/types/typography/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", + "typography-tests.ts" + ] +} diff --git a/types/typography/tslint.json b/types/typography/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/typography/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/typography/typography-tests.ts b/types/typography/typography-tests.ts new file mode 100644 index 0000000000..5b004d2eae --- /dev/null +++ b/types/typography/typography-tests.ts @@ -0,0 +1,12 @@ +import Typography from 'typography'; + +const typography = new Typography({ + baseFontSize: '18px', + baseLineHeight: 1.45, + headerFontFamily: ['Avenir Next', 'Helvetica Neue', 'Segoe UI', 'Helvetica', 'Arial', 'sans-serif'], + bodyFontFamily: ['Georgia', 'serif'] +}); + +typography.createStyles(); // $ExpectType string +typography.toJSON(); // $ExpectType object +typography.options; // $ExpectType TypographyOptions diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index bea88fcc9d..1981528a55 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -4395,6 +4395,20 @@ declare namespace videojs { */ reset(): void; + /** + * Returns whether or not the player is in the "seeking" state. + * + * @return boolean True if the player is in the seeking state, false if not. + */ + seeking(): boolean; + + /** + * Returns the TimeRanges of the media that are currently available for seeking to. + * + * @return TimeRanges Returns the TimeRanges of the media that are currently available for seeking to. + */ + seekable(): TimeRanges; + /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 22daba4274..1c10c9d5f1 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -43,7 +43,7 @@ declare class Web3 { bzz: Bzz; currentProvider: Provider; eth: Eth; - ssh: Shh; + shh: Shh; givenProvider: Provider; providers: Providers; setProvider(provider: Provider): void; diff --git a/types/web3/package.json b/types/web3/package.json new file mode 100644 index 0000000000..e29fa78a2d --- /dev/null +++ b/types/web3/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "bignumber.js": "^4.0.0", + "underscore": "^1.8.3" + } +} diff --git a/types/web3/types.d.ts b/types/web3/types.d.ts index 985dab0979..c3d681d60f 100644 --- a/types/web3/types.d.ts +++ b/types/web3/types.d.ts @@ -81,5 +81,12 @@ export interface Subscribe { on(type: "error", handler: (data: Error) => void): void; } -export class Shh {} // TODO: Type +export interface Shh { + generateSymKeyFromPassword(password: string): Promise; + generateSymKeyFromPassword( + password: string, + callback: Callback + ): void; + // TODO: type every method +} export class Bzz {} // TODO: Type diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index 48cba2d885..99e1ce9f78 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -21,9 +21,12 @@ myContract.options.gas = 5000000; const weiStr: string = web3.utils.toWei("100", "gwei"); const weiBn: BigNumber = web3.utils.toWei(web3.utils.toBN("1")); const rndHex: string = Web3.utils.randomHex(10); +const shhPromise: Promise = web3.shh.generateSymKeyFromPassword("xyz"); web3.eth.personal.unlockAccount( web3.eth.defaultAccount, "passphrase", 600 ); + + diff --git a/types/webpack-bundle-analyzer/index.d.ts b/types/webpack-bundle-analyzer/index.d.ts index 6b2db94b65..f1e3f2a3c6 100644 --- a/types/webpack-bundle-analyzer/index.d.ts +++ b/types/webpack-bundle-analyzer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for webpack-bundle-analyzer 2.9 +// Type definitions for webpack-bundle-analyzer 2.13 // Project: https://github.com/th0r/webpack-bundle-analyzer // Definitions by: Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,9 @@ import * as webpack from 'webpack'; export namespace BundleAnalyzerPlugin { + type ExcludeAssetsPatternFn = (assetName: string) => boolean; + type ExcludeAssetsPattern = string | RegExp | ExcludeAssetsPatternFn; + interface Options { /** * Can be "server", "static" or "disabled". @@ -68,6 +71,16 @@ export namespace BundleAnalyzerPlugin { */ statsOptions?: null | webpack.Stats.ToJsonOptionsObject; + /** + * Default: `null`. + * Patterns that will be used to match against asset names to exclude them from the report. + * If pattern is a string it will be converted to RegExp via `new RegExp(str)`. + * If pattern is a function it should have the following signature `(assetName: string) => boolean` + * and should return true to exclude matching asset. + * If multiple patterns are provided asset should match at least one of them to be excluded. + */ + excludeAssets?: null | ExcludeAssetsPattern | ExcludeAssetsPattern[]; + /** * Log level. Can be "info", "warn", "error" or "silent". * Defaults to "info" diff --git a/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts b/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts index 0b5fcabcc7..7aa2b0aee7 100644 --- a/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts +++ b/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts @@ -19,6 +19,11 @@ const config: webpack.Configuration = { statsOptions: { source: false }, + excludeAssets: [ + 'foo', + /foo/, + assetName => assetName.indexOf('foo') !== -1 + ], logLevel: 'info' }) ] diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 32969d3b83..2b0a905afe 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -7,4100 +7,4087 @@ // TypeScript Version: 2.8 declare namespace wx { - // #region 基本参数 - interface DataResponse { - /** 回调函数返回的内容 */ - data: object | string | ArrayBuffer; - /** 开发者服务器返回的 HTTP 状态码 */ - statusCode: number; - /** 开发者服务器返回的 HTTP Response Header */ - header: object; - } - interface ErrMsgResponse { - /** 成功:ok,错误:详细信息 */ - errMsg: "ok" | string; - } - interface TempFileResponse { - /** 文件的临时路径 */ - tempFilePath: string; - } - interface BaseOptions { - /** 接口调用成功的回调函数 */ - success?(res: R): void; - /** 接口调用失败的回调函数 */ - fail?(res: E): void; - /** 接口调用结束的回调函数(调用成功、失败都会执行) */ - complete?(res: any): void; - } - interface ErrCodeResponse { - errCode: number; - } - // #endregion - // #region 网络API列表 - // 发起请求 - interface RequestHeader { - [key: string]: string; - } - interface RequestOptions extends BaseOptions { - /** 开发者服务器接口地址 */ - url: string; - /** 请求的参数 */ - data?: string | object | ArrayBuffer; - /** 设置请求的 header , header 中不能设置 Referer */ - header?: RequestHeader; - /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ - method?: - | "GET" - | "OPTIONS" - | "GET" - | "HEAD" - | "POST" - | "PUT" - | "DELETE" - | "TRACE" - | "CONNECT"; - /** 如果设为json,会尝试对返回的数据做一次 JSON.parse */ - dataType?: string; - /** - * 设置响应的数据类型。合法值:text、arraybuffer - * @version 1.7.0 - */ - responseType?: string; - /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ - success?(res: DataResponse): void; - } - /** - * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 - */ - function request(options: RequestOptions): RequestTask; - - /** - * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 - */ - interface RequestTask { - abort(): void; - } - - interface UploadTask { - /** - * 监听上传进度变化 - * @version 1.4.0 - */ - onProgressUpdate( - callback?: ( - res: { - /** 上传进度百分比 */ - progress: number; - /** 已经上传的数据长度,单位 Bytes */ - totalBytesSent: number; - /** 预期需要上传的数据总长度,单位 Bytes */ - totalBytesExpectedToSend: number; - } - ) => void - ): void; - /** - * 中断下载任务 - * @version 1.4.0 - */ - abort(): void; - } - // 上传下载 - interface UploadFileOptions extends BaseOptions { - /** 开发者服务器 url */ - url: string; - /** 要上传文件资源的路径 */ - filePath: string; - /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ - name: string; - /** HTTP 请求 Header , header 中不能设置 Referer */ - header?: RequestHeader; - /** HTTP 请求中其他额外的 form data */ - formData?: any; - } - interface UploadFileResponse { - data: string; // 开发者服务器返回的数据 - statusCode: number; // 开发者服务器返回的 HTTP 状态码 - } - /** - * 将本地资源上传到开发者服务器。 - * 如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后, - * 可通过此接口将本地资源上传到指定服务器。 - * 客户端发起一个 HTTPS POST 请求, - * 其中 Content-Type 为 multipart/form-data 。 - */ - function uploadFile(options: UploadFileOptions): UploadTask; - interface DownloadTask { - /** - * 监听下载进度变化 - * @version 1.4.0 - */ - onProgressUpdate( - callback?: ( - res: { - /** 下载进度百分比 */ - progress: number; - /** 已经下载的数据长度,单位 Bytes */ - totalBytesWritten: number; - /** 预期需要下载的数据总长度,单位 Bytes */ - totalBytesExpectedToWrite: number; - } - ) => void - ): void; - /** - * 中断下载任务 - * @version 1.4.0 - */ - abort(): void; - } - interface DownloadFileOptions extends BaseOptions { - /** 下载资源的 url */ - url: string; - /** 下载资源的类型,用于客户端识别处理,有效值:image/audio/video */ - type?: string; - /** HTTP 请求 Header */ - header?: RequestHeader; - /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ - success?(res: TempFileResponse): void; - } - /** - * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, - * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 - */ - function downloadFile(options: DownloadFileOptions): DownloadTask; - // WebSocket - interface ConnectSocketOptions extends BaseOptions { - /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ - url: string; - /** 请求的数据 */ - data?: any; - /** HTTP Header , header 中不能设置 Referer */ - header?: RequestHeader; - /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ - method?: string; - /** - * 子协议数组 - * @version 1.4.0 - */ - protocols?: string[]; - } - /** - * 创建一个 WebSocket 连接; - * 一个微信小程序同时只能有一个 WebSocket 连接, - * 如果当前已存在一个 WebSocket 连接, - * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 - */ - function connectSocket(options: ConnectSocketOptions): void; - /** 监听WebSocket连接打开事件。 */ - function onSocketOpen(callback: () => void): void; - /** 监听WebSocket错误。 */ - function onSocketError(callback: (error: any) => void): void; - interface SendSocketMessageOptions extends BaseOptions { - /** 需要发送的内容 */ - data: string | ArrayBuffer; - } - /** - * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket, - * 并在 wx.onSocketOpen 回调之后才能发送。 - */ - function sendSocketMessage(options: SendSocketMessageOptions): void; - /** - * 监听WebSocket接受到服务器的消息事件。 - */ - function onSocketMessage(callback: (res: DataResponse) => void): void; - /** - * 关闭WebSocket连接。 - */ - interface CloseSocketOptions extends BaseOptions { - code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 - reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) - } - - /** - * 关闭WebSocket连接。 - */ - function closeSocket(options: CloseSocketOptions): void; - /** 监听WebSocket关闭。 */ - function onSocketClose(callback: () => void): void; - // #endregion - // #region 媒体API列表 - // 媒体-----图片 - type ImageSizeType = "original" | "compressed"; - type ImageSourceType = "album" | "camera"; - type VideoSourceType = "album" | "camera"; - type CameraDevice = "front" | "back"; - interface TempFile { - /** 本地文件路径 */ - path: string; - /** 本地文件大小,单位:B */ - size: number; - } - interface TempFilesData { - /** 文件的临时路径 */ - tempFilePaths: string; - /** - * 图片的本地文件列表,每一项是一个 File 对象 - * @version 1.2.0 - */ - tempFiles: TempFile[]; - } - interface ChooseImageOptions extends BaseOptions { - /** 最多可以选择的图片张数,默认9 */ - count?: number; - /** original 原图,compressed 压缩图,默认二者都有 */ - sizeType?: ImageSizeType[]; - /** album 从相册选图,camera 使用相机,默认二者都有 */ - sourceType?: ImageSourceType[]; - /** 成功则返回图片的本地文件路径列表 tempFilePaths */ - success(res: TempFilesData): void; - } - /** - * 从本地相册选择图片或使用相机拍照。 - */ - function chooseImage(options: ChooseImageOptions): void; - interface PreviewImageOptions extends BaseOptions { - /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ - current?: string; - /** 需要预览的图片链接列表 */ - urls: string[]; - } - /** - * 预览图片。 - */ - function previewImage(options: PreviewImageOptions): void; - interface GetImageInfoOptions extends BaseOptions { - /** - * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 - */ - src: string; - } - /** - * 获取图片信息 - */ - function getImageInfo(options: GetImageInfoOptions): void; - interface SaveImageToPhotosAlbumOptions extends BaseOptions { - /** - * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 - */ - filePath: string; - success(res: { errMsg: string }): void; - } - /** - * 保存图片到系统相册。 - * 需要用户授权 scope.writePhotosAlbum - * @version 1.2.0 - */ - function saveImageToPhotosAlbum( - options: SaveImageToPhotosAlbumOptions - ): void; - // 媒体-----录音 - interface StartRecordAudioOptions extends BaseOptions { - /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ - success?(res: TempFileResponse): void; - } - /** - * 开始录音。当主动调用wx.stopRecord, - * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 - * 注:文件的临时路径,在小程序本次启动期间可以正常使用, - * 如需持久保存,需在主动调用wx.saveFile,在小程序下次启动时才能访问得到。 - * @deprecated 1.6.0 - */ - function startRecord(options: StartRecordAudioOptions): void; - - interface StopRecordAudioOptions extends BaseOptions { - success?(res: TempFileResponse): void; - } - /** - * 主动调用停止录音。 - */ - function stopRecord(options?: StopRecordAudioOptions): void; - type EncodeBitRate = - | 8000 - | 11025 - | 12000 - | 16000 - | 22050 - | 24000 - | 32000 - | 44100 - | 48000; - interface RecorderManagerStartOptions { - /** - * 指定录音的时长,单位 ms - * 如果传入了合法的 duration - * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) - */ - duration?: number; - /** - * 采样率,有效值 8000/16000/44100 - */ - sampleRate?: number; - /** - * 否 录音通道数,有效值 1/2 - */ - numberOfChannels?: number; - /** - * 编码码率 - * 采样率和码率有一定要求,具体有效值如下: - * 采样率 编码码率 - * + 8000 16000 ~ 48000 - * + 11025 16000 ~ 48000 - * + 12000 24000 ~ 64000 - * + 16000 24000 ~ 96000 - * + 22050 32000 ~ 128000 - * + 24000 32000 ~ 128000 - * + 32000 48000 ~ 192000 - * + 44100 64000 ~ 320000 - * + 48000 64000 ~ 320000 - */ - encodeBitRate: number; - /** 音频格式,有效值 aac/mp3 */ - format: string; - /** - * 指定帧大小,单位 KB - * 传入 frameSize 后,每录制指定帧大小的内容后 - * 会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。 - */ - frameSize: number; - } - interface OnRecorderManagerStopOptions { - tempFilePath: string; - } - interface OnFrameRecordedOptions { - /** 录音分片结果数据 */ - frameBuffer: ArrayBuffer; - /** 当前帧是否正常录音结束前的最后一帧 */ - isLastFrame: boolean; - } - interface RecorderManager { - /** 开始录音 */ - start(options?: RecorderManagerStartOptions): void; - /** 暂停录音 */ - pause(): void; - /** 继续录音 */ - resume(): void; - /** 停止录音 */ - stop(): void; - /** 录音开始事件 */ - onStart(callback?: () => void): void; - /** 录音暂停事件 */ - onPause(callback?: () => void): void; - /** 录音恢复事件 */ - onResume(callback?: () => void): void; - /** 录音停止事件,会回调文件地址 */ - onStop( - callback?: (options: OnRecorderManagerStopOptions) => void - ): void; - /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ - onFrameRecorded( - callback?: (options: OnFrameRecordedOptions) => void - ): void; - /** 录音错误事件, 会回调错误信息 */ - onError(callback?: (err: ErrMsgResponse) => void): void; - } - /** - * 获取全局唯一的录音管理器 recorderManager - * @version 1.6.0 - */ - function getRecorderManager(): RecorderManager; - // 媒体-----音频播放控制 - interface PlayVoiceOptions extends BaseOptions { - /** 需要播放的语音文件的文件路径 */ - filePath: string; - } - /** - * 开始播放语音,同时只允许一个语音文件正在播放, - * 如果前一个语音文件还没播放完,将中断前一个语音播放。 - * @deprecated 1.6.0 - */ - function playVoice(options: PlayVoiceOptions): void; - /** - * 暂停正在播放的语音。 - * 再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。 - * 如果想从头开始播放,需要先调用 wx.stopVoice。 - * @deprecated 1.6.0 - */ - function pauseVoice(): void; - /** - * 结束播放语音。 - * @deprecated 1.6.0 - */ - function stopVoice(): void; - // 媒体-----音乐播放控制 - interface BackgroundAudioPlayerState { - /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ - duration: number; - /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ - currentPosition: number; - /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ - status: number; - /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ - downloadPercent: number; - /** 歌曲数据链接,只有在当前有音乐播放时返回 */ - dataUrl: string; - } - interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { - /** 接口调用成功的回调函数 */ - success?(state: BackgroundAudioPlayerState): void; - /** 接口调用失败的回调函数 */ - fail?(): void; - /** 接口调用结束的回调函数(调用成功、失败都会执行) */ - complete?(): void; - } - /** - * 获取音乐播放状态。 - * @deprecated 1.2.0 - */ - function getBackgroundAudioPlayerState( - options: GetBackgroundAudioPlayerStateOptions - ): void; - interface PlayBackgroundAudioOptions extends BaseOptions { - /** 音乐链接 */ - dataUrl: string; - /** 音乐标题 */ - title?: string; - /** 封面URL */ - coverImgUrl?: string; - } - /** - * 播放音乐,同时只能有一首音乐正在播放。 - * @deprecated 1.2.0 - */ - function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; - /** - * 暂停播放音乐。 - * @deprecated 1.2.0 - */ - function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; - interface SeekBackgroundAudioOptions extends BaseOptions { - /** 音乐位置,单位:秒 */ - position: number; - } - /** - * 控制音乐播放进度。 - * @deprecated 1.2.0 - */ - function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; - /** - * 停止播放音乐。 - * @deprecated 1.2.0 - */ - function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; - /** - * 监听音乐播放。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioPlay(callback: () => void): void; - /** - * 监听音乐暂停。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioPause(callback: () => void): void; - /** - * 监听音乐停止。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioStop(callback: () => void): void; - interface BackgroundAudioManager { - /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ - readonly duration: number; - /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ - readonly currentTime: number; - /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ - readonly paused: boolean; - /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ - src: string; - /** 音频开始播放的位置(单位:s) */ - startTime: number; - /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ - buffered: number; - /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ - title: string; - /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - epname: string; - /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - singer: string; - /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ - coverImgUrl: string; - /** 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - webUrl: string; - /** 播放 */ - play(): void; - /** 暂停 */ - pause(): void; - /** 停止 */ - stop(): void; - /** 跳转到指定位置,单位 s */ - seek(position: number): void; - /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ - onCanplay(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频播放事件 */ - onPlay(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频暂停事件 */ - onPause(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频停止事件 */ - onStop(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频自然播放结束事件 */ - onEnded(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频播放进度更新事件 */ - onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; - /** 用户在系统音乐播放面板点击上一曲事件(iOS only) */ - onPrev(callback: (res: ErrCodeResponse) => void): void; - /** 用户在系统音乐播放面板点击下一曲事件(iOS only) */ - onNext(callback: (res: ErrCodeResponse) => void): void; - /** 背景音频播放错误事件 */ - onError(callback: (res: ErrCodeResponse) => void): void; - /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ - onWaiting(callback: (res: ErrCodeResponse) => void): void; - } - /** - * 获取全局唯一的背景音频管理器 backgroundAudioManager。 - * @version 1.2.0 - */ - function getBackgroundAudioManager(): BackgroundAudioManager; - // 媒体-----音频组件控制 - /** - * audioContext 通过 audioId 跟一个