diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 1e57cd1427..ed0e9d1f3f 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for auth0 2.9.2 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx new file mode 100644 index 0000000000..bceab689e7 --- /dev/null +++ b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx @@ -0,0 +1,30 @@ +import React = require('react'); +import enzyme = require('enzyme'); +import configureExtensions = require('@commercetools/enzyme-extensions'); + +configureExtensions(enzyme.ShallowWrapper); + +function App() { + return 'Hello world'} />; +} + +interface ChildProps { + cb: () => string; +} + +function Child(props: ChildProps) { + return
{props.cb()}
; +} + +enzyme.shallow() + .find(App) + .renderProp('render'); +enzyme.shallow() + .find(Child) + .renderProp('render', 1, 2); + +enzyme.shallow() + .find(Child) + .drill(props => props.cb()); + +enzyme.shallow().until(Child); diff --git a/types/commercetools__enzyme-extensions/index.d.ts b/types/commercetools__enzyme-extensions/index.d.ts new file mode 100644 index 0000000000..7c009f8e95 --- /dev/null +++ b/types/commercetools__enzyme-extensions/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for @commercetools/enzyme-extensions 3.0 +// Project: https://github.com/commercetools/enzyme-extensions +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as enzyme from 'enzyme'; + +declare module 'enzyme' { + interface UntilOptions { + maxDepth: number; + } + interface ShallowWrapper

{ + renderProp(propName: string, ...args: any[]): ShallowWrapper

; + drill(expander: (props: any) => ShallowWrapper): ShallowWrapper

; + until(selector: EnzymeSelector, options?: UntilOptions): ShallowWrapper

; + } +} + +declare function monkeyPatchShallowWrapper(s: typeof enzyme.ShallowWrapper): void; + +export = monkeyPatchShallowWrapper; diff --git a/types/commercetools__enzyme-extensions/tsconfig.json b/types/commercetools__enzyme-extensions/tsconfig.json new file mode 100644 index 0000000000..9e6d70239e --- /dev/null +++ b/types/commercetools__enzyme-extensions/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@commercetools/enzyme-extensions": ["commercetools__enzyme-extensions"] + } + }, + "files": [ + "index.d.ts", + "commercetools__enzyme-extensions-tests.tsx" + ] +} diff --git a/types/commercetools__enzyme-extensions/tslint.json b/types/commercetools__enzyme-extensions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/commercetools__enzyme-extensions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts new file mode 100644 index 0000000000..72925fe5ba --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts @@ -0,0 +1,63 @@ +let BluetoothClassicSerial: BluetoothClassicSerial = + window.BluetoothClassicSerial; + +BluetoothClassicSerial.connect( + "", + [""] +); +BluetoothClassicSerial.connect( + "", + [""], + results => {} +); +BluetoothClassicSerial.connect( + "", + [""], + results => {}, + error => {} +); +BluetoothClassicSerial.connectInsecure("", [""]); +BluetoothClassicSerial.connectInsecure("", [""], results => {}); +BluetoothClassicSerial.connectInsecure("", [""], results => {}, error => {}); +BluetoothClassicSerial.register(() => {}); +BluetoothClassicSerial.disconnect(results => {}); +BluetoothClassicSerial.disconnect(results => {}, error => {}); +BluetoothClassicSerial.write("", ""); +BluetoothClassicSerial.write("", "", results => {}); +BluetoothClassicSerial.write("", "", results => {}, error => {}); +BluetoothClassicSerial.available(""); +BluetoothClassicSerial.available("", results => {}); +BluetoothClassicSerial.available("", results => {}, error => {}); +BluetoothClassicSerial.read(""); +BluetoothClassicSerial.read("", results => {}); +BluetoothClassicSerial.read("", results => {}, error => {}); +BluetoothClassicSerial.readUntil("", ""); +BluetoothClassicSerial.readUntil("", "", results => {}); +BluetoothClassicSerial.readUntil("", "", results => {}, error => {}); +BluetoothClassicSerial.subscribe("", ""); +BluetoothClassicSerial.subscribe("", "", results => {}); +BluetoothClassicSerial.subscribe("", "", results => {}, error => {}); +BluetoothClassicSerial.unsubscribe(""); +BluetoothClassicSerial.unsubscribe("", results => {}); +BluetoothClassicSerial.unsubscribe("", results => {}, error => {}); +BluetoothClassicSerial.subscribeRawData(""); +BluetoothClassicSerial.subscribeRawData("", results => {}); +BluetoothClassicSerial.subscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.unsubscribeRawData(""); +BluetoothClassicSerial.unsubscribeRawData("", results => {}); +BluetoothClassicSerial.unsubscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.clear(""); +BluetoothClassicSerial.clear("", results => {}); +BluetoothClassicSerial.clear("", results => {}, error => {}); +BluetoothClassicSerial.list(results => {}); +BluetoothClassicSerial.list(results => {}, error => {}); +BluetoothClassicSerial.isConnected(results => {}); +BluetoothClassicSerial.isConnected(results => {}, error => {}); +BluetoothClassicSerial.isEnabled(results => {}); +BluetoothClassicSerial.isEnabled(results => {}, error => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}, error => {}); +BluetoothClassicSerial.enable(results => {}); +BluetoothClassicSerial.enable(results => {}, error => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}, error => {}); diff --git a/types/cordova-plugin-bluetoothclassic-serial/index.d.ts b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts new file mode 100644 index 0000000000..2dfe8c94ae --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for cordova-plugin-bluetoothClassic-serial 0.9 +// Project: https://github.com/soltius/BluetoothClassicSerial +// Definitions by: Wouter Roosendaal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Global object bluetoothClassicSerial. + */ +interface Window { + BluetoothClassicSerial: BluetoothClassicSerial; +} + +interface BluetoothClassicSerial { + connect: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + connectInsecure: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + register: (data_cb?: () => any) => void; + disconnect: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + write: ( + interfaceId: string, + data: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + available: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + read: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + readUntil: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribe: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribe: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + clear: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + list: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isConnected: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isEnabled: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + showBluetoothSettings: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + enable: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + discoverUnpaired: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; +} + +declare var bluetoothClassicSerial: BluetoothClassicSerial; diff --git a/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json b/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json new file mode 100644 index 0000000000..5cd12b710a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-bluetoothclassic-serial-tests.ts" + ] +} diff --git a/types/node-gamepad/tslint.json b/types/cordova-plugin-bluetoothclassic-serial/tslint.json similarity index 100% rename from types/node-gamepad/tslint.json rename to types/cordova-plugin-bluetoothclassic-serial/tslint.json diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 8169358155..9d6936875a 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -9,6 +9,7 @@ tracer.init({ debug: msg => {}, error: err => {}, }, + tags: { tracerEnv: 'dev'} }); function useWebFrameworkPlugin(plugin: "express" | "hapi" | "koa" | "restify") { diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts index 90aa9afc66..311fa7675e 100644 --- a/types/dd-trace/index.d.ts +++ b/types/dd-trace/index.d.ts @@ -110,6 +110,11 @@ interface TracerOptions { debug: (message: string) => void; error: (err: Error) => void; }; + + /** + * Global tags that should be assigned to every span. + */ + tags?: { [key: string]: any }; } interface ExperimentalOptions {} diff --git a/types/gamepad/gamepad-tests.ts b/types/gamepad/gamepad-tests.ts index af3095adb0..b71203eb7c 100644 --- a/types/gamepad/gamepad-tests.ts +++ b/types/gamepad/gamepad-tests.ts @@ -1,70 +1,69 @@ +/// +import gamepad = require('gamepad'); +// Initialize the library +gamepad.init(); +// List the state of all currently attached devices +for (let i = 0, l = gamepad.numDevices(); i < l; i++) { + console.log(i, gamepad.deviceAtIndex(i)); +} -()=>{ - function runAnimation() - { - window.requestAnimationFrame(runAnimation); +// Create a game loop and poll for events +setInterval(gamepad.processEvents, 16); +// Scan for new gamepads as a slower rate +setInterval(gamepad.detectDevices, 500); - var gamepads = navigator.getGamepads(); - - for (var i = 0; i < gamepads.length; ++i) - { - var pad = gamepads[i]; - // todo; simple demo of displaying pad.axes and pad.buttons +// Listen for new gamepads being attached +gamepad.on('attach', (deviceID, device) => { + console.log('attach', { + deviceID, + device: { + deviceID: device.deviceID, + description: device.description, + vendorID: device.vendorID, + productID: device.productID, + axisStates: device.axisStates, + buttonStates: device.buttonStates, } - } + }); +}); - window.requestAnimationFrame(runAnimation); -}; +// Listen for new gamepads being removed +gamepad.on('remove', deviceID => { + console.log('remove', { + deviceID + }); +}); -(()=>{ - var gamepadconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' connected!'); - if(e.gamepad.mapping == 'standard'){ - console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); - } - }; - var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); - }; +// Listen for button down events on all gamepads +gamepad.on('up', (deviceID, buttonID, timestamp) => { + console.log('up', { + deviceID, + buttonID, + timestamp + }); +}); - window.addEventListener('GamepadConnected', gamepadconnected, false); - window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('webkitGamepadConnected', gamepadconnected, false); - window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('mozGamepadConnected', gamepadconnected, false); - window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); +// Listen for button down events on all gamepads +gamepad.on('down', (deviceID, buttonID, timestamp) => { + console.log('down', { + deviceID, + buttonID, + timestamp + }); +}); - var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; - var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; - if(getGamepads){ - function runAnimation() - { - requestAnimationFrame.call(window, runAnimation); +// Listen for move events on all gamepads +gamepad.on('move', (deviceID, axisID, value, lastValue, timestamp) => { + console.log('move', { + deviceID, + axisID, + value, + lastValue, + timestamp + }); +}); - var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); - for(var i = 0; i < gamepads.length; i++){ - var pad: Gamepad.Gamepad = gamepads[i]; - if(pad && pad.connected){ - for (var k = 0; k < pad.buttons.length; k++) - { - var button: Gamepad.GamepadButton = pad.buttons[k]; - if(button.pressed){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); - } - } - for (var k = 0; k < pad.axes.length; k++) - { - var axis = pad.axes[k]; - if(Math.abs(axis) > 0.1){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); - } - } - } - } - } - - runAnimation(); - } -})(); \ No newline at end of file +// Shutdown the library +gamepad.shutdown(); diff --git a/types/gamepad/index.d.ts b/types/gamepad/index.d.ts index 3678190522..b66e13336b 100644 --- a/types/gamepad/index.d.ts +++ b/types/gamepad/index.d.ts @@ -1,97 +1,33 @@ -// Type definitions for Gamepad API -// Project: http://www.w3.org/TR/gamepad/ -// Definitions by: Kon +// Type definitions for gamepad 1.5 +// Project: https://github.com/creationix/node-gamepad#readme +// Definitions by: Alex Van Camp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Gamepad{ - /** - * This interface defines an individual gamepad device. - */ - export interface Gamepad{ - /** - * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. - * @readonly - */ - id:string; +import { EventEmitter } from 'events'; - /** - * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. - * @readonly - */ - index:number; +declare const nodeGamepad: NodeGamepad; +export = nodeGamepad; - /** - * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. - * @readonly - */ - timestamp:number; +interface NodeGamepad extends EventEmitter { + init(): void; + shutdown(): void; + numDevices(): number; + deviceAtIndex(deviceIndex: number): GamepadInstance; + detectDevices(): void; + processEvents(): void; - /** - * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. - * @readonly - */ - axes:number[]; - - /** - * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. - * @readonly - */ - buttons:GamepadButton[]; - - /** - * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. - * @readonly - */ - connected:boolean; - - /** - * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. - * @readonly - */ - mapping:string; - } - - /** - * - */ - export interface GamepadEvent extends Event{ - /** - * The single gamepad attribute provides access to the associated gamepad data for this event. - * @readonly - */ - gamepad:Gamepad; - } - - export interface GamepadList{ - [index: number]: Gamepad; - length: number; - } - - export interface GamepadButton{ - pressed: boolean; - value: number; - } - - /* - * @event gamepadconnected - * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. - */ - - /* - * @event gamepaddisconnected - * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. - */ + on(event: 'attach', listener: (deviceID: number, device: GamepadInstance) => void): this; + on(event: 'remove', listener: (deviceID: number) => void): this; + on(event: 'down' | 'up', listener: (deviceID: number, buttonID: number, timestamp: number) => void): this; + on(event: 'move', listener: (deviceID: number, axisID: number, value: number, lastValue: number, timestamp: number) => void): this; } -interface Navigator{ - /** - * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. - * @readonly - */ - getGamepads(): Gamepad.Gamepad[]; - - webkitGetGamepads(): Gamepad.GamepadList; - - // Not supported yet :( - // mozGetGamepads(): Gamepad[]; +interface GamepadInstance { + deviceID: number; + description: string; + vendorID: number; + productID: number; + axisStates: number[]; + buttonStates: boolean[]; } diff --git a/types/gamepad/tsconfig.json b/types/gamepad/tsconfig.json index 4cb63f3d80..39d007a909 100644 --- a/types/gamepad/tsconfig.json +++ b/types/gamepad/tsconfig.json @@ -2,13 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +20,4 @@ "index.d.ts", "gamepad-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gamepad/tslint.json b/types/gamepad/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/gamepad/tslint.json +++ b/types/gamepad/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/glue/v4/glue-tests.ts b/types/glue/v4/glue-tests.ts new file mode 100644 index 0000000000..1b67554725 --- /dev/null +++ b/types/glue/v4/glue-tests.ts @@ -0,0 +1,69 @@ +import * as glue from "glue"; +import * as hapi from "hapi"; + +const manifest: glue.Manifest = { + server: { + debug: false, + }, + connections: [ + { + port: 8000, + labels: ['web'] + }, + { + port: 8001, + labels: ['admin'] + } + ], + registrations: [ + { + plugin: { + register: './assets', + options: { + uglify: true + } + } + }, + { + plugin: './ui-user', + options: { + select: ['web'] + } + }, + { + plugin: { + register: './ui-admin', + options: { + sessiontime: 500 + } + }, + options: { + select: ['admin'], + routes: { + prefix: '/admin' + } + } + }, + { + plugin: { + register: require('./awesome-plugin.js'), + options: { + whyNot: true + } + } + }, + ] +}; + +const options: glue.Options = { + relativeTo: `${__dirname}/modules` +}; + +glue.compose(manifest, options, (err, server) => { + if (err) { + throw err; + } + server.start(() => { + console.log('hapi days!'); + }); +}); diff --git a/types/glue/v4/index.d.ts b/types/glue/v4/index.d.ts new file mode 100644 index 0000000000..69c7d56d01 --- /dev/null +++ b/types/glue/v4/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for glue 4.2 +// Project: https://github.com/hapijs/glue +// Definitions by: Greg Jednaszewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server, ServerConnectionOptions, ServerOptions } from "hapi"; + +export interface Options { + relativeTo: string; + preConnections?: (Server: Server, next: (err: any) => void) => void; + preRegister?: (Server: Server, next: (err: any) => void) => void; +} + +export interface Plugin { + plugin: string | { + register: string; + options?: any; + }; + options?: any; +} + +export interface Manifest { + server: ServerOptions; + connections: ServerConnectionOptions[]; + registrations?: Plugin[]; +} + +export function compose(manifest: Manifest, + options?: Options, + callback?: (err?: any, server?: Server) => void): Promise; diff --git a/types/glue/v4/tsconfig.json b/types/glue/v4/tsconfig.json new file mode 100644 index 0000000000..ead9b81629 --- /dev/null +++ b/types/glue/v4/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "boom": [ "boom/v4" ], + "catbox": [ "catbox/v7" ], + "hapi": [ "hapi/v16" ], + "glue": [ "glue/v4" ] + } + }, + "files": [ + "index.d.ts", + "glue-tests.ts" + ] +} diff --git a/types/glue/v4/tslint.json b/types/glue/v4/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/glue/v4/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/inquirer-npm-name/index.d.ts b/types/inquirer-npm-name/index.d.ts new file mode 100644 index 0000000000..bca64cd7ac --- /dev/null +++ b/types/inquirer-npm-name/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for inquirer-npm-name 3.0 +// Project: https://github.com/SBoudrias/inquirer-npm-name +// Definitions by: manuth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.3 + +import { Inquirer, Answers, Question } from "inquirer"; + +declare function askName(name: string | Question, inquirer: Inquirer): Promise<{ [key: string]: string }>; +export = askName; diff --git a/types/inquirer-npm-name/inquirer-npm-name-tests.ts b/types/inquirer-npm-name/inquirer-npm-name-tests.ts new file mode 100644 index 0000000000..aee1b039d7 --- /dev/null +++ b/types/inquirer-npm-name/inquirer-npm-name-tests.ts @@ -0,0 +1,13 @@ +import inquirer = require("inquirer"); +import askName = require("inquirer-npm-name"); + +// $ExpectType Promise<{ [key: string]: string; }> +askName("moduleName", inquirer); + +// $ExpectType Promise<{ [key: string]: string; }> +askName( + { + name: "moduleName", + message: "Whar's the name of your module?" + }, + inquirer); diff --git a/types/inquirer-npm-name/tsconfig.json b/types/inquirer-npm-name/tsconfig.json new file mode 100644 index 0000000000..99dee30a17 --- /dev/null +++ b/types/inquirer-npm-name/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", + "inquirer-npm-name-tests.ts" + ] +} diff --git a/types/inquirer-npm-name/tslint.json b/types/inquirer-npm-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/inquirer-npm-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/json-rpc-random-id/index.d.ts b/types/json-rpc-random-id/index.d.ts new file mode 100644 index 0000000000..14b5ba0ff0 --- /dev/null +++ b/types/json-rpc-random-id/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for json-rpc-random-id 1.0 +// Project: https://github.com/kumavis/json-rpc-random-id#readme +// Definitions by: Micah Riggan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Returns a function that generates a random number + * This number is to be used with web3 rpc + */ +declare function IdIterator(options?: { + max?: number; + start?: number; +}): () => number; + +export = IdIterator; diff --git a/types/json-rpc-random-id/json-rpc-random-id-tests.ts b/types/json-rpc-random-id/json-rpc-random-id-tests.ts new file mode 100644 index 0000000000..c71a7581e8 --- /dev/null +++ b/types/json-rpc-random-id/json-rpc-random-id-tests.ts @@ -0,0 +1,2 @@ +import jsonRPCRandomID = require("json-rpc-random-id"); +const generateId = jsonRPCRandomID(); diff --git a/types/json-rpc-random-id/tsconfig.json b/types/json-rpc-random-id/tsconfig.json new file mode 100644 index 0000000000..c39a0a4e2b --- /dev/null +++ b/types/json-rpc-random-id/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes":true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "json-rpc-random-id-tests.ts" + ] +} diff --git a/types/json-rpc-random-id/tslint.json b/types/json-rpc-random-id/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-rpc-random-id/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 4d9b1b25f5..5f9f3a7d6c 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Knex.js 0.14 +// Type definitions for Knex.js 0.15 // Project: https://github.com/tgriesser/knex // Definitions by: Qubo // Pablo Rodríguez @@ -14,13 +14,13 @@ import events = require("events"); import stream = require ("stream"); import Bluebird = require("bluebird"); -type Callback = Function; -type Client = Function; -type Value = string | number | boolean | Date | Array | Array | Array | Array | Buffer | Knex.Raw; -type ValueMap = { [key: string]: Value | Knex.QueryBuilder }; +type Callback = (...args: any[]) => void; +type Client = (...args: any[]) => void; +type Value = string | number | boolean | Date | string[] | number[] | Date[] | boolean[] | Buffer | Knex.Raw; +interface ValueMap { [key: string]: Value | Knex.QueryBuilder; } type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; type TableName = string | Knex.Raw | Knex.QueryBuilder; -type Identifier = { [alias: string]: string }; +interface Identifier { [alias: string]: string; } interface Knex extends Knex.QueryInterface { (tableName?: TableName | Identifier): Knex.QueryBuilder; @@ -29,7 +29,7 @@ interface Knex extends Knex.QueryInterface { raw: Knex.RawBuilder; transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; - destroy(callback: Function): void; + destroy(callback: (...args: any[]) => void): void; destroy(): Bluebird; batchInsert(tableName: TableName, data: any[], chunkSize?: number): Knex.QueryBuilder; schema: Knex.SchemaBuilder; @@ -39,7 +39,7 @@ interface Knex extends Knex.QueryInterface { migrate: Knex.Migrator; seed: any; fn: Knex.FunctionHelper; - on(eventName: string, callback: Function): Knex.QueryBuilder; + on(eventName: string, callback: (...args: any[]) => void): Knex.QueryBuilder; } declare function Knex(config: Knex.Config): Knex; @@ -138,18 +138,18 @@ declare namespace Knex { // Aggregation count(...columnNames: string[]): QueryBuilder; - count(columnName: Record | Knex.Raw): QueryBuilder; - countDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + count(columnName: Record | Raw): QueryBuilder; + countDistinct(columnName: string | Record | Raw): QueryBuilder; min(columnName: string, ...columnNames: string[]): QueryBuilder; - min(columnName: Record | Knex.Raw): QueryBuilder; + min(columnName: Record | Raw): QueryBuilder; max(columnName: string, ...columnNames: string[]): QueryBuilder; - max(columnName: Record | Knex.Raw): QueryBuilder; + max(columnName: Record | Raw): QueryBuilder; sum(columnName: string, ...columnNames: string[]): QueryBuilder; - sum(columnName: Record | Knex.Raw): QueryBuilder; - sumDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + sum(columnName: Record | Raw): QueryBuilder; + sumDistinct(columnName: string | Record | Raw): QueryBuilder; avg(columnName: string, ...columnNames: string[]): QueryBuilder; - avg(columnName: Record | Knex.Raw): QueryBuilder; - avgDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + avg(columnName: Record | Raw): QueryBuilder; + avgDistinct(columnName: string | Record | Raw): QueryBuilder; increment(columnName: string, amount?: number): QueryBuilder; decrement(columnName: string, amount?: number): QueryBuilder; @@ -180,11 +180,11 @@ declare namespace Knex { } interface Table { - (tableName: TableName | Identifier): QueryBuilder; - (callback: Function): QueryBuilder; - (raw: Raw): QueryBuilder; + // tslint:disable-next-line ban-types + (tableName: TableName | Identifier | Function | Raw): QueryBuilder; } + // tslint:disable-next-line no-empty-interface interface Distinct extends ColumnNameQueryBuilder { } @@ -258,7 +258,7 @@ declare namespace Knex { interface WithRaw { (alias: string, raw: Raw): QueryBuilder; - (alias: string, sql: string, bindings?: Value[] | Object): QueryBuilder; + (alias: string, sql: string, bindings?: Value[] | object): QueryBuilder; } interface WithSchema { @@ -273,7 +273,7 @@ declare namespace Knex { interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; (callback: QueryCallback): QueryBuilder; - (object: Object): QueryBuilder; + (object: object): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; @@ -318,8 +318,8 @@ declare namespace Knex { interface Union { (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; - (callbacks: (QueryCallback | QueryBuilder | Raw)[], wrap?: boolean): QueryBuilder; - (...callbacks: (QueryCallback | QueryBuilder | Raw)[]): QueryBuilder; + (callbacks: Array, wrap?: boolean): QueryBuilder; + (...callbacks: Array): QueryBuilder; // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; } @@ -339,8 +339,8 @@ declare namespace Knex { } interface RawQueryBuilder { - (sql: string, ...bindings: (Value | QueryBuilder)[]): QueryBuilder; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): QueryBuilder; + (sql: string, ...bindings: Array): QueryBuilder; + (sql: string, bindings: Array | ValueMap): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -352,8 +352,8 @@ declare namespace Knex { interface RawBuilder { (value: Value): Raw; - (sql: string, ...bindings: (Value | QueryBuilder)[]): Raw; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): Raw; + (sql: string, ...bindings: Array): Raw; + (sql: string, bindings: Array | ValueMap): Raw; } // @@ -367,7 +367,7 @@ declare namespace Knex { or: QueryBuilder; and: QueryBuilder; - //TODO: Promise? + // TODO: Promise? columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; @@ -375,7 +375,7 @@ declare namespace Knex { toSQL(): Sql; - on(event: string, callback: Function): QueryBuilder; + on(event: string, callback: (...args: any[]) => void): QueryBuilder; } interface Sql { @@ -398,6 +398,7 @@ declare namespace Knex { 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; + // tslint:disable-next-line no-unnecessary-generics pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; } @@ -444,25 +445,26 @@ declare namespace Knex { timestamp(columnName: string, standard?: boolean): ColumnBuilder; timestamps(useTimestampType?: boolean, makeDefaultNow?: boolean): ColumnBuilder; binary(columnName: string, length?: number): ColumnBuilder; - enum(columnName: string, values: Value[]): ColumnBuilder; - enu(columnName: string, values: Value[]): ColumnBuilder; + enum(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; + enu(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; json(columnName: string): ColumnBuilder; jsonb(columnName: string): ColumnBuilder; uuid(columnName: string): ColumnBuilder; comment(val: string): TableBuilder; specificType(columnName: string, type: string): ColumnBuilder; primary(columnNames: string[]): TableBuilder; - index(columnNames: (string | Raw)[], indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + index(columnNames: Array, indexName?: string, indexType?: string): TableBuilder; + unique(columnNames: Array, indexName?: string): TableBuilder; foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; foreign(columns: string[], foreignKeyName?: string): MultikeyForeignConstraintBuilder; dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropUnique(columnNames: Array, indexName?: string): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropIndex(columnNames: Array, indexName?: string): TableBuilder; dropTimestamps(): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface CreateTableBuilder extends TableBuilder { } @@ -472,9 +474,11 @@ declare namespace Knex { collate(val: string): CreateTableBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterTableBuilder extends TableBuilder { } + // tslint:disable-next-line no-empty-interface interface MySqlAlterTableBuilder extends AlterTableBuilder { } @@ -509,6 +513,7 @@ declare namespace Knex { inTable(tableName: string): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterColumnBuilder extends ColumnBuilder { } @@ -517,6 +522,11 @@ declare namespace Knex { after(columnName: string): AlterColumnBuilder; } + interface EnumOptions { + useNative: boolean; + enumName: string; + } + // // Configurations // @@ -650,10 +660,10 @@ declare namespace Knex { interface PoolConfig { name?: string; - create?: Function; - afterCreate?: Function; - destroy?: Function; - beforeDestroy?: Function; + create?: (...args: any[]) => void; + afterCreate?: (...args: any[]) => void; + destroy?: (...args: any[]) => void; + beforeDestroy?: (...args: any[]) => void; min?: number; max?: number; refreshIdle?: boolean; @@ -661,7 +671,7 @@ declare namespace Knex { reapIntervalMillis?: number; returnToHead?: boolean; priorityRange?: number; - validate?: Function; + validate?: (...args: any[]) => void; log?: boolean; // generic-pool v3 configs diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 193eea8cf6..1f22e08df0 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1,14 +1,15 @@ import Knex = require('knex'); +import { WriteStream } from 'fs'; // Initializing the Library -var knex = Knex({ +let knex = Knex({ client: 'sqlite3', connection: { filename: "./mydb.sqlite" } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -19,7 +20,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'pg', version: '9.5', @@ -33,7 +34,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mssql', connection: { @@ -47,7 +48,7 @@ var knex = Knex({ }); // Mariasql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mariasql', connection: { @@ -59,7 +60,7 @@ var knex = Knex({ }); // Mysql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -72,28 +73,24 @@ var knex = Knex({ }); // Pooling -var knex = Knex({ - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - pool: { - min: 0, - max: 7, - afterCreate: (connection: any, callback: Function) => { - return callback(null, connection); +knex = Knex({ + client: "mysql", + connection: { + host: "127.0.0.1", + user: "your_database_user", + password: "your_database_password", + database: "myapp_test" }, - beforeDestroy: (connection: any, callback: Function) => { - return callback(null, connection); + pool: { + min: 0, + max: 7, + afterCreate: (connection: any, callback: (...args: any[]) => void) => callback(null, connection), + beforeDestroy: (connection: any, callback: (...args: any[]) => void) => callback(null, connection) } - } }); // acquireConnectionTimeout -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -106,41 +103,41 @@ var knex = Knex({ }); // Pure Query Builder without a connection -var knex = Knex({}); +knex = Knex({}); // Pure Query Builder without a connection, using a specific flavour of SQL -var knex = Knex({ +knex = Knex({ client: 'pg' }); // searchPath -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: 'public', }); -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: ['public', 'private'], }); // postProcessResponse -var knex = Knex({ +knex = Knex({ client: 'pg', - postProcessResponse: function(result, queryContext){ + postProcessResponse(result, queryContext) { return result; } }); // wrapIdentifier -var knex = Knex({ +knex = Knex({ client: 'pg', - wrapIdentifier: function(value, origImpl, queryContext){ + wrapIdentifier(value, origImpl, queryContext) { return origImpl(value + 'foo'); } }); // useNullAsDefault -var knex = Knex({ +knex = Knex({ client: 'sqlite', useNullAsDefault: true, }); @@ -148,14 +145,14 @@ var knex = Knex({ // Using custom client class TestClient extends Knex.Client {} -var knex = Knex({ +knex = Knex({ client: TestClient, }); knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations -var knex = Knex({ +knex = Knex({ client: 'mysql', connection: { host : '127.0.0.1', @@ -176,7 +173,7 @@ knex.select('title', 'author', 'year').from('books'); knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); knex.select().table('books'); -knex.avg('sum_column1').from(function() { +knex.avg('sum_column1').from(() => { this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); }).as('ignored_alias'); @@ -208,20 +205,20 @@ knex('users').where(knex.raw('votes + 1'), '>', 101); knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); knex('users').where('votes', '>', knex.raw('100 + 1')); -var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); +let subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); knex('accounts').where('id', 'in', subquery); knex.select('name').from('users') .whereIn('id', [1, 2, 3]) .orWhereIn('id', [4, 5, 6]); -var subquery = knex.select('id').from('accounts'); +subquery = knex.select('id').from('accounts'); knex.select('name').from('users') .whereIn('account_id', subquery); knex('users') .where('name', '=', 'John') - .orWhere(function() { + .orWhere(() => { this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); }); @@ -233,13 +230,13 @@ knex('users').whereNull('updated_at'); knex('users').whereNotNull('created_at'); -knex('users').whereExists(function() { +knex('users').whereExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); -knex('users').whereNotExists(function() { +knex('users').whereNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); @@ -324,15 +321,15 @@ knex('users') .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) .select('users.id', 'contacts.phone'); -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { +knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function() { +knex.select('*').from('users').join('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { +knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { if (this !== join) { throw new Error("join() callback call semantics wrong"); } @@ -344,116 +341,116 @@ knex.select('*').from('user').join('contacts', () => { this.on('users.id', '=', knex.raw(7)); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); @@ -478,7 +475,7 @@ knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); -knex('users').innerJoin('accounts', function() { +knex('users').innerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -488,7 +485,7 @@ knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftJoin('accounts', function() { +knex.select('*').from('users').leftJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -505,13 +502,13 @@ knex.select('*').from('users').leftJoin('accounts', (join) => { knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftOuterJoin('accounts', function() { +knex.select('*').from('users').leftOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightJoin('accounts', function() { +knex.select('*').from('users').rightJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -521,13 +518,13 @@ knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightOuterJoin('accounts', function() { +knex.select('*').from('users').rightOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').outerJoin('accounts', function() { +knex.select('*').from('users').outerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -537,7 +534,7 @@ knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').fullOuterJoin('accounts', function() { +knex.select('*').from('users').fullOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -552,43 +549,42 @@ knex.select('*').from('accounts').joinRaw('natural full join table1').where('id' knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); knex.select('*').from('accounts') - .join(function() { + .join(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftJoin(function() { + .leftJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftOuterJoin(function() { + .leftOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightJoin(function() { + .rightJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightOuterJoin(function() { + .rightOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .innerJoin(function() { + .innerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .crossJoin(function() { + .crossJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .fullOuterJoin(function() { + .fullOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .outerJoin(function() { + .outerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); - knex('customers') .distinct('first_name', 'last_name') .select(); @@ -635,7 +631,7 @@ knex('accounts').where('activated', false).delete(); knex('accounts').where('activated', false).delete('id'); knex('accounts').where('activated', false).delete(['id', 'title']); -knex.with('old_books', function(qb) { +knex.with('old_books', (qb) => { qb.select('*').from('books').where('published_date', '<', 1970); }).select('*').from('old_books'); @@ -657,30 +653,30 @@ knex.withRaw('recent_books', 'select * from books where published_date >= :year' knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) .select('*').from('recent_books'); -knex.withWrapped("antique_books", function (qb) { +knex.withWrapped("antique_books", (qb) => { qb.select('*').from('books').where('published_date', '<', 1899); }).select('*').from('antique_books'); knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) .select('*').from('new_books'); -var someExternalMethod: Function; +const someExternalMethod: (...args: any[]) => void = () => {}; -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('books').transacting(trx).insert({name: 'Old Books'}) - .then(function(resp) { - var id = resp[0]; - return someExternalMethod(id, trx); + .then((resp) => { + const id = resp[0]; + someExternalMethod(id, trx); }) .then(trx.commit) .catch(trx.rollback); -}).then(function() { +}).then(() => { console.log('Transaction complete.'); -}).catch(function(err) { +}).catch((err) => { console.error(err); }); -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('tableName') .transacting(trx) .forUpdate() @@ -692,11 +688,13 @@ knex.transaction(function(trx) { .select('*'); }); -const transactionReturnValue = knex.transaction(function(trx) { +const transactionReturnValue = knex.transaction((trx) => { return knex("table") .insert({ foo: "bar" }) .returning(["id"]) - .then(function(result) { return result[0].id as number; }); + .then((result) => { + return result[0].id as number; + }); }); // Tests that the transaction has kept the type of its return value by referencing a method of number @@ -728,31 +726,30 @@ knex('accounts').where('userid', '=', 1).decrement('balance', 5); knex('accounts').truncate(); -knex.table('users').first('id').then(function(ids) { +knex.table('users').first('id').then((ids) => { console.log(ids); }); -knex.table('users').first('id', 'name').then(function(row) { +knex.table('users').first('id', 'name').then((row) => { console.log(row); }); -knex.table('users').first(knex.raw('round(sum(products)) as p')).then(function(row) { +knex.table('users').first(knex.raw('round(sum(products)) as p')).then((row) => { console.log(row); }); -knex.table('users').select('*').clearSelect().select('id').then(function(rows) { +knex.table('users').select('*').clearSelect().select('id').then((rows) => { console.log(rows); }); -knex('accounts').where('userid', '=', 1).clearWhere().select().then(function (rows) { +knex('accounts').where('userid', '=', 1).clearWhere().select().then((rows) => { console.log(rows); }); // Using trx as a query builder: -knex.transaction(function(trx) { - - var info: any; - var books: any[] = [ +knex.transaction((trx) => { + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -761,42 +758,41 @@ knex.transaction(function(trx) { return trx .insert({name: 'Old Books'}, 'id') .into('catalogues') - .then(function(ids) { - return Promise.all(books.map(function (book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. return trx.insert(info).into('books'); })); }); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); }); // Using trx as a transaction object: -knex.transaction<{ length: number }>(function(trx) { - +knex.transaction<{ length: number }>((trx) => { trx.raw(''); - trx.on('query-error', function(error: Error) { + trx.on('query-error', (error: Error) => { console.error(error); }); - trx.savepoint(function(nestedTrx) { + trx.savepoint((nestedTrx) => { nestedTrx.rollback(new Error('something went terribly wrong')); }); - trx.transaction(function(nestedTrx) { + trx.transaction((nestedTrx) => { nestedTrx.commit(); }); - var info: any; - var books: any[] = [ + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -805,8 +801,8 @@ knex.transaction<{ length: number }>(function(trx) { knex.insert({name: 'Old Books'}, 'id') .into('catalogues') .transacting(trx) - .then(function(ids) { - return Promise.all(books.map(function(book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. @@ -817,10 +813,10 @@ knex.transaction<{ length: number }>(function(trx) { .then(trx.commit) .catch(trx.rollback); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); @@ -831,7 +827,7 @@ knex.insert({ name: 'Old Books'}).transacting(undefined); knex.schema.withSchema("public").hasTable("table"); // $ExpectType Bluebird -knex.schema.createTable('users', function (table) { +knex.schema.createTable('users', (table) => { table.increments(); table.string('name'); table.enu('favorite_color', ['red', 'blue', 'green']); @@ -840,7 +836,7 @@ knex.schema.createTable('users', function (table) { table.timestamps(true, true); }); -knex.schema.alterTable('users', function (table) { +knex.schema.alterTable('users', (table) => { table.string('role').nullable(); }); @@ -848,9 +844,9 @@ knex.schema.renameTable('users', 'old_users'); knex.schema.dropTable('users'); -knex.schema.hasTable('users').then(function(exists) { +knex.schema.hasTable('users').then((exists) => { if (!exists) { - return knex.schema.createTable('users', function(t) { + return knex.schema.createTable('users', (t) => { t.increments('id').primary(); t.string('first_name', 100); t.string('last_name', 100); @@ -859,20 +855,20 @@ knex.schema.hasTable('users').then(function(exists) { } }); -var tableName: string; -var columnName: string; +const tableName = ''; +const columnName = ''; knex.schema.hasColumn(tableName, columnName); knex.schema.dropTableIfExists('users'); -knex.schema.table('users', function (table) { +knex.schema.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); }); knex.schema.raw("SET sql_mode='TRADITIONAL'") -.table('users', function (table) { +.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); @@ -888,12 +884,12 @@ knex('users') .orWhere(knex.raw('status <> ?', [1])) .groupBy('status'); -knex.raw('select * from users where id = ?', [1]).then(function(resp) { +knex.raw('select * from users where id = ?', [1]).then((resp) => { // ... }); (() => { - var subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') + const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') .wrap('(', ') avg_sal_dept'); knex.select('e.lastname', 'e.salary', subcolumn) @@ -902,7 +898,7 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { })(); (() => { - var subcolumn = knex.avg('salary') + const subcolumn = knex.avg('salary') .from('employee') .whereRaw('dept_no = e.dept_no') .as('avg_sal_dept'); @@ -912,70 +908,70 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { .whereRaw('dept_no = e.dept_no'); })(); -var x: number; +const x = 1; knex.select('name').from('users') .where('id', '>', 20) .andWhere('id', '<', 200) .limit(10) .offset(x) - .then(function(rows) { + .then((rows) => { return rows.map((r: any) => r.name); }) - .then(function(names: any) { + .then((names: any) => { return knex.select('id').from('nicknames').whereIn('nickname', names); }) - .then(function(rows) { + .then((rows) => { console.log(rows); }) - .catch(function(error) { + .catch((error) => { console.error(error); }); knex.select('*').from('users').where({name: 'Tim'}) - .then(function(rows) { + .then((rows) => { return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); - }).then(function(id) { + }).then((id) => { console.log('Inserted Account ' + id); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') - .catch(function(error) { + .catch((error) => { console.error(error); - }).then(function() { + }).then(() => { return knex.select('*').from('accounts').where('id', 1); - }).then(function(rows) { + }).then((rows) => { console.log(rows[0]); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); -var query: any; -query.then(function(x: any) { +const query: any = () => {}; +query.then((x: any) => { // doSideEffectsHere(x); return x; }); -knex.select('name').from('users').limit(10).then(function (rows: any[]): string[] { - return rows.map(function (row: any): string { +knex.select('name').from('users').limit(10).then((rows: any[]): string[] => { + return rows.map((row: any): string => { return row.name; }); -}).then(function(names: string[]) { +}).then((names: string[]) => { console.log(names); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); -knex.select('name').from('users').limit(10).then(function (rows: any[]) { - return rows.reduce(function(memo: any, row: any) { +knex.select('name').from('users').limit(10).then((rows: any[]) => { + return rows.reduce((memo: any, row: any) => { memo.names.push(row.name); memo.count++; return memo; }, {count: 0, names: []}); -}).then(function(obj: any) { +}).then((obj: any) => { console.log(obj); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); @@ -984,10 +980,10 @@ knex.select('name').from('users') .then(console.log.bind(console)) .catch(console.error.bind(console)); -var values: any[]; +const values: any[] = []; knex.insert(values).into('users') - .then(function() { + .then(() => { return {inserted: true}; }); @@ -998,36 +994,40 @@ knex.select('name').from('users') .offset(x); // Retrieve the stream: -var stream = knex.select('*').from('users').stream(); -var writableStream: NodeJS.WritableStream; +let stream = knex.select('*').from('users').stream(); +const writableStream: NodeJS.WritableStream = new WriteStream(); stream.pipe(writableStream); // With options: -var stream = knex.select('*').from('users').stream({highWaterMark: 5}); +stream = knex.select('*').from('users').stream({highWaterMark: 5}); stream.pipe(writableStream); // Use as a promise: (() => { - -var stream = knex.select('*').from('users').where(knex.raw('id = ?', [1])).stream(function(stream: any) { - stream.pipe(writableStream); -}).then(function() { - // ... -}).catch(function(e: Error) { - console.error(e); -}); - + knex + .select("*") + .from("users") + .where(knex.raw("id = ?", [1])) + .stream((stream: any) => { + stream.pipe(writableStream); + }) + .then(() => { + // ... + }) + .catch((e: Error) => { + console.error(e); + }); })(); -var stream = knex.select('*').from('users').pipe(writableStream); -var app: any; +stream = knex.select('*').from('users').pipe(writableStream); +const app: any = () => {}; knex.select('*') .from('users') - .on('query', function(data: any) { + .on('query', (data: any) => { app.log(data); }) - .then(function() { + .then(() => { // ... }); @@ -1040,66 +1040,66 @@ knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); // knex('users') .select('*') - .join('contacts', function(builder) { - this.on(function(builder) { + .join('contacts', (builder) => { + this.on((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).andOn(function(builder) { + }).andOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).orOn(function(builder) { + }).orOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).onExists(function(builder) { + }).onExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnExists(function(builder) { + }).orOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnExists(function(builder) { + }).andOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).onNotExists(function(builder) { + }).onNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnNotExists(function(builder) { + }).andOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnNotExists(function(builder) { + }).orOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; }); - }).where(function(builder) { + }).where((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhere(function(builder) { + }).orWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).andWhere(function(builder) { + }).andWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereIn('column', function(builder) { + }).whereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereIn('column', function(builder) { + }).orWhereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereNotIn('column', function(builder) { + }).whereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereNotIn('column', function(builder) { + }).orWhereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereWrapped(function(builder) { + }).whereWrapped((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).union(function(builder) { + }).union((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).unionAll(function(builder) { + }).unionAll((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).modify(function(builder, aBool) { + }).modify((builder, aBool) => { let self: Knex.QueryBuilder = this; self = builder; }, true); @@ -1107,7 +1107,7 @@ knex('users') // // Migrations // -var config = { +const config = { directory: "./migrations", extension: "js", tableName: "knex_migrations", @@ -1131,7 +1131,6 @@ knex.seed.make(name); knex.seed.run(config); knex.seed.run(); - knex.schema .dropTableIfExists('A') .createTable('A', table => { @@ -1142,21 +1141,20 @@ knex.schema table.timestamp('T', false).notNullable(); }); - -//creating table in MySQL with binary primary key with known field length -knex.schema.createTable('testTable', function (table) { - table.binary('binaryKey', 16).primary(); //will make table with binaryKey type BINARY(16) +// creating table in MySQL with binary primary key with known field length +knex.schema.createTable('testTable', (table) => { + table.binary('binaryKey', 16).primary(); // will make table with binaryKey type BINARY(16) }); // allow creating decimal column that can store that can store numbers of any // precision and scale. (Only supported for Oracle, SQLite, Postgres) -var knex = Knex({ +knex = Knex({ client: 'pg' }); knex.schema .dropTableIfExists('testTable') - .createTable('testTable', function (table) { + .createTable('testTable', (table) => { table.decimal('dec', null); }) .dropTable('testTable'); @@ -1165,10 +1163,10 @@ knex.schema knex.schema .dropTableIfExists('foo') .dropTableIfExists('bar') - .createTable('foo', function (table) { + .createTable('foo', (table) => { table.uuid('id').primary(); }) - .createTable('bar', function (table) { + .createTable('bar', (table) => { table.uuid('id').primary(); }); @@ -1194,12 +1192,12 @@ knex('characters') knex('characters') .select() - .whereIn('name', function() { + .whereIn('name', () => { this.select('name').from('characters'); }); knex('characters') .select() - .whereIn(['name', 'class'], function() { + .whereIn(['name', 'class'], () => { this.select('name', 'class').from('characters'); }); diff --git a/types/knex/tslint.json b/types/knex/tslint.json index d84fe24e60..604d5950cf 100644 --- a/types/knex/tslint.json +++ b/types/knex/tslint.json @@ -1,76 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "unified-signatures": false + "unified-signatures": false, + "callable-types": false } } diff --git a/types/lzma-native/index.d.ts b/types/lzma-native/index.d.ts new file mode 100644 index 0000000000..33165885da --- /dev/null +++ b/types/lzma-native/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for lzma-native 4.0 +// Project: https://github.com/addaleax/lzma-native +// Definitions by: Evan Cameron +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// + +import { Stream } from "stream"; +export interface LzmaOptions { + synchronous?: boolean; + bufsize?: number; + memlimit?: number; + check?: Check; + preset?: Preset; + flags?: + | "TELL_NO_CHECK" + | "TELL_UNSUPPORTED_CHECK" + | "TELL_ANY_CHECK" + | "CONCATENATED"; + threads?: number; + blockSize?: number; + timeout?: number; +} + +export type Check = + | "CHECK_CRC32" + | "CHECK_CRC64" + | "CHECK_NONE" + | "CHECK_SHA256"; + +export type Coders = + | "easyEncoder" + | "aloneDecoder" + | "rawEncoder" + | "autoDecoder" + | "aloneEncoder" + | "streamEncoder" + | "streamDecoder"; + +export type Preset = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + +export interface FileOptions { + fileSize: number; + memlimit?: number; + read: ( + count: number, + offset: number, + cb: (err: any, buffer: Buffer) => void + ) => void; +} + +export interface StreamInfo { + streamPadding: number; + memlimit: number; + streams: number; + blocks: number; + fileSize: number; + uncompressedSize: number; + checks: number; +} + +export function createStream( + coder: Coders, + options?: LzmaOptions +): JSLzmaStream; + +export function createCompressor(options?: LzmaOptions): JSLzmaStream; +export function createDecompressor(options?: LzmaOptions): JSLzmaStream; +export function crc32( + input: string, + encoding?: string, + previous?: number +): string; +export function isXZ(buf: Buffer | string): boolean; +export function versionString(): string; +export function versionNumber(): number; +export function checkSize(check: Check): number; +export function easyDecoderMemusage(preset: Preset): number; +export function easyEncoderMemusage(preset: Preset): number; +export function rawDecoderMemusage(preset: Preset): number; +export function rawEncoderMemusage(preset: Preset): number; + +export function Compressor( + preset?: Preset, + options?: LzmaOptions +): JSLzmaStream; +export function Decompressor(options?: LzmaOptions): JSLzmaStream; + +export function parseFileIndex( + options: FileOptions, + callback?: (err: any, info?: StreamInfo) => void +): void; +export function parseFileIndexFD( + fileDescriptor: number, + callback?: (err: any, info?: StreamInfo) => void +): void; + +export function compress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function decompress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function LZMA(): { + compress( + buf: Buffer | string, + mode: Preset, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; + decompress( + buf: Buffer | string, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; +}; + +export class JSLzmaStream extends Stream.Transform { + constructor(nativeStream: Stream, options: LzmaOptions); + bufsize(): number; + bufsize(size: number): void; + totalInt(): number; + totalOut(): number; + cleanUp(): void; +} diff --git a/types/lzma-native/lzma-native-tests.ts b/types/lzma-native/lzma-native-tests.ts new file mode 100644 index 0000000000..44a5eab221 --- /dev/null +++ b/types/lzma-native/lzma-native-tests.ts @@ -0,0 +1,55 @@ +import * as lzma from "lzma-native"; +import * as fs from "fs"; + +const compressor = lzma.createCompressor(); +const input = fs.createReadStream("tsconfig.json"); +const output = fs.createWriteStream("tsconfig.json.xz"); + +input.pipe(compressor).pipe(output); + +lzma.compress("Banana", undefined, result => { + console.log(result); // +}); + +lzma.compress("Bananas", 6, result => { + lzma.decompress(result, undefined, decompressedResult => { + console.log(decompressedResult.toString() === "Bananas"); + }); +}); + +lzma.LZMA().compress("Bananas", 4, result => { + lzma.LZMA().decompress(result, decompressedResult => { + console.log("Bananas" === decompressedResult.toString()); + }); +}); + +const comp = lzma.Compressor(); + +process.stdin.pipe(comp).pipe(process.stdout); +lzma.crc32("Banana"); // => 69690105 +lzma.checkSize("CHECK_SHA256"); // => 16 +lzma.checkSize("CHECK_CRC32"); // => 4 +lzma.easyDecoderMemusage(6); // => 8454192 +lzma.easyEncoderMemusage(6); // => 97620499 +lzma.versionString(); // => '5.2.3' +lzma.versionNumber(); // => 50020012 +lzma.isXZ("Banana"); // => false + +fs.open("test/hamlet.txt.xz", "r", (err: any, fd: number) => { + if (err) return; + // handle error + lzma.parseFileIndexFD(fd, (err, info) => { + // handle error + if (err) { + console.log(err); + } + // do something with e.g. info.uncompressedSize + + fs.close(fd, (err: any) => { + /* handle error */ + if (err) { + console.log(err); + } + }); + }); +}); diff --git a/types/lzma-native/tsconfig.json b/types/lzma-native/tsconfig.json new file mode 100644 index 0000000000..fa7667f123 --- /dev/null +++ b/types/lzma-native/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "lzma-native-tests.ts"] +} diff --git a/types/lzma-native/tslint.json b/types/lzma-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lzma-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-screenreader-trap/index.d.ts b/types/makeup-screenreader-trap/index.d.ts new file mode 100644 index 0000000000..0995b62a3c --- /dev/null +++ b/types/makeup-screenreader-trap/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-screenreader-trap 0.0 +// Project: https://github.com/makeup-js/makeup-screenreader-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function trap(el: HTMLElement): void; + +export function untrap(): void; diff --git a/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts new file mode 100644 index 0000000000..48b198ab2d --- /dev/null +++ b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts @@ -0,0 +1,9 @@ +import { trap, untrap } from 'makeup-screenreader-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +if (widgetEl) { + trap(widgetEl); +} + +untrap(); diff --git a/types/makeup-screenreader-trap/tsconfig.json b/types/makeup-screenreader-trap/tsconfig.json new file mode 100644 index 0000000000..08df420e11 --- /dev/null +++ b/types/makeup-screenreader-trap/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "makeup-screenreader-trap-tests.ts" + ] +} diff --git a/types/makeup-screenreader-trap/tslint.json b/types/makeup-screenreader-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-screenreader-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/markdown-it-anchor/index.d.ts b/types/markdown-it-anchor/index.d.ts index fc4cead6d4..39cb91be45 100644 --- a/types/markdown-it-anchor/index.d.ts +++ b/types/markdown-it-anchor/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Core, Token } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Core = require('markdown-it/lib/parser_core'); +import Token = require('markdown-it/lib/token'); declare namespace anchor { interface AnchorInfo { diff --git a/types/markdown-it-anchor/markdown-it-anchor-tests.ts b/types/markdown-it-anchor/markdown-it-anchor-tests.ts index 3570ba764b..a9a865a469 100644 --- a/types/markdown-it-anchor/markdown-it-anchor-tests.ts +++ b/types/markdown-it-anchor/markdown-it-anchor-tests.ts @@ -1,4 +1,4 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); import anchor = require("markdown-it-anchor"); const md = new MarkdownIt(); diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts index b0913972fa..2920f38f91 100644 --- a/types/markdown-it-container/index.d.ts +++ b/types/markdown-it-container/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Token, Renderer } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Renderer = require('markdown-it/lib/renderer'); +import Token = require('markdown-it/lib/token'); declare namespace markdownItContainer { interface ContainerOpts { diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts index 3c8f3bf980..e6754f82f3 100644 --- a/types/markdown-it-container/markdown-it-container-tests.ts +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -1,11 +1,13 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Token = require("markdown-it/lib/token"); + import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), - render: (tokens: MarkdownIt.Token[], index: number) => { + render: (tokens: Token[], index: number) => { const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); const onClick = "this.parentNode.classList.toggle('_expanded');" + diff --git a/types/markdown-it-lazy-headers/index.d.ts b/types/markdown-it-lazy-headers/index.d.ts index 0579118f80..43ac828764 100644 --- a/types/markdown-it-lazy-headers/index.d.ts +++ b/types/markdown-it-lazy-headers/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); declare function lazyheaders(md: MarkdownIt): void; diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 0948a6d353..e7d0ffa6e7 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -4,235 +4,5 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface MarkdownItStatic { - new (): MarkdownIt.MarkdownIt; - new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - new (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (): MarkdownIt.MarkdownIt; - (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; -} - -declare var MarkdownIt: MarkdownItStatic; +import MarkdownIt = require("./lib"); export = MarkdownIt; -export as namespace markdownit; - -declare module MarkdownIt { - interface MarkdownIt { - render(md: string, env?: any): string; - renderInline(md: string, env?: any): string; - parse(src: string, env: any): Token[]; - parseInline(src: string, env: any): Token[]; - - /* - // The following only works in 3.0 - // Since it's still not allowed to target 3.0, i'll leave the code commented out - - use = any[]>( - plugin: (md: MarkdownIt, ...params: T) => void, - ...params: T - ): MarkdownIt; - */ - - use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; - - utils: { - assign(obj: any): any; - isString(obj: any): boolean; - has(object: any, key: string): boolean; - unescapeMd(str: string): string; - unescapeAll(str: string): string; - isValidEntityCode(str: any): boolean; - fromCodePoint(str: string): string; - escapeHtml(str: string): string; - arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] - isSpace(str: any): boolean; - isWhiteSpace(str: any): boolean - isMdAsciiPunct(str: any): boolean; - isPunctChar(str: any): boolean; - escapeRE(str: string): string; - normalizeReference(str: string): string; - } - - disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - set(options: Options): MarkdownIt; - normalizeLink(url: string): string; - normalizeLinkText(url: string): string; - validateLink(url: string): boolean; - block: ParserBlock; - core: Core; - helpers: any; - inline: ParserInline; - linkify: LinkifyIt; - renderer: Renderer; - } - interface Options { - html?: boolean; - xhtmlOut?: boolean; - breaks?: boolean; - langPrefix?: string; - linkify?: boolean; - typographer?: boolean; - quotes?: string; - highlight?: (str: string, lang: string) => void; - } - interface LinkifyIt { - tlds(lang: string, linkified: boolean): void; - } - interface Renderer { - rules: { [name: string]: TokenRender }; - render(tokens: Token[], options: any, env: any): string; - renderAttrs(token: Token): string; - renderInline(tokens: Token[], options: any, env: any): string; - renderToken(tokens: Token[], idx: number, options: any): string; - } - interface Token { - new (type: string, tag: string, nesting: number): Token; - attrGet: (name: string) => string | null; - attrIndex: (name: string) => number; - attrJoin: (name: string, value: string) => void; - attrPush: (attrData: string[]) => void; - attrSet: (name: string, value: string) => void; - attrs: string[][]; - block: boolean; - children: Token[]; - content: string; - hidden: boolean; - info: string; - level: number; - map: number[]; - markup: string; - meta: any; - nesting: number; - tag: string; - type: string; - } - - type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; - - interface Rule { - (state: S, silent?: boolean): boolean | void; - } - - interface RuleInline extends Rule {} - interface RuleBlock extends Rule {} - - interface Ruler { - after(afterName: string, ruleName: string, rule: Rule, options?: any): void; - at(name: string, rule: Rule, options?: any): void; - before(beforeName: string, ruleName: string, rule: Rule, options?: any): void; - disable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enableOnly(rule: string, ignoreInvalid?: boolean): void; - getRules(chain: string): Rule[]; - push(ruleName: string, rule: Rule, options?: any): void; - } - - interface RulerInline extends Ruler {} - interface RulerBlock extends Ruler {} - - interface ParserBlock { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: RulerBlock; - } - - interface Core { - process(state: any): void; - ruler: Ruler; - } - - interface ParserInline { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - tokenize(state: State): void; - skipToken(state: State): void; - ruler: RulerInline; - ruler2: RulerInline; - } - - interface Delimiter { - close: boolean; - end: number; - jump: number; - length: number; - level: number; - marker: number; - open: boolean; - token: number; - } - - interface State { - env: any; - level: number; - - /** Link to parser instance */ - md: MarkdownIt; - - /** The markdown source code that is being parsed. */ - src: string; - - tokens: Token[]; - - /** Return any for a yet untyped property */ - [undocumented: string]: any; - } - - interface StateInline extends State { - /** - * Stores `{ start: end }` pairs. Useful for backtrack - * optimization of pairs parse (emphasis, strikes). - */ - cache: { [start: number]: number }; - - /** Emphasis-like delimiters */ - delimiters: Delimiter[]; - - pending: string; - pendingLevel: number; - - /** Index of the first character of this token. */ - pos: number; - - /** Index of the last character that can be used (for example the one before the end of this line). */ - posMax: number; - - /** - * Push new token to "stream". - * If pending text exists, flush it as text token. - */ - push(type: string, tag: string, nesting: number): Token; - - /** Flush pending text */ - pushPending(): Token; - - /** - * Scan a sequence of emphasis-like markers and determine whether - * it can start an emphasis sequence or end an emphasis sequence. - * @param start - position to scan from (it should point to a valid marker) - * @param canSplitWord - determine if these markers can be found inside a word - */ - scanDelims(start: number, canSplitWord: boolean): { - can_open: boolean, - can_close: boolean, - length: number - }; - } - - interface StateBlock extends State { - /** Used in lists to determine if they interrupt a paragraph */ - parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; - - eMarks: number[]; - bMarks: number[]; - bsCount: number[]; - sCount: number[]; - tShift: number[]; - - blkIndent: number; - ddIndent: number; - - line: number; - lineMax: number; - tight: boolean; - } -} diff --git a/types/markdown-it/lib/index.d.ts b/types/markdown-it/lib/index.d.ts new file mode 100644 index 0000000000..9a9caf37b6 --- /dev/null +++ b/types/markdown-it/lib/index.d.ts @@ -0,0 +1,113 @@ +import { LinkifyIt } from 'linkify-it' + +import State = require('./rules_core/state_core'); +import StateBlock = require('./rules_block/state_block'); +import StateInline = require('./rules_inline/state_inline'); + +import Core = require('./parser_core'); +import ParserBlock = require('./parser_block'); +import ParserInline = require('./parser_inline'); + +import Renderer = require('./renderer'); +import Ruler = require('./ruler'); +import Token = require('./token'); + +export = MarkdownIt; +export as namespace markdownit; + +declare const MarkdownIt: MarkdownItConstructor; + +interface MarkdownItConstructor { + new (): MarkdownIt; + new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt; + new (options: MarkdownIt.Options): MarkdownIt; + (): MarkdownIt; + (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt; + (options: MarkdownIt.Options): MarkdownIt; +} + +interface MarkdownIt { + render(md: string, env?: any): string; + renderInline(md: string, env?: any): string; + parse(src: string, env: any): Token[]; + parseInline(src: string, env: any): Token[]; + + /* + // The following only works in 3.0 + // Since it's still not allowed to target 3.0, i'll leave the code commented out + + use = any[]>( + plugin: (md: MarkdownIt, ...params: T) => void, + ...params: T + ): MarkdownIt; + */ + + use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; + + utils: { + assign(obj: any): any; + isString(obj: any): boolean; + has(object: any, key: string): boolean; + unescapeMd(str: string): string; + unescapeAll(str: string): string; + isValidEntityCode(str: any): boolean; + fromCodePoint(str: string): string; + escapeHtml(str: string): string; + arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] + isSpace(str: any): boolean; + isWhiteSpace(str: any): boolean + isMdAsciiPunct(str: any): boolean; + isPunctChar(str: any): boolean; + escapeRE(str: string): string; + normalizeReference(str: string): string; + } + + disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + set(options: MarkdownIt.Options): MarkdownIt; + normalizeLink(url: string): string; + normalizeLinkText(url: string): string; + validateLink(url: string): boolean; + block: ParserBlock; + core: Core; + helpers: any; + inline: ParserInline; + linkify: LinkifyIt; + renderer: Renderer; +} + +declare module MarkdownIt { + interface Options { + html?: boolean; + xhtmlOut?: boolean; + breaks?: boolean; + langPrefix?: string; + linkify?: boolean; + typographer?: boolean; + quotes?: string; + highlight?: (str: string, lang: string) => void; + } + + interface Rule { + (state: S, silent?: boolean): boolean | void; + } + + interface RuleInline extends Rule {} + interface RuleBlock extends Rule {} + + interface RulerInline extends Ruler {} + interface RulerBlock extends Ruler {} + + type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; + + interface Delimiter { + close: boolean; + end: number; + jump: number; + length: number; + level: number; + marker: number; + open: boolean; + token: number; + } +} diff --git a/types/markdown-it/lib/parser_block.d.ts b/types/markdown-it/lib/parser_block.d.ts new file mode 100644 index 0000000000..2efc76b858 --- /dev/null +++ b/types/markdown-it/lib/parser_block.d.ts @@ -0,0 +1,9 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = ParserBlock; + +declare class ParserBlock { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + ruler: MarkdownIt.RulerBlock; +} diff --git a/types/markdown-it/lib/parser_core.d.ts b/types/markdown-it/lib/parser_core.d.ts new file mode 100644 index 0000000000..a6559bdfef --- /dev/null +++ b/types/markdown-it/lib/parser_core.d.ts @@ -0,0 +1,10 @@ +import MarkdownIt = require("."); +import Ruler = require("./ruler"); +import Token = require("./token"); + +export = ParserCore; + +declare class ParserCore { + process(state: any): void; + ruler: Ruler; +} diff --git a/types/markdown-it/lib/parser_inline.d.ts b/types/markdown-it/lib/parser_inline.d.ts new file mode 100644 index 0000000000..ad7aa26d93 --- /dev/null +++ b/types/markdown-it/lib/parser_inline.d.ts @@ -0,0 +1,13 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); +import Token = require("./token"); + +export = ParserInline; + +declare class ParserInline { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + tokenize(state: State): void; + skipToken(state: State): void; + ruler: MarkdownIt.RulerInline; + ruler2: MarkdownIt.RulerInline; +} diff --git a/types/markdown-it/lib/renderer.d.ts b/types/markdown-it/lib/renderer.d.ts new file mode 100644 index 0000000000..0231dad0f9 --- /dev/null +++ b/types/markdown-it/lib/renderer.d.ts @@ -0,0 +1,12 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = Renderer; + +declare class Renderer { + rules: { [name: string]: MarkdownIt.TokenRender }; + render(tokens: Token[], options: any, env: any): string; + renderAttrs(token: Token): string; + renderInline(tokens: Token[], options: any, env: any): string; + renderToken(tokens: Token[], idx: number, options: any): string; +} diff --git a/types/markdown-it/lib/ruler.d.ts b/types/markdown-it/lib/ruler.d.ts new file mode 100644 index 0000000000..62ab55e3de --- /dev/null +++ b/types/markdown-it/lib/ruler.d.ts @@ -0,0 +1,15 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); + +export = Ruler; + +declare class Ruler { + after(afterName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + at(name: string, rule: MarkdownIt.Rule, options?: any): void; + before(beforeName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + disable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enableOnly(rule: string, ignoreInvalid?: boolean): void; + getRules(chain: string): MarkdownIt.Rule[]; + push(ruleName: string, rule: MarkdownIt.Rule, options?: any): void; +} diff --git a/types/markdown-it/lib/rules_block/state_block.d.ts b/types/markdown-it/lib/rules_block/state_block.d.ts new file mode 100644 index 0000000000..6eebab4202 --- /dev/null +++ b/types/markdown-it/lib/rules_block/state_block.d.ts @@ -0,0 +1,23 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateBlock; + +declare class StateBlock extends State { + /** Used in lists to determine if they interrupt a paragraph */ + parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; + + eMarks: number[]; + bMarks: number[]; + bsCount: number[]; + sCount: number[]; + tShift: number[]; + + blkIndent: number; + ddIndent: number; + + line: number; + lineMax: number; + tight: boolean; +} diff --git a/types/markdown-it/lib/rules_core/state_core.d.ts b/types/markdown-it/lib/rules_core/state_core.d.ts new file mode 100644 index 0000000000..7cf73134aa --- /dev/null +++ b/types/markdown-it/lib/rules_core/state_core.d.ts @@ -0,0 +1,20 @@ +import MarkdownIt = require(".."); +import Token = require("../token"); + +export = StateCore; + +declare class StateCore { + env: any; + level: number; + + /** Link to parser instance */ + md: MarkdownIt; + + /** The markdown source code that is being parsed. */ + src: string; + + tokens: Token[]; + + /** Return any for a yet untyped property */ + [undocumented: string]: any; +} diff --git a/types/markdown-it/lib/rules_inline/state_inline.d.ts b/types/markdown-it/lib/rules_inline/state_inline.d.ts new file mode 100644 index 0000000000..27938d99da --- /dev/null +++ b/types/markdown-it/lib/rules_inline/state_inline.d.ts @@ -0,0 +1,46 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateInline; + +declare class StateInline extends State { + /** + * Stores `{ start: end }` pairs. Useful for backtrack + * optimization of pairs parse (emphasis, strikes). + */ + cache: { [start: number]: number }; + + /** Emphasis-like delimiters */ + delimiters: MarkdownIt.Delimiter[]; + + pending: string; + pendingLevel: number; + + /** Index of the first character of this token. */ + pos: number; + + /** Index of the last character that can be used (for example the one before the end of this line). */ + posMax: number; + + /** + * Push new token to "stream". + * If pending text exists, flush it as text token. + */ + push(type: string, tag: string, nesting: number): Token; + + /** Flush pending text */ + pushPending(): Token; + + /** + * Scan a sequence of emphasis-like markers and determine whether + * it can start an emphasis sequence or end an emphasis sequence. + * @param start - position to scan from (it should point to a valid marker) + * @param canSplitWord - determine if these markers can be found inside a word + */ + scanDelims(start: number, canSplitWord: boolean): { + can_open: boolean, + can_close: boolean, + length: number + }; +} diff --git a/types/markdown-it/lib/token.d.ts b/types/markdown-it/lib/token.d.ts new file mode 100644 index 0000000000..1f71d54bfd --- /dev/null +++ b/types/markdown-it/lib/token.d.ts @@ -0,0 +1,23 @@ +export = Token; + +declare class Token { + constructor(type: string, tag: string, nesting: number); + attrGet: (name: string) => string | null; + attrIndex: (name: string) => number; + attrJoin: (name: string, value: string) => void; + attrPush: (attrData: string[]) => void; + attrSet: (name: string, value: string) => void; + attrs: string[][]; + block: boolean; + children: Token[]; + content: string; + hidden: boolean; + info: string; + level: number; + map: number[]; + markup: string; + meta: any; + nesting: number; + tag: string; + type: string; +} diff --git a/types/markdown-it/markdown-it-tests.ts b/types/markdown-it/markdown-it-tests.ts index f22fc5cb2d..343661ad87 100644 --- a/types/markdown-it/markdown-it-tests.ts +++ b/types/markdown-it/markdown-it-tests.ts @@ -1,4 +1,6 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Renderer = require("markdown-it/lib/renderer"); +import Token = require("markdown-it/lib/token"); { const md = new MarkdownIt(); @@ -141,7 +143,7 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { return ""; }, }); - md.renderer.rules["image"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["image"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { const token = tokens[index]; const aIndex = token.attrIndex("src"); token.attrs[aIndex][1]; @@ -154,11 +156,11 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { if (md.renderer.rules["link_open"]) { defaultLinkRender = md.renderer.rules["link_open"]; } else { - defaultLinkRender = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + defaultLinkRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { return self.renderToken(tokens, index, options); }; } - md.renderer.rules["link_open"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["link_open"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { tokens[index].attrPush(["target", "_blank"]); tokens[index].attrPush(["rel", "nofollow"]); return defaultLinkRender(tokens, index, options, env, self); diff --git a/types/module-deps/index.d.ts b/types/module-deps/index.d.ts new file mode 100644 index 0000000000..94706542a1 --- /dev/null +++ b/types/module-deps/index.d.ts @@ -0,0 +1,181 @@ +// Type definitions for module-deps 6.1 +// Project: https://github.com/browserify/module-deps +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as browserResolve from "browser-resolve"; + +/** + * Return an object transform stream 'd' that expects entry filenames or '{ id: ..., file: ... }' objects + * as input and produces objects for every dependency from a recursive module traversal as output. + */ +declare function moduleDeps(opts?: moduleDeps.Options): moduleDeps.ModuleDepsObject; + +/** + * Walk the dependency graph to generate json output that can be fed into browser-pack + */ +declare namespace moduleDeps { + /** + * module-deps constructor options + */ + interface Options { + /** + * A string or array of string transforms + */ + transform?: string | string[]; + + /** + * An array path of strings showing where to look in the package.json + * for source transformations. If falsy, don't look at the package.json at all + */ + transformKey?: string[]; + + /** + * Custom resolve function using the opts.resolve(id, parent, cb) signature that browser-resolve has + */ + resolve?: (id: string, opts: browserResolve.SyncOpts, cb: (err?: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => void) => void; + + /** + * A custom dependency detection function. opts.detect(source) should return an array of dependency module names. By default detective is used + */ + detect?: (source: string) => string[]; + + /** + * A function (id) to skip resolution of some module id strings. If defined, + * opts.filter(id) should return truthy for all the ids to include and falsey for all the ids to skip. + */ + filter?: (id: string) => boolean; + + /** + * A function (id, file, pkg) that gets called after id has been resolved. + * Return false to skip this file + */ + postFilter?: (id: string, file: string, pkg: PackageObject) => (void | boolean); // tslint:disable-line:void-return + + /** + * Transform the parsed package.json contents before using the values. + * opts.packageFilter(pkg, dir) should return the new pkg object to use. + */ + packageFilter?: (pkg: PackageObject, dir: string) => PackageObject; + + /** + * An array of absolute paths to not parse for dependencies. + * Use this for large dependencies like jquery or threejs which take forever to parse. + */ + noParse?: boolean | string[]; + + /** + * An object mapping filenames to file objects to skip costly io + */ + cache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to their parent package.json contents + * for browser fields, main entries, and transforms + */ + packageCache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to raw source to avoid reading from disk. + */ + fileCache?: { [fileName: string]: string }; + + /** + * A complex cache handler that allows async and persistent caching of data. + */ + persistentCache?: (file: string, id: string, pkg: PackageObject, fallback: (dataAsString: string, cb: CacheCallback) => void, cb: CacheCallback) => void; + + /** + * Array of global paths to search. Defaults to splitting on ':' in process.env.NODE_PATH + */ + paths?: string[]; + + /** + * Ignore files that failed to resolve + */ + ignoreMissing?: boolean; + + // un-documented options used by module-deps + basedir?: string; + globalTransform?: any[]; + extensions?: string[]; + modules?: { [name: string]: any }; + expose?: { [name: string]: string }; + + [prop: string]: any; + } + + interface ModuleDepsObject extends NodeJS.ReadWriteStream { + resolve(id: string, parent: { id: string }, cb: (err: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => any): any; + + readFile(file: string, id?: any, pkg?: PackageObject): NodeJS.ReadableStream; + + getTransforms(file: string, pkg: PackageObject, opts?: { builtin?: boolean; inNodeModules?: boolean }): NodeJS.ReadWriteStream; + + walk(id: string | { file: string; id: string; entry?: boolean; expose?: string; noparse?: boolean; source?: string }, + parent: { modules: any }, + cb: (err: Error | null, file?: string) => void): void; + + parseDeps(file: string, src: string, cb: any): any[]; + + lookupPackage(file: string, cb: (a: any, b: any, c?: any) => any): void; + + _isTopLevel(file: string): boolean; + _transform(row: string | InputRow | InputTransform, enc: string, next: () => void): void; + _flush(): void; + + /** + * Every time a transform is applied to a file, a 'transform' event fires with the instantiated transform stream tr. + */ + on(event: "transform", listener: (tr: any, file: string) => any): this; + /** + * Every time a file is read, this event fires with the file path. + */ + on(event: "file", listener: (file: string, id: string) => any): this; + /** + * When opts.ignoreMissing is enabled, this event fires for each missing package. + */ + on(event: "missing", listener: (id: string, parent: { id: string; filename: string; [prop: string]: any }) => any): this; + /** + * Every time a package is read, this event fires. The directory name of the package is available in pkg.__dirname. + */ + on(event: "package", listener: (package: PackageObject) => any): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + } + + type CacheCallback = (err: Error | null, res?: { source: string; package: any; deps: { [dep: string]: boolean } }) => void; + + interface InputRow { + file: string; + id: string; + entry?: boolean; + expose: string; + noparse?: boolean; + } + + interface InputTransform { + transform: string | (() => any); + options: any; + global?: boolean; + } + + interface TransformObject { + id: string; + file: string; + entry: boolean; + expose: string; + source: string; + deps: { [requireName: string]: any }; + } + + /** + * Placeholder, feel free to redefine or put in a pull request to improve + */ + interface PackageObject { + [prop: string]: any; + } +} + +export = moduleDeps; diff --git a/types/module-deps/module-deps-tests.ts b/types/module-deps/module-deps-tests.ts new file mode 100644 index 0000000000..e0930f8f88 --- /dev/null +++ b/types/module-deps/module-deps-tests.ts @@ -0,0 +1,95 @@ +import moduleDeps = require("module-deps"); + +function coreDepsTest() { + const coreDeps: { [prop: string]: any } = {}; + const coreModules = { + assert: "./assert.js", + buffer: "./buffer.js", + path: "./path.js" + }; + + const opts = { + resolve: () => { }, + modules: coreModules, + extensions: [".js", ".json"] + }; + + const s = moduleDeps(opts); + + s.on("data", (obj) => { + for (const dep of Object.keys(obj.deps)) { + if (dep in coreModules) { + coreDeps[dep] = true; + } + } + }); +} + +function rifiTest() { + const md = moduleDeps({ + resolve: (id, parent, cb) => { + const dependency = id.substr(1); + }, + transform: [], + globalTransform: [], + cache: {} + }); + + md.once("error", (err) => { + console.error(err); + }); +} + +function browserifyTest(opts: moduleDeps.Options) { + const packOpts: moduleDeps.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts["externalRequireName"] || "require", + hasExports: opts["hasExports"] || false, + prelude: opts["prelude"] || undefined, + preludePath: opts["preludePath"] || undefined, + raw: opts["raw"] || false, + sourceMapPrefix: opts["sourceMapPrefix"] || "//#", + standalone: opts["standalone"] || undefined, + standaloneModule: opts["standaloneModule"] || undefined, + }; + + const res = moduleDeps(); // 'opts' are optional + const res2 = moduleDeps(packOpts); + + // ensure return value is a stream + const res3 = res.pipe(res2); + + res.on("error", (err: any) => { + console.error("module-deps error: ", err); + }); + + const inst: moduleDeps.ModuleDepsObject = moduleDeps({ + expose: { id: "file.txt" }, + extensions: [ ".js", ".json" ], + transform: [], + transformKey: ["browserify", "transform"], + filter: (id) => { + if (opts.filter && !opts.filter(id)) return false; + if (["name"].indexOf(id) >= 0) return false; + return true; + }, + postFilter: (id, file, pkg) => { + console.log("postFilter", id, file, pkg); + }, + globalTransform: [], + modules: {}, + resolve: (id, parent, cb) => { + cb(null, "", {}); + } + }); + + inst.on("file", (file, id) => { + console.log("file", file, id); + }); + inst.on("package", (pkg) => { + console.log("package", pkg); + }); + inst.on("transform", (tr, file) => { + console.log("transform", tr, file); + }); +} diff --git a/types/module-deps/tsconfig.json b/types/module-deps/tsconfig.json new file mode 100644 index 0000000000..5dd4af3cc1 --- /dev/null +++ b/types/module-deps/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", + "module-deps-tests.ts" + ] +} \ No newline at end of file diff --git a/types/module-deps/tslint.json b/types/module-deps/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/module-deps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node-gamepad/index.d.ts b/types/node-gamepad/index.d.ts deleted file mode 100644 index 77570a5218..0000000000 --- a/types/node-gamepad/index.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Type definitions for node-gamepad 1.5 -// Project: https://github.com/creationix/node-gamepad#readme -// Definitions by: Alex Van Camp -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import { EventEmitter } from 'events'; - -declare const nodeGamepad: NodeGamepad; -export = nodeGamepad; - -interface NodeGamepad extends EventEmitter { - init(): void; - shutdown(): void; - numDevices(): number; - deviceAtIndex(deviceIndex: number): GamepadInstance; - detectDevices(): void; - processEvents(): void; - - on(event: 'attach', listener: (deviceID: number, device: GamepadInstance) => void): this; - on(event: 'remove', listener: (deviceID: number) => void): this; - on(event: 'down' | 'up', listener: (deviceID: number, buttonID: number, timestamp: number) => void): this; - on(event: 'move', listener: (deviceID: number, axisID: number, value: number, lastValue: number, timestamp: number) => void): this; -} - -interface GamepadInstance { - deviceID: number; - description: string; - vendorID: number; - productID: number; - axisStates: number[]; - buttonStates: boolean[]; -} diff --git a/types/node-gamepad/node-gamepad-tests.ts b/types/node-gamepad/node-gamepad-tests.ts deleted file mode 100644 index 1d2d24e788..0000000000 --- a/types/node-gamepad/node-gamepad-tests.ts +++ /dev/null @@ -1,69 +0,0 @@ -/// -import gamepad = require('node-gamepad'); - -// Initialize the library -gamepad.init(); - -// List the state of all currently attached devices -for (let i = 0, l = gamepad.numDevices(); i < l; i++) { - console.log(i, gamepad.deviceAtIndex(i)); -} - -// Create a game loop and poll for events -setInterval(gamepad.processEvents, 16); -// Scan for new gamepads as a slower rate -setInterval(gamepad.detectDevices, 500); - -// Listen for new gamepads being attached -gamepad.on('attach', (deviceID, device) => { - console.log('attach', { - deviceID, - device: { - deviceID: device.deviceID, - description: device.description, - vendorID: device.vendorID, - productID: device.productID, - axisStates: device.axisStates, - buttonStates: device.buttonStates, - } - }); -}); - -// Listen for new gamepads being removed -gamepad.on('remove', deviceID => { - console.log('remove', { - deviceID - }); -}); - -// Listen for button down events on all gamepads -gamepad.on('up', (deviceID, buttonID, timestamp) => { - console.log('up', { - deviceID, - buttonID, - timestamp - }); -}); - -// Listen for button down events on all gamepads -gamepad.on('down', (deviceID, buttonID, timestamp) => { - console.log('down', { - deviceID, - buttonID, - timestamp - }); -}); - -// Listen for move events on all gamepads -gamepad.on('move', (deviceID, axisID, value, lastValue, timestamp) => { - console.log('move', { - deviceID, - axisID, - value, - lastValue, - timestamp - }); -}); - -// Shutdown the library -gamepad.shutdown(); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 105062a56e..26631c8c1d 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1035,6 +1035,10 @@ declare namespace Office { * 12007 * A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time. * + * + * 12009 + * The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog. + * * * * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 4e52dd66a4..c7246ecb1f 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -7,6 +7,7 @@ // Alberto Restifo // Behind The Math // 3af +// Janne Liuhtonen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,7 +24,7 @@ export function parse(file: File, config?: ParseConfig): ParseResult; export function parse(stream: NodeJS.ReadableStream, config?: ParseConfig): ParseResult; -export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadableStream; +export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadWriteStream; /** * Unparses javascript data objects and returns a csv string diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 5db22091ca..57115dc0d5 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -9,6 +9,7 @@ import { ParseMeta, ParseResult } from "papaparse"; +import { Readable } from "stream"; /** * Parsing @@ -40,8 +41,19 @@ Papa.parse(file, { } }); +const readable = new Readable() +const rows = [ + "1,2,3", + "4,5,6" +] -Papa.parse(Papa.NODE_STREAM_INPUT); +rows.forEach(r => { + readable.push(r); +}); + +const papaStream: NodeJS.ReadWriteStream = Papa.parse(Papa.NODE_STREAM_INPUT); + +readable.pipe(papaStream); /** * Unparsing diff --git a/types/prosemirror-markdown/index.d.ts b/types/prosemirror-markdown/index.d.ts index 7af366c04e..91b37ea51e 100644 --- a/types/prosemirror-markdown/index.d.ts +++ b/types/prosemirror-markdown/index.d.ts @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; /** diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 8c099c2f89..851a778827 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ramda 0.26 +// Type definitions for ramda 0.25 // Project: https://github.com/donnut/typescript-ramda // Definitions by: Erwin Poeze // Tycho Grouwstra diff --git a/types/rc-time-picker/index.d.ts b/types/rc-time-picker/index.d.ts new file mode 100644 index 0000000000..62f6a7711a --- /dev/null +++ b/types/rc-time-picker/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for rc-time-picker 3.4 +// Project: http://github.com/react-component/time-picker +// Definitions by: Frithjof Winkelmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as moment from "moment"; +import * as React from 'react'; + +interface TimePickerProps { + prefixCls: string; + clearText: string; + disabled: boolean; + allowEmpty: boolean; + open: boolean; + defaultValue: moment.Moment; + defaultOpenValue: moment.Moment; + value: moment.Moment; + placeholder: string; + className: string; + id: string; + popupClassName: string; + showHour: boolean; + showMinute: boolean; + showSecond: boolean; + format: string; + disabledHours: () => number[]; + disabledMinutes: (hour: number) => number[]; + disabledSeconds: (hour: number, minute: number) => number[]; + use12Hours: boolean; + hideDisabledOptions: boolean; + onChange: (value: moment.Moment) => void; + addon: (timepicker: TimePicker) => JSX.Element; + placement: string; + transitionName: string; + onOpen: (state: { open: boolean }) => void; + onClose: (state: { open: boolean }) => void; + hourStep: number; + minuteStep: number; + secondStep: number; + focusOnOpen: boolean; + inputReadOnly: boolean; + inputIcon: React.ReactNode; + clearIcon: React.ReactNode; +} + +declare class TimePicker extends React.Component> { + constructor(props: Readonly>) + + close(): void; + isAM(): boolean; +} + +export = TimePicker; diff --git a/types/rc-time-picker/rc-time-picker-tests.tsx b/types/rc-time-picker/rc-time-picker-tests.tsx new file mode 100644 index 0000000000..7f0ea63e9c --- /dev/null +++ b/types/rc-time-picker/rc-time-picker-tests.tsx @@ -0,0 +1,10 @@ +import TimePicker from 'rc-time-picker'; +import * as React from 'react'; +import moment from 'moment'; + + {}} + placeholder={'Input time'} + showSecond={false} + onOpen={({open}: { open: boolean }) => {}}/>; diff --git a/types/rc-time-picker/tsconfig.json b/types/rc-time-picker/tsconfig.json new file mode 100644 index 0000000000..adda4c82bb --- /dev/null +++ b/types/rc-time-picker/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "rc-time-picker-tests.tsx" + ] +} diff --git a/types/rc-time-picker/tslint.json b/types/rc-time-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rc-time-picker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts index 3814b7f29f..6c94da77b0 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -1,110 +1,97 @@ -// Type definitions for react-alert 2.4 +// Type definitions for react-alert 4.0 // Project: https://github.com/schiehll/react-alert -// Definitions by: Steve Syrell +// Definitions by: Yue Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import * as React from 'react'; -export interface AlertContainerProps { - /** - * The offset of the alert from the page border, can be any number. - * - * Default: 14. - */ - offset: number; +export type AlertPosition = + | 'top left' + | 'top right' + | 'top center' + | 'bottom left' + | 'bottom right' + | 'bottom center'; - /** - * The position of the alert. Can be [bottom left, bottom right, top left, top right]. - * - * Default: 'bottom left' - */ - position: string; +export type AlertType = 'info' | 'success' | 'error'; +export type AlertTransition = 'fade' | 'scale'; +export interface ProviderOptions { /** - * The color theme of the alert. Can be [dark, light]. + * The margin of each alert * - * Default: 'dark' + * Default value: '10px' */ - theme: string; - + offset?: string; /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure - * (applies to all alerts). + * The position of the alerts in the page * - * Default: 5000 + * Default value: 'top center' */ - time: number; - + position?: AlertPosition; /** - * The transition animation. Can be [scale, fade]. + * Timeout to alert remove itself, if set to 0 it never removes itself * - * Default: 'scale' + * Default value: 0 */ - transition: string; + timeout?: number; + /** + * The default alert type used when calling this.props.alert.show + * + * Default value: 'info' + */ + type?: AlertType; + /** + * The transition animation + * + * Default value: 'fade' + */ + transition?: AlertTransition; + /** + * The z-index of alerts + * + * Default value: 100 + */ + zIndex?: number; } -export interface AlertShowOptions { - /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure. - */ - time?: number; +export class Provider extends React.Component {} - /** - * The icon to show in the alert. - * - * Default: the icon which matches the type of alert to be shown. - */ - icon?: React.ReactNode; +export const Alert: React.Consumer; +export interface AlertCustomOptions { /** - * A callback function that will be called when the alert is closed. + * Custom timeout just for this one alert */ - onClose?: () => void; - + timeout?: number; /** - * The type of alert to show. This will only be used when calling show(). - * Can be [info, success, error]. - * - * Default: 'info' + * Callback that will be executed after this alert open */ - type?: string; + onOpen?(): undefined; + /** + * Callback that will be executed after this alert is removed + */ + onClose?(): undefined; } -export default class AlertContainer extends React.Component { - /** - * Show a success alert. - * @returns The id of the created alert. - */ - success(message: string, options?: AlertShowOptions): string; - - /** - * Show an error alert. - * @returns The id of the created alert. - */ - error(message: string, options?: AlertShowOptions): string; - - /** - * Show an info alert. - * @returns The id of the created alert. - */ - info(message: string, options?: AlertShowOptions): string; - - /** - * Show an alert. - * @returns The id of the created alert. - */ - show(message: string, options?: AlertShowOptions): string; - - /** - * Remove all alerts from the page. - */ - removeAll(): void; - - /** - * Removes the alert with the specified id from the page. - */ - remove(id: string): void; +export interface AlertCustomOptionsWithType extends AlertCustomOptions { + type?: AlertType; } + +export interface InjectedAlertProp { + show( + message?: string, + options?: AlertCustomOptionsWithType + ): InjectedAlertProp; + remove(alert: InjectedAlertProp): undefined; + success(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + error(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + info(message?: string, options?: AlertCustomOptions): InjectedAlertProp; +} + +export function withAlert

( + c: React.ComponentType

+): React.ComponentType>>; diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx index 84686ea73d..c6088a52a8 100644 --- a/types/react-alert/react-alert-tests.tsx +++ b/types/react-alert/react-alert-tests.tsx @@ -1,48 +1,91 @@ -import * as React from "react"; -import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; +import * as React from 'react'; +import { + Provider as AlertProvider, + Alert, + withAlert, + AlertPosition, + AlertTransition, + ProviderOptions, + InjectedAlertProp +} from 'react-alert'; -export class ReactAlertTest extends React.Component { - private _alert: AlertContainer; +class AppWithoutAlert extends React.Component<{ alert: InjectedAlertProp }> { render() { - const props: AlertContainerProps = { - offset: 14, - position: "bottom left", - theme: "dark", - time: 5000, - transition: "scale" - }; + return ( + + ); + } +} + +const App = withAlert(AppWithoutAlert); + +class AppAlert extends React.Component { + render() { + return ( + + {alert => ( + + )} + + ); + } +} + +class AlertTemplate extends React.Component { + render() { + // the style contains only the margin given as offset + // options contains all alert given options + // message is the alert message... + // close is a function that closes the alert + const { style, options, message, close } = this.props; return ( -

- this._alert = a as AlertContainer} {...props} /> +
+ {options.type === 'info' && '!'} + {options.type === 'success' && ':)'} + {options.type === 'error' && ':('} + {message} +
); } +} - private _testMethods(): void { - const options: AlertShowOptions = { - time: 5000, - type: "info", - onClose: this._onAlertClosed, - icon: - }; +const options: ProviderOptions = { + position: 'bottom center' as AlertPosition, + timeout: 5000, + offset: '30px', + transition: 'scale' as AlertTransition +}; - let alertId: string; - alertId = this._alert.show("show without options"); - alertId = this._alert.show("show with options", options); - - alertId = this._alert.error("error without options"); - alertId = this._alert.error("error with options", options); - - alertId = this._alert.info("info without options"); - alertId = this._alert.info("info with options", options); +class Root extends React.Component { + render() { + return ( + + + + ); + } +} - alertId = this._alert.success("success without options"); - alertId = this._alert.success("success with options", options); - - this._alert.remove(alertId); - this._alert.removeAll(); +class RootAlert extends React.Component { + render() { + return ( + + + + ); } - - private _onAlertClosed(): void { } } diff --git a/types/react-alert/v2/index.d.ts b/types/react-alert/v2/index.d.ts new file mode 100644 index 0000000000..3814b7f29f --- /dev/null +++ b/types/react-alert/v2/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for react-alert 2.4 +// Project: https://github.com/schiehll/react-alert +// Definitions by: Steve Syrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface AlertContainerProps { + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + offset: number; + + /** + * The position of the alert. Can be [bottom left, bottom right, top left, top right]. + * + * Default: 'bottom left' + */ + position: string; + + /** + * The color theme of the alert. Can be [dark, light]. + * + * Default: 'dark' + */ + theme: string; + + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure + * (applies to all alerts). + * + * Default: 5000 + */ + time: number; + + /** + * The transition animation. Can be [scale, fade]. + * + * Default: 'scale' + */ + transition: string; +} + +export interface AlertShowOptions { + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure. + */ + time?: number; + + /** + * The icon to show in the alert. + * + * Default: the icon which matches the type of alert to be shown. + */ + icon?: React.ReactNode; + + /** + * A callback function that will be called when the alert is closed. + */ + onClose?: () => void; + + /** + * The type of alert to show. This will only be used when calling show(). + * Can be [info, success, error]. + * + * Default: 'info' + */ + type?: string; +} + +export default class AlertContainer extends React.Component { + /** + * Show a success alert. + * @returns The id of the created alert. + */ + success(message: string, options?: AlertShowOptions): string; + + /** + * Show an error alert. + * @returns The id of the created alert. + */ + error(message: string, options?: AlertShowOptions): string; + + /** + * Show an info alert. + * @returns The id of the created alert. + */ + info(message: string, options?: AlertShowOptions): string; + + /** + * Show an alert. + * @returns The id of the created alert. + */ + show(message: string, options?: AlertShowOptions): string; + + /** + * Remove all alerts from the page. + */ + removeAll(): void; + + /** + * Removes the alert with the specified id from the page. + */ + remove(id: string): void; +} diff --git a/types/react-alert/v2/react-alert-tests.tsx b/types/react-alert/v2/react-alert-tests.tsx new file mode 100644 index 0000000000..84686ea73d --- /dev/null +++ b/types/react-alert/v2/react-alert-tests.tsx @@ -0,0 +1,48 @@ +import * as React from "react"; +import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; + +export class ReactAlertTest extends React.Component { + private _alert: AlertContainer; + render() { + const props: AlertContainerProps = { + offset: 14, + position: "bottom left", + theme: "dark", + time: 5000, + transition: "scale" + }; + + return ( +
+ this._alert = a as AlertContainer} {...props} /> +
+ ); + } + + private _testMethods(): void { + const options: AlertShowOptions = { + time: 5000, + type: "info", + onClose: this._onAlertClosed, + icon: + }; + + let alertId: string; + alertId = this._alert.show("show without options"); + alertId = this._alert.show("show with options", options); + + alertId = this._alert.error("error without options"); + alertId = this._alert.error("error with options", options); + + alertId = this._alert.info("info without options"); + alertId = this._alert.info("info with options", options); + + alertId = this._alert.success("success without options"); + alertId = this._alert.success("success with options", options); + + this._alert.remove(alertId); + this._alert.removeAll(); + } + + private _onAlertClosed(): void { } +} diff --git a/types/react-alert/v2/tsconfig.json b/types/react-alert/v2/tsconfig.json new file mode 100644 index 0000000000..47de249c7e --- /dev/null +++ b/types/react-alert/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "react-alert": ["react-alert/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-alert-tests.tsx" + ] +} diff --git a/types/react-alert/v2/tslint.json b/types/react-alert/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alert/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-uuid-generator/index.d.ts b/types/react-native-uuid-generator/index.d.ts new file mode 100644 index 0000000000..ad5cb96bec --- /dev/null +++ b/types/react-native-uuid-generator/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-uuid-generator 4.0 +// Project: https://github.com/Traviskn/react-native-uuid-generator#readme +// Definitions by: burtek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace UUIDGenerator { + function getRandomUUID(): Promise; + function getRandomUUID(callback: (uuid: string) => void): void; +} + +export default UUIDGenerator; diff --git a/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts new file mode 100644 index 0000000000..b65f0ef410 --- /dev/null +++ b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts @@ -0,0 +1,5 @@ +import UUIDGenerator from 'react-native-uuid-generator'; + +UUIDGenerator.getRandomUUID().then((uuid: string) => { }).catch((error: any) => { }); + +UUIDGenerator.getRandomUUID((uuid: string) => { }); diff --git a/types/react-native-uuid-generator/tsconfig.json b/types/react-native-uuid-generator/tsconfig.json new file mode 100644 index 0000000000..30c1f52249 --- /dev/null +++ b/types/react-native-uuid-generator/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", + "react-native-uuid-generator-tests.ts" + ] +} diff --git a/types/react-native-uuid-generator/tslint.json b/types/react-native-uuid-generator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-uuid-generator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/scheduler/index.d.ts b/types/scheduler/index.d.ts new file mode 100644 index 0000000000..9df4054e8e --- /dev/null +++ b/types/scheduler/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for scheduler 0.10 +// Project: https://reactjs.org/ +// Definitions by: Nathan Bierema +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export interface Deadline { + timeRemaining(): number; + didTimeout: boolean; +} +export type FrameCallbackType = (deadline: Deadline) => FrameCallbackType | void; +export interface CallbackNode { + callback: FrameCallbackType; + priorityLevel: number; + expirationTime: number; + next: CallbackNode | null; + prev: CallbackNode | null; +} + +export const unstable_ImmediatePriority = 1; +export const unstable_UserBlockingPriority = 2; +export const unstable_NormalPriority = 3; +export const unstable_IdlePriority = 4; +export function unstable_runWithPriority(priorityLevel: number, eventHandler: () => T): T | undefined; +export function unstable_scheduleCallback(callback: FrameCallbackType, deprecated_options?: { timeout: number}): CallbackNode; +export function unstable_cancelCallback(callbackNode: CallbackNode): void; +export function unstable_wrapCallback(callback: FrameCallbackType): () => FrameCallbackType | undefined; +export function unstable_getCurrentPriorityLevel(): number; +export function unstable_now(): number; diff --git a/types/scheduler/scheduler-tests.ts b/types/scheduler/scheduler-tests.ts new file mode 100644 index 0000000000..84c35fb5b7 --- /dev/null +++ b/types/scheduler/scheduler-tests.ts @@ -0,0 +1,8 @@ +import { unstable_scheduleCallback, unstable_cancelCallback, unstable_now } from 'scheduler'; + +// $ExpectType CallbackNode +const callbackNode = unstable_scheduleCallback(() => {}, { timeout: 100 }); +unstable_cancelCallback(callbackNode); + +// $ExpectType number +unstable_now(); diff --git a/types/node-gamepad/tsconfig.json b/types/scheduler/tsconfig.json similarity index 93% rename from types/node-gamepad/tsconfig.json rename to types/scheduler/tsconfig.json index 7546894e6d..b6c5c6021a 100644 --- a/types/node-gamepad/tsconfig.json +++ b/types/scheduler/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "node-gamepad-tests.ts" + "scheduler-tests.ts" ] } diff --git a/types/scheduler/tslint.json b/types/scheduler/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/scheduler/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/terser/index.d.ts b/types/terser/index.d.ts new file mode 100644 index 0000000000..44a3e1cdb7 --- /dev/null +++ b/types/terser/index.d.ts @@ -0,0 +1,648 @@ +// Type definitions for terser 3.8 +// Project: https://github.com/terser-js/terser +// Definitions by: JordiAnderl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as MOZ_SourceMap from "source-map"; + +export interface Tokenizer { + /** + * The type of this token. + * "comment1" and "comment2" are for single-line, respectively multi-line comments. + */ + type: "num" | "string" | "regexp" | "operator" | "punc" | "atom" | "name" | "keyword" | "comment1" | "comment2"; + + /** + * The name of the file where this token originated from. Useful when compressing multiple files at once to generate the proper source map. + */ + file: string; + + /** + * The "value" of the token. + * That's additional information and depends on the token type: "num", "string" and "regexp" tokens you get their literal value. + * - For "operator" you get the operator. + * - For "punc" it's the punctuation sign (parens, comma, semicolon etc). + * - For "atom", "name" and "keyword" it's the name of the identifier + * - For comments it's the body of the comment (excluding the initial "//" and "/*". + */ + value: string; + + /** + * The line number of this token in the original code. + * 1-based index. + */ + line: number; + + /** + * The column number of this token in the original code. + * 0-based index. + */ + col: number; + + /** + * Short for "newline before", it's a boolean that tells us whether there was a newline before this node in the original source. It helps for automatic semicolon insertion. + * For multi-line comments in particular this will be set to true if there either was a newline before this comment, or * * if this comment contains a newline. + */ + nlb: boolean; + + /** + * This doesn't apply for comment tokens, but for all other token types it will be an array of comment tokens that were found before. + */ + comments_before: string[]; +} + +export class AST_Node { + // The first token of this node + start: AST_Node; + + // The last token of this node + end: AST_Node; + + value?: string | number; + file?: string; + property?: string; + key?: string; + + transform(tt: TreeTransformer): AST_Toplevel; + + walk(walker: TreeWalker): void; +} + +export class AST_Toplevel extends AST_Node { + // Terser contains a scope analyzer which figures out variable/function definitions, references etc. + // You need to call it manually before compression or mangling. + // The figure_out_scope method is defined only on the AST_Toplevel node. + figure_out_scope(): void; + + // Get names that are optimized for GZip compression (names will be generated using the most frequent characters first) + compute_char_frequency(): void; + + mangle_names(): void; + + print(stream: OutputStream): void; + + print_to_string(options?: BeautifierOptions): string; +} + +export interface MinifyOptions { + spidermonkey?: boolean; + outSourceMap?: string; + sourceRoot?: string; + inSourceMap?: string; + fromString?: boolean; + warnings?: boolean; + mangle?: boolean | MangleOptions; + output?: OutputOptions; + compress?: boolean | CompressOptions; + nameCache?: {}; +} + +export interface MinifyOutput { + code: string; + map: string; + warnings?: string[]; + error?: string; + ast?: boolean | AST_Toplevel; +} + +export function minify(files: {}, options?: MinifyOptions): MinifyOutput; + +export interface ParseOptions { + // Default is false + strict?: boolean; + + // Input file name, default is null + filename?: string; + + // Default is null + toplevel?: AST_Toplevel; +} +export interface CompressOptions { + /** Replace `arguments[index]` with function parameter name whenever possible. */ + arguments?: boolean; + /** Various optimizations for boolean context, for example `!!a ? b : c → a ? b : c` */ + booleans?: boolean; + /** Collapse single-use non-constant variables, side effects permitting. */ + collapse_vars?: boolean; + /** Apply certain optimizations to binary nodes, e.g. `!(a <= b) → a > b,` attempts to negate binary nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc */ + comparisons?: boolean; + /** Apply optimizations for `if-s` and conditional expressions. */ + conditionals?: boolean; + /** Remove unreachable code */ + dead_code?: boolean; + /** + * Pass `true` to discard calls to console.* functions. + * If you wish to drop a specific function call such as `console.info` and/or retain side effects from function + * arguments after dropping the function call then use `pure_funcs` instead. + */ + drop_console?: boolean; + /** Remove `debugger;` statements */ + drop_debugger?: boolean; + /** Attempt to evaluate constant expressions */ + evaluate?: boolean; + /** Pass `true` to preserve completion values from terminal statements without `return`, e.g. in bookmarklets. */ + expression?: boolean; + global_defs?: object; + /** hoist function declarations */ + hoist_funs?: boolean; + /** + * Hoist properties from constant object and array literals into regular variables subject to a set of constraints. + * For example: `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` works best with mangle enabled, + * the compress option passes set to 2 or higher, and the compress option toplevel enabled. + */ + hoist_props?: boolean; + /** Hoist var declarations (this is `false` by default because it seems to increase the size of the output in general) */ + hoist_vars?: boolean; + /** Optimizations for if/return and if/continue */ + if_return?: boolean; + /** + * Inline calls to function with simple/return statement + * - false -- same as `Disabled` + * - `Disabled` -- disabled inlining + * - `SimpleFunctions` -- inline simple functions + * - `WithArguments` -- inline functions with arguments + * - `WithArgumentsAndVariables` -- inline functions with arguments and variables + * - true -- same as `WithArgumentsAndVariables` + */ + inline?: boolean | InlineFunctions; + /** join consecutive `var` statements */ + join_vars?: boolean; + /** Prevents the compressor from discarding unused function arguments. You need this for code which relies on `Function.length` */ + keep_fargs?: boolean; + /** Pass true to prevent the compressor from discarding function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass true to prevent Infinity from being compressed into `1/0`, which may cause performance issues on `Chrome` */ + keep_infinity?: boolean; + /** Optimizations for `do`, `while` and `for` loops when we can statically determine the condition. */ + loops?: boolean; + /** negate `Immediately-Called Function Expressions` where the return value is discarded, to avoid the parens that the code generator would insert. */ + negate_iife?: boolean; + /** The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. */ + passes?: number; + /** Rewrite property access using the dot notation, for example `foo["bar"]` to `foo.bar` */ + properties?: boolean; + /** + * An array of names and UglifyJS will assume that those functions do not produce side effects. + * DANGER: will not check if the name is redefined in scope. + * An example case here, for instance `var q = Math.floor(a/b)`. + * If variable q is not used elsewhere, UglifyJS will drop it, but will still keep the `Math.floor(a/b)`, + * not knowing what it does. You can pass `pure_funcs: [ 'Math.floor' ]` to let it know that this function + * won't produce any side effect, in which case the whole statement would get discarded. The current + * implementation adds some overhead (compression will be slower). + */ + pure_funcs?: string[]; + pure_getters?: boolean | 'strict'; + /** + * Allows single-use functions to be inlined as function expressions when permissible allowing further optimization. + * Enabled by default. Option depends on reduce_vars being enabled. Some code runs faster in the Chrome V8 engine if + * this option is disabled. Does not negatively impact other major browsers. + */ + reduce_funcs?: boolean; + /** Improve optimization on variables assigned with and used as constant values. */ + reduce_vars?: boolean; + sequences?: boolean; + /** Pass false to disable potentially dropping functions marked as "pure". */ + side_effects?: boolean; + /** De-duplicate and remove unreachable `switch` branches. */ + switches?: boolean; + /** Drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables) */ + toplevel?: boolean; + /** Prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) */ + top_retain?: boolean; + typeofs?: boolean; + unsafe?: boolean; + /** Compress expressions like a `<= b` assuming none of the operands can be (coerced to) `NaN`. */ + unsafe_comps?: boolean; + /** Compress and mangle `Function(args, code)` when both args and code are string literals. */ + unsafe_Function?: boolean; + /** Optimize numerical expressions like `2 * x * 3` into `6 * x`, which may give imprecise floating point results. */ + unsafe_math?: boolean; + /** Optimize expressions like `Array.prototype.slice.call(a)` into `[].slice.call(a)` */ + unsafe_proto?: boolean; + /** Enable substitutions of variables with `RegExp` values the same way as if they are constants. */ + unsafe_regexp?: boolean; + unsafe_undefined?: boolean; + unused?: boolean; + /** display warnings when dropping unreachable code or unused declarations etc. */ + warnings?: boolean; +} + +export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 +} + +export interface MangleOptions { + /** Pass true to mangle names visible in scopes where `eval` or with are used. */ + eval?: boolean; + /** Pass true to not mangle function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass an array of identifiers that should be excluded from mangling. Example: `["foo", "bar"]`. */ + reserved?: string[]; + /** Pass true to mangle names declared in the top level scope. */ + toplevel?: boolean; + properties?: boolean | ManglePropertiesOptions; +} + +export interface ManglePropertiesOptions { + /** Use true to allow the mangling of builtin DOM properties. Not recommended to override this setting. */ + builtins?: boolean; + /** Mangle names with the original name still present. Pass an empty string "" to enable, or a non-empty string to set the debug suffix. */ + debug?: boolean; + /** Only mangle unquoted property names */ + keep_quoted?: boolean; + /** Pass a RegExp literal to only mangle property names matching the regular expression. */ + regex?: RegExp; + /** Do not mangle property names listed in the reserved array */ + reserved?: string[]; +} + +export interface OutputOptions { + ascii_only?: boolean; + beautify?: boolean; + braces?: boolean; + comments?: boolean | 'all' | 'some' | RegExp; + indent_level?: number; + indent_start?: boolean; + inline_script?: boolean; + keep_quoted_props?: boolean; + max_line_len?: boolean | number; + preamble?: string; + preserve_line?: boolean; + quote_keys?: boolean; + quote_style?: OutputQuoteStyle; + semicolons?: boolean; + shebang?: boolean; + webkit?: boolean; + width?: number; + wrap_iife?: boolean; +} + +export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 +} + +/** + * The parser creates a custom abstract syntax tree given a piece of JavaScript code. + * Perhaps you should read about the AST first. + */ +export function parse(code: string, options?: ParseOptions): AST_Toplevel; + +export interface BeautifierOptions { + /** + * Start indentation on every line (only when `beautify`) + */ + indent_start?: number; + + /** + * Indentation level (only when `beautify`) + */ + indent_level?: number; + + /** + * Quote all keys in {} literals? + */ + quote_keys?: boolean; + + /** + * Add a space after colon signs? + */ + space_colon?: boolean; + + /** + * Output ASCII-safe? (encodes Unicode characters as ASCII) + */ + ascii_only?: boolean; + + /** + * Escape " void): void; + + // This is used to output blocks in curly brackets. + // It'll print an open bracket at current point, then call newline() and with the next indentation level it calls your func. + // Lastly, it'll print an indented closing bracket. As usual, if beautification is off you'll just get {x} where x is whatever func outputs. + with_block(func: () => void): void; + + // Adds parens around the output that your function prints. + with_parens(func: () => void): void; + + // Adds square brackets around the output that your function prints. + with_square(func: () => void): void; + + // If options.source_map is set, this will generate a source mapping between the given token (which should be an AST_Token-like {}) and the current line/col. + // The name is optional; in most cases it will be inferred from the token. + add_mapping(token: AST_Node, name?: string): void; + + // Returns the option with the given name. + option(name: string): any; + + // Returns the current line in the output (1-based). + line(): number; + + // Returns the current column in the output (zero-based). + col(): number; + + // Push the given node into an internal stack. This is used to keep track of current node's parent(s). + push_node(node: AST_Node): void; + + // Pops the top of the stack and returns it. + pop_node(): AST_Node; + + // Returns that internal stack. + stack(): any; + + // Returns the n-th parent node (where zero means the direct parent). + parent(n: number): AST_Node; +} + +/** + * The code generator is a recursive process of getting back source code from an AST returned by the parser. + * Every AST node has a “print” method that takes an OutputStream and dumps the code from that node into it. + * The stream {} supports a lot of options that control the output. + * You can specify whether you'd like to get human-readable (indented) output, the indentation level, whether you'd like to quote all properties in {} literals etc. + */ +export function OutputStream(options?: BeautifierOptions): OutputStream; + +export interface SourceMapOptions { + /** + * The compressed file name + */ + file?: string; + + /** + * The root URL to the original sources + */ + root?: string; + + /** + * The input source map. + * Useful when you compress code that was generated from some other source (possibly other programming language). + * If you have an input source map, pass it in this argument and Terser will generate a mapping that maps back + * to the original source (as opposed to the compiled code that you are compressing). + */ + orig?: {} | JSON; +} + +export interface SourceMap { + add(source: string, gen_line: number, gen_col: number, orig_line: number, orig_col: number, name?: string): void; + get(): MOZ_SourceMap.SourceMapGenerator; + toString(): string; +} + +/** + * The output stream keeps track of the current line/column in the output and can trivially generate a source mapping to the original code via Mozilla's source-map library. + * To use this functionality, you must load this library (it's automatically require-d by Terser in the NodeJS version, but in a browser you must load it yourself) + * and make it available via the global MOZ_SourceMap variable. + */ +export function SourceMap(options?: SourceMapOptions): SourceMap; + +export interface CompressorOptions { + // Join consecutive statemets with the “comma operator” + sequences?: boolean; + + // Optimize property access: a["foo"] → a.foo + properties?: boolean; + + // Discard unreachable code + dead_code?: boolean; + + // Discard “debugger” statements + drop_debugger?: boolean; + + // Some unsafe optimizations (see below) + unsafe?: boolean; + + // Optimize if-s and conditional expressions + conditionals?: boolean; + + // Optimize comparisons + comparisons?: boolean; + + // Evaluate constant expressions + evaluate?: boolean; + + // Optimize boolean expressions + booleans?: boolean; + + // Optimize loops + loops?: boolean; + + // Drop unused variables/functions + unused?: boolean; + + // Hoist function declarations + hoist_funs?: boolean; + + // Hoist variable declarations + hoist_vars?: boolean; + + // Optimize if-s followed by return/continue + if_return?: boolean; + + // Join var declarations + join_vars?: boolean; + + // Try to cascade `right` into `left` in sequences + cascade?: boolean; + + // Drop side-effect-free statements + side_effects?: boolean; + + // Warn about potentially dangerous optimizations/code + warnings?: boolean; + + // Global definitions + global_defs?: {}; +} + +/** + * The compressor is a tree transformer which reduces the code size by applying various optimizations on the AST + */ +export function Compressor(options?: CompressorOptions): AST_Toplevel; + +// TODO: + +/** + * Terser provides a TreeWalker {} and every node has a walk method that given a walker will apply your visitor to each node in the tree. + * Your visitor can return a non-falsy value in order to prevent descending the current node. + */ +export class TreeWalker { + constructor(visitor: visitor); + parent: () => AST_Scope; + stack: AST_Scope[]; +} + +export type visitor = (node: AST_Node, descend: () => void) => boolean | void; + +// TODO: + +/** + * The tree transformer is a special case of a tree walker. + * In fact it even inherits from TreeWalker and you can use the same methods, but initialization and visitor protocol are a bit different. + */ +export class TreeTransformer extends TreeWalker { + constructor(visitor: visitor, after: visitor); +} + +// TODO: http://lisperator.net/uglifyjs/ast + +export class AST_PropAccess extends AST_Node { +} + +export class AST_ObjectKeyVal extends AST_Node { +} + +export class AST_Scope extends AST_Node { + find_variable(name: string): AST_SymbolDeclaration; +} + +export class AST_Symbol extends AST_Node { + scope?: AST_Scope; + name: string; + thedef: unknown; +} + +export class AST_SymbolDeclaration extends AST_Symbol { + orig: AST_SymbolDeclaration[]; + references: AST_SymbolRef[]; + global: boolean; + undeclared: boolean; + constant: boolean; + mangledName?: string; + mangled_name?: string; +} + +export class AST_SymbolRef extends AST_Symbol { +} + +export class AST_Call extends AST_Node { + expression: { name?: string, property?: string }; + args: AST_Node[]; +} +export class AST_String extends AST_Node { + value: string; +} +export class AST_Lambda extends AST_Node { + name?: string; +} +export class AST_SymbolMethod extends AST_Node { + name?: string; +} +export class AST_ConciseMethod extends AST_Node { +} +export class AST_SymbolVar extends AST_Node { + name?: string; +} diff --git a/types/terser/package.json b/types/terser/package.json new file mode 100644 index 0000000000..25c65e7595 --- /dev/null +++ b/types/terser/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "source-map": "*" + } +} diff --git a/types/terser/terser-tests.ts b/types/terser/terser-tests.ts new file mode 100644 index 0000000000..49b9190070 --- /dev/null +++ b/types/terser/terser-tests.ts @@ -0,0 +1,33 @@ +/// + +import { OutputQuoteStyle, minify } from 'terser'; + +let code: any; + +code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; + +minify(code); + +code = "function add(first, second) { return first + second; }"; +minify(code); + +minify(code); + +const output = minify(code, { + warnings: true, + mangle: { + properties: { + regex: /reg/ + } + }, + compress: { + arguments: true + } +}); + +if (output.warnings) { + output.warnings.filter(x => x === 'Dropping unused variable'); +} diff --git a/types/terser/tsconfig.json b/types/terser/tsconfig.json new file mode 100644 index 0000000000..937a5d1350 --- /dev/null +++ b/types/terser/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", + "terser-tests.ts" + ] +} diff --git a/types/terser/tslint.json b/types/terser/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/terser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 6530be5757..63bf98bcfe 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -22,6 +22,7 @@ // Methuselah96 // Dilip Ramirez // Julian Strecker +// Zhang Hao // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -33,7 +34,7 @@ export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; export * from "./three-ddsloader"; -export * from './three-dragcontrols'; +export * from "./three-dragcontrols"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; export * from "./three-examples"; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 66276bb1f4..6f0051404c 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1127,7 +1127,8 @@ export class EventDispatcher { export interface Event { type: string; - target: any; + target?: any; + [attachment: string]: any; } /** diff --git a/types/three/three-unrealbloompass.d.ts b/types/three/three-unrealbloompass.d.ts index dec35b3da7..ed58b853ac 100644 --- a/types/three/three-unrealbloompass.d.ts +++ b/types/three/three-unrealbloompass.d.ts @@ -22,6 +22,8 @@ export class UnrealBloomPass extends Pass { camera: OrthographicCamera; scene: Scene; quad: Mesh; + radius: number; + threshold: number; dispose(): void; getSeparableBlurMaterial(): ShaderMaterial; getCompositeMaterial(): ShaderMaterial; diff --git a/types/w3c-gamepad/index.d.ts b/types/w3c-gamepad/index.d.ts new file mode 100644 index 0000000000..bff1d30567 --- /dev/null +++ b/types/w3c-gamepad/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for W3C Gamepad API +// Project: http://www.w3.org/TR/gamepad/ +// Definitions by: Kon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Gamepad{ + /** + * This interface defines an individual gamepad device. + */ + export interface Gamepad{ + /** + * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. + * @readonly + */ + id:string; + + /** + * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. + * @readonly + */ + index:number; + + /** + * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. + * @readonly + */ + timestamp:number; + + /** + * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. + * @readonly + */ + axes:number[]; + + /** + * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. + * @readonly + */ + buttons:GamepadButton[]; + + /** + * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. + * @readonly + */ + connected:boolean; + + /** + * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. + * @readonly + */ + mapping:string; + } + + /** + * + */ + export interface GamepadEvent extends Event{ + /** + * The single gamepad attribute provides access to the associated gamepad data for this event. + * @readonly + */ + gamepad:Gamepad; + } + + export interface GamepadList{ + [index: number]: Gamepad; + length: number; + } + + export interface GamepadButton{ + pressed: boolean; + value: number; + } + + /* + * @event gamepadconnected + * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. + */ + + /* + * @event gamepaddisconnected + * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. + */ +} + +interface Navigator{ + /** + * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. + * @readonly + */ + getGamepads(): Gamepad.Gamepad[]; + + webkitGetGamepads(): Gamepad.GamepadList; + + // Not supported yet :( + // mozGetGamepads(): Gamepad[]; +} diff --git a/types/w3c-gamepad/tsconfig.json b/types/w3c-gamepad/tsconfig.json new file mode 100644 index 0000000000..e8a490bcf2 --- /dev/null +++ b/types/w3c-gamepad/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-gamepad-tests.ts" + ] +} diff --git a/types/w3c-gamepad/tslint.json b/types/w3c-gamepad/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/w3c-gamepad/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/w3c-gamepad/w3c-gamepad-tests.ts b/types/w3c-gamepad/w3c-gamepad-tests.ts new file mode 100644 index 0000000000..af3095adb0 --- /dev/null +++ b/types/w3c-gamepad/w3c-gamepad-tests.ts @@ -0,0 +1,70 @@ + + + +()=>{ + function runAnimation() + { + window.requestAnimationFrame(runAnimation); + + var gamepads = navigator.getGamepads(); + + for (var i = 0; i < gamepads.length; ++i) + { + var pad = gamepads[i]; + // todo; simple demo of displaying pad.axes and pad.buttons + } + } + + window.requestAnimationFrame(runAnimation); +}; + +(()=>{ + var gamepadconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + if(e.gamepad.mapping == 'standard'){ + console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); + } + }; + var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }; + + window.addEventListener('GamepadConnected', gamepadconnected, false); + window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('webkitGamepadConnected', gamepadconnected, false); + window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('mozGamepadConnected', gamepadconnected, false); + window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); + + var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; + var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; + if(getGamepads){ + function runAnimation() + { + requestAnimationFrame.call(window, runAnimation); + + var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); + for(var i = 0; i < gamepads.length; i++){ + var pad: Gamepad.Gamepad = gamepads[i]; + if(pad && pad.connected){ + for (var k = 0; k < pad.buttons.length; k++) + { + var button: Gamepad.GamepadButton = pad.buttons[k]; + if(button.pressed){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); + } + } + for (var k = 0; k < pad.axes.length; k++) + { + var axis = pad.axes[k]; + if(Math.abs(axis) > 0.1){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); + } + } + } + } + } + + runAnimation(); + } +})(); \ No newline at end of file diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 99bc9ffa09..94974500eb 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -50,15 +50,15 @@ declare namespace wx { header?: RequestHeader; /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ method?: - | "GET" - | "OPTIONS" - | "GET" - | "HEAD" - | "POST" - | "PUT" - | "DELETE" - | "TRACE" - | "CONNECT"; + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE" + | "TRACE" + | "CONNECT"; /** 如果设为json,会尝试对返回的数据做一次 JSON.parse */ dataType?: string; /** @@ -289,9 +289,7 @@ declare namespace wx { * 需要用户授权 scope.writePhotosAlbum * @version 1.2.0 */ - function saveImageToPhotosAlbum( - options: SaveImageToPhotosAlbumOptions - ): void; + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; // 媒体-----录音 interface StartRecordAudioOptions extends BaseOptions { /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ @@ -387,13 +385,9 @@ declare namespace wx { /** 录音恢复事件 */ onResume(callback?: () => void): void; /** 录音停止事件,会回调文件地址 */ - onStop( - callback?: (options: OnRecorderManagerStopOptions) => void - ): void; + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ - onFrameRecorded( - callback?: (options: OnFrameRecordedOptions) => void - ): void; + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; /** 录音错误事件, 会回调错误信息 */ onError(callback?: (err: ErrMsgResponse) => void): void; } @@ -1066,9 +1060,7 @@ declare namespace wx { /** * 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 wx.openLocation */ - getCenterLocation( - options: GetCenterLocationOptions - ): OpenLocationOptions; + getCenterLocation(options: GetCenterLocationOptions): OpenLocationOptions; /** * 将地图中心移动到当前定位点,需要配合map组件的show-location使用 */ @@ -3294,13 +3286,13 @@ declare namespace wx { // 开放接口-----设置 interface AuthSetting { scope: - | "scope.userInfo" - | "scope.userLocation" - | "scope.address" - | "scope.invoiceTitle" - | "scope.werun" - | "scope.record" - | "scope.writePhotosAlbum"; + | "scope.userInfo" + | "scope.userLocation" + | "scope.address" + | "scope.invoiceTitle" + | "scope.werun" + | "scope.record" + | "scope.writePhotosAlbum"; success?(res: ErrMsgResponse): void; fail?(): void; complete?(): void; @@ -3490,10 +3482,10 @@ declare namespace wx { } interface BuiltInEvent - extends BaseEvent { } + extends BaseEvent {} interface CustomEvent - extends BaseEvent { } + extends BaseEvent {} /** * 指定focus时的光标位置 @@ -3501,22 +3493,22 @@ declare namespace wx { */ interface InputEvent extends BuiltInEvent< - "input", - { - value: string; - cursor: number; - } - > { } + "input", + { + value: string; + cursor: number; + } + > {} interface FormEvent extends BuiltInEvent< - "form", - { - value: { [name: string]: string | boolean | number }; - } - > { } + "form", + { + value: { [name: string]: string | boolean | number }; + } + > {} - interface ScrollEvent extends BuiltInEvent<"scroll", {}> { } + interface ScrollEvent extends BuiltInEvent<"scroll", {}> {} interface Touch { identifier: number; @@ -3528,12 +3520,12 @@ declare namespace wx { interface TouchEvent extends BuiltInEvent< - T, - { - x: number; - y: number; - } - > { + T, + { + x: number; + y: number; + } + > { touches: Touch[]; changedTouches: Touch[]; } @@ -3616,6 +3608,30 @@ declare namespace wx { enableDebug: boolean; } // #region App里的onLaunch、onShow回调参数 + + // #region Account + interface AccountInfo { + /* 小程序账号信息 */ + miniProgram: { + /*小程序 appId */ + appId: string; + }; + /* 插件账号信息(仅在插件中调用时包含这一项) */ + plugin?: { + /* 插件 appId */ + appId: string; + /* 插件版本号 */ + version: string; + }; + } + + /** + * 获取当前账号信息 + * @version >= 2.2.2 + */ + function getAccountInfoSync(): AccountInfo; + // #endregion + /** * App 实现的接口对象 * 开发者可以添加任意的函数或数据到 Object 参数中,用 this 可以访问 @@ -3673,8 +3689,7 @@ declare namespace wx { Data, Methods, Props - > = CombinedInstance & - Component; + > = CombinedInstance & Component; // CombinedInstance models the `this`, i.e. instance type for (user defined) component type CombinedInstance< @@ -3682,9 +3697,9 @@ declare namespace wx { Data, Methods, Props - > = Methods & Instance; + > = Methods & Instance; - type Prop = (() => T) | { new(...args: any[]): T & object }; + type Prop = (() => T) | { new (...args: any[]): T & object }; type PropValidator = PropOptions | Prop | Array>; @@ -3705,9 +3720,7 @@ declare namespace wx { type ArrayPropsDefinition = Array; - type PropsDefinition = - | ArrayPropsDefinition - | RecordPropsDefinition; + type PropsDefinition = ArrayPropsDefinition | RecordPropsDefinition; interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ @@ -3726,7 +3739,7 @@ declare namespace wx { Data, Methods, Props - > = object & + > = object & ComponentOptions Data), Methods, Props> & ThisType>>; @@ -3789,7 +3802,7 @@ declare namespace wx { Data = DefaultData, Methods = DefaultMethods, Props = PropsDefinition - > extends Partial { + > extends Partial { /** * 组件的对外属性,是属性名到属性设置的映射表 * 属性设置中可包含三个字段: @@ -3841,9 +3854,7 @@ declare namespace wx { * 类似于mixins和traits的组件间代码复用机制 * 参见 [behaviors](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/behaviors.html) */ - behaviors?: Array< - (ComponentOptions>) | string - >; + behaviors?: Array<(ComponentOptions>) | string>; /** * 组件生命周期声明对象,组件的生命周期:created、attached、ready、moved、detached将收归到lifetimes字段内进行声明, @@ -3914,13 +3925,13 @@ declare namespace wx { setData( data: { [key in keyof D]?: - | string - | number - | boolean - | symbol - | object - | null - | any[] + | string + | number + | boolean + | symbol + | object + | null + | any[] }, callback?: () => void ): void; @@ -4087,25 +4098,22 @@ declare namespace wx { /** * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ - referrerInfo: object; - /** - * 来源小程序或公众号或App的 appId,详见下方说明 - */ - "referrerInfo.appId": string; - /** - * 来源小程序传过来的数据,scene=1037或1038时支持 - */ - "referrerInfo.extraData": object; + referrerInfo: { + /* 来源小程序或公众号或App的 appId,详见下方说明 */ + appId: string; + /* 来源小程序传过来的数据,scene=1037或1038时支持 */ + extraData: object; + }; // #endregion } // 云开发 // 文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html - interface cloud { + interface Cloud { /** * 初始化方法(全局只需一次) */ - init: (options: initCloudOptions) => void; + init: (options: InitCloudOptions) => void; /** * 接受一个可选对象参数 env:环境 ID,获取数据库的引用 */ @@ -4118,12 +4126,12 @@ declare namespace wx { /** * 定义了云开发的默认配置,该配置会作为之后调用其他所有云 API 的默认配置 */ - interface initCloudOptions { + interface InitCloudOptions { /** * 默认环境配置,传入字符串形式的环境 ID 可以指定所有服务的默认环境,传入对象 initCloudEnvOptions 可以分别指定各个服务的默认环境 * 默认值: default */ - env?: string | initCloudEnvOptions; + env?: string | InitCloudEnvOptions; /** * 是否在将用户访问记录到用户管理中,在控制台中可见 * 默认值: false @@ -4133,7 +4141,7 @@ declare namespace wx { /** * initCloudOptions 的 env 参数,可以指定各个服务的默认环境 */ - interface initCloudEnvOptions { + interface InitCloudEnvOptions { /** * 数据库 API 默认环境配置 * 默认值: default @@ -4171,7 +4179,7 @@ declare function Component( D, M, P - > + > ): wx.ExtendedComponent, D, M, P>; /** * behaviors 是用于组件间代码共享的特性 @@ -4187,7 +4195,7 @@ declare function Behavior( D, M, P - > + > ): wx.ExtendedComponent, D, M, P>; // #endregion // #region Page diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index cacdeaee70..7333dce911 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -469,3 +469,8 @@ wx.getSystemInfo({ } = res; } }); + +function testAccountInfo(): string { + const accountInfo: wx.AccountInfo = wx.getAccountInfoSync(); + return accountInfo.miniProgram.appId; +}