diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 32267be127..5121e1095e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3012,7 +3012,7 @@ /types/node/v7/ @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry /types/node/v8/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 @n-e @brunoscheufler @KSXGitHub @islishude @r3nya /types/node/v9/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @eyqs -/types/node/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @ZaneHannanAU @ThomasdenH @eyqs @matthieusieben +/types/node/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @ZaneHannanAU @ThomasdenH @eyqs /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts index 77fe716390..1120b50be8 100644 --- a/types/aframe/test/aframe-io-tests.ts +++ b/types/aframe/test/aframe-io-tests.ts @@ -533,9 +533,10 @@ AFRAME.registerComponent('audioanalyser-waveform', { rings.forEach(function transformRing(ring: THREE.Line, index: number) { var normLevel; normLevel = levels[RINGCOUNT - index - 1] + 0.01; // Avoid scaling by 0. - (ring.material as THREE.LineBasicMaterial).color.setHSL(colors[index], 1, normLevel); - ring.material.linewidth = normLevel * 3; - ring.material.opacity = normLevel; + const lineMaterial = ring.material as THREE.LineBasicMaterial; + lineMaterial.color.setHSL(colors[index], 1, normLevel); + lineMaterial.linewidth = normLevel * 3; + lineMaterial.opacity = normLevel; ring.scale.z = normLevel; }); }, diff --git a/types/amqplib/tslint.json b/types/amqplib/tslint.json index bfc9508c49..f64a783725 100644 --- a/types/amqplib/tslint.json +++ b/types/amqplib/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { // All are TODOs + "no-any-union": false, "no-empty-interface": false, "prefer-const": false } diff --git a/types/angular-pdfjs-viewer/tsconfig.json b/types/angular-pdfjs-viewer/tsconfig.json index bdae87bf50..05a851782e 100644 --- a/types/angular-pdfjs-viewer/tsconfig.json +++ b/types/angular-pdfjs-viewer/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/angular-q-extras/tsconfig.json b/types/angular-q-extras/tsconfig.json index 3047a809eb..973131f033 100644 --- a/types/angular-q-extras/tsconfig.json +++ b/types/angular-q-extras/tsconfig.json @@ -6,7 +6,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/apollo-codegen/index.d.ts b/types/apollo-codegen/index.d.ts index ea5d415418..4309db4116 100644 --- a/types/apollo-codegen/index.d.ts +++ b/types/apollo-codegen/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apollographql/apollo-codegen // Definitions by: Bradley Ayers , Maria Carrasco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { Options } from 'graphql/utilities/schemaPrinter'; diff --git a/types/apostrophe/index.d.ts b/types/apostrophe/index.d.ts index 7083405e8e..5201453542 100644 --- a/types/apostrophe/index.d.ts +++ b/types/apostrophe/index.d.ts @@ -7,7 +7,10 @@ export = apostrophe; export as namespace apos; -declare function apostrophe(options: any, ...args: any[]): any; +declare function apostrophe( + options: apostrophe.AposConstructor, + ...args: any[] +): any; declare namespace apostrophe { const moogBundle: { @@ -15,6 +18,20 @@ declare namespace apostrophe { modules: string[]; }; + // Pass in custom modules as first argument + // second argument is additional custom options e.g. restApi exposed by apostrophe-headless + interface AposConstructor { + afterInit?: () => void; + afterListen?: () => void; + initFailed?: (error: any) => void; + baseUrl?: string; + modules: { [K in AposCoreModules & M]?: AposModuleOptions | O }; + prefix?: string; + root?: string; + rootDir?: string; + shortName: string; + } + const ui: { globalBusy: (state: any) => any; link: ( @@ -297,6 +314,7 @@ declare namespace apostrophe { label: string; fields: string[]; }[]; + beforeConstruct?: (self: any, options: any) => any; defer?: boolean; filters?: { projection?: { diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 32ad04210b..76641f5270 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/arangodb/arangodb // Definitions by: Alan Plum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// diff --git a/types/arangodb/tsconfig.json b/types/arangodb/tsconfig.json index f778fd7c47..d30610b604 100644 --- a/types/arangodb/tsconfig.json +++ b/types/arangodb/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": ["es6", "esnext.asynciterable"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/types/ascii2mathml/index.d.ts b/types/ascii2mathml/index.d.ts index dcb9f7bb98..0ff3b1d10e 100644 --- a/types/ascii2mathml/index.d.ts +++ b/types/ascii2mathml/index.d.ts @@ -7,29 +7,31 @@ export = A2MML; declare var A2MML: ascii2mathml; -interface Options { - decimalMark?: string; - colSep?: string; - rowSep?: string; - display?: 'inline' | 'block'; - dir?: 'ltr' | 'rtl'; - bare?: boolean; - standalone?: boolean; - annotate?: boolean; -} - interface ascii2mathml { /** * Generates a function with default options set to convert * ASCIIMath expression to MathML markup. * @param options Options */ - (options: Options): ascii2mathml; + (options: A2MML.Options): ascii2mathml; /** * Converts ASCIIMath expression to MathML markup. * @param asciimath ASCIIMath expression * @param options Options */ - (asciimath: string, options?: Options): string; + (asciimath: string, options?: A2MML.Options): string; +} + +declare namespace A2MML { + interface Options { + decimalMark?: string; + colSep?: string; + rowSep?: string; + display?: 'inline' | 'block'; + dir?: 'ltr' | 'rtl'; + bare?: boolean; + standalone?: boolean; + annotate?: boolean; + } } diff --git a/types/atom/tslint.json b/types/atom/tslint.json index 4c3e6e9036..3811d3257c 100644 --- a/types/atom/tslint.json +++ b/types/atom/tslint.json @@ -4,6 +4,9 @@ "await-promise": [true, "CancellablePromise"], "indent": [true, "spaces", 4], "max-line-length": [true, 100], - "no-any": true + "no-any": true, + + // TODOs + "no-declare-current-package": false } } diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index a2d52cfc84..8c3a7da850 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -98,6 +98,7 @@ interface Auth0LockAuthOptions { params?: Auth0LockAuthParamsOptions; redirect?: boolean; redirectUrl?: string; + responseMode?: string; responseType?: string; sso?: boolean; audience?: string; diff --git a/types/bootstrap3-dialog/tsconfig.json b/types/bootstrap3-dialog/tsconfig.json index cdf93479b7..774e895668 100644 --- a/types/bootstrap3-dialog/tsconfig.json +++ b/types/bootstrap3-dialog/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/chai-http/tsconfig.json b/types/chai-http/tsconfig.json index 3554b4ab09..45d92cf188 100644 --- a/types/chai-http/tsconfig.json +++ b/types/chai-http/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 41ab453e0f..705392baed 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -19,7 +19,7 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { backgroundColor: "#000000", borderWidth: 1, label: "test", - data: [1] + data: [1, null, 3] } ] }, @@ -36,6 +36,7 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { tooltips: { filter: data => Number(data.yLabel) > 0, intersect: true, + mode: 'index', itemSort: (a, b) => Math.random() - 0.5, position: "average", caretPadding: 2, @@ -125,6 +126,7 @@ const chartConfig: Chart.ChartConfiguration = { backgroundColor: '#37738353', borderColor: '#37738353', borderWidth: 3, + borderCapStyle: 'round', fill: true }] }, diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f779cdc57d..198b868f74 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -174,6 +174,8 @@ declare namespace Chart { type PositionType = 'left' | 'right' | 'top' | 'bottom'; + type InteractionMode = 'point' | 'nearest' | 'single' | 'label' | 'index' | 'x-axis' | 'dataset' | 'x' | 'y'; + interface ChartArea { top: number; right: number; @@ -185,10 +187,10 @@ declare namespace Chart { text?: string; fillStyle?: string; hidden?: boolean; - lineCap?: string; + lineCap?: 'butt' | 'round' | 'square'; lineDash?: number[]; lineDashOffset?: number; - lineJoin?: string; + lineJoin?: 'bevel' | 'round' | 'miter'; lineWidth?: number; strokeStyle?: string; pointStyle?: PointStyle; @@ -331,7 +333,7 @@ declare namespace Chart { interface ChartTooltipOptions { enabled?: boolean; custom?(a: any): void; - mode?: string; + mode?: InteractionMode; intersect?: boolean; backgroundColor?: ChartColor; titleFontFamily?: string; @@ -373,7 +375,7 @@ declare namespace Chart { type ChartTooltipPositioner = (elements: any[], eventPosition: Point) => Point; interface ChartHoverOptions { - mode?: string; + mode?: InteractionMode; animationDuration?: number; intersect?: boolean; onHover?(this: Chart, event: MouseEvent, activeElements: Array<{}>): any; @@ -541,12 +543,12 @@ declare namespace Chart { backgroundColor?: ChartColor | ChartColor[]; borderWidth?: number | number[]; borderColor?: ChartColor | ChartColor[]; - borderCapStyle?: string; + borderCapStyle?: 'butt' | 'round' | 'square'; borderDash?: number[]; borderDashOffset?: number; - borderJoinStyle?: string; + borderJoinStyle?: 'bevel' | 'round' | 'miter'; borderSkipped?: PositionType; - data?: number[] | ChartPoint[]; + data?: Array | ChartPoint[]; fill?: boolean | number | string; hoverBackgroundColor?: string | string[]; hoverBorderColor?: string | string[]; @@ -566,7 +568,7 @@ declare namespace Chart { pointStyle?: PointStyle | HTMLImageElement | HTMLCanvasElement | Array; xAxisID?: string; yAxisID?: string; - type?: string; + type?: ChartType | string; hidden?: boolean; hideInLegendAndTooltip?: boolean; showLine?: boolean; diff --git a/types/codemirror/codemirror-panel.d.ts b/types/codemirror/codemirror-panel.d.ts new file mode 100644 index 0000000000..2059c8ff72 --- /dev/null +++ b/types/codemirror/codemirror-panel.d.ts @@ -0,0 +1,51 @@ +// Type definitions for CodeMirror +// Project: https://github.com/marijnh/CodeMirror +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// See docs https://codemirror.net/doc/manual.html#addon_panel + +import * as CodeMirror from "codemirror"; + +declare module "codemirror" { + interface Panel { + /**Removes the panel from the editor */ + clear(): void; + /**Notifies panel that height of DOM node has changed */ + changed(height?: number): void; + } + + interface ShowPanelOptions { + /**Controls the position of the newly added panel. The following values are recognized: + * `top` (default): Adds the panel at the very top. + * `after-top`: Adds the panel at the bottom of the top panels. + * `bottom`: Adds the panel at the very bottom. + * `before-bottom`: Adds the panel at the top of the bottom panels. + */ + position?: "top" | "after-top" | "bottom" | "before-bottom"; + /**The new panel will be added before the given panel. */ + before?: Panel; + /**The new panel will be added after the given panel. */ + after?: Panel; + /**The new panel will replace the given panel. */ + replace?: Panel; + /**Whether to scroll the editor to keep the text's vertical position stable, when adding a panel above it. Defaults to false. */ + stable?: boolean; + } + + interface Editor { + + /** + * Places a DOM node above or below an editor and shrinks the editor to make room for the node. + * When using the `after`, `before` or `replace` options, if the panel doesn't exists or has been removed, the value of the `position` option will be used as a fallback. + * @param node the DOM node + * @param options optional options object + */ + addPanel(node: HTMLElement, options?: ShowPanelOptions): Panel; + + } +} + +declare module "codemirror/addon/display/panel" { + export = CodeMirror; +} diff --git a/types/codemirror/test/panel.ts b/types/codemirror/test/panel.ts new file mode 100644 index 0000000000..3cf200beae --- /dev/null +++ b/types/codemirror/test/panel.ts @@ -0,0 +1,17 @@ + +var cm: CodeMirror.Editor = CodeMirror(document.body); + +var panel1 = cm.addPanel(document.body); + +var panel2: CodeMirror.Panel = cm.addPanel(document.body, { + position: "top", + after: panel1, + before: panel1, + replace: panel1, + stable: true +}); + +panel2.changed(); +panel2.changed(100); + +panel2.clear(); diff --git a/types/codemirror/tsconfig.json b/types/codemirror/tsconfig.json index a2c6a52430..79d2eae5c3 100644 --- a/types/codemirror/tsconfig.json +++ b/types/codemirror/tsconfig.json @@ -20,11 +20,13 @@ "files": [ "index.d.ts", "codemirror-matchbrackets.d.ts", + "codemirror-panel.d.ts", "codemirror-runmode.d.ts", "codemirror-showhint.d.ts", "searchcursor.d.ts", "test/index.ts", "test/matchbrackets.ts", + "test/panel.ts", "test/runmode.ts", "test/searchcursor.ts", "test/showhint.ts" diff --git a/types/cometd/cometd-tests.ts b/types/cometd/cometd-tests.ts index ada9412c04..ef56879d6f 100644 --- a/types/cometd/cometd-tests.ts +++ b/types/cometd/cometd-tests.ts @@ -1,4 +1,4 @@ -import { CometD, Listener, Message } from "cometd"; +import { CometD, Listener, Message, SubscriptionHandle } from "cometd"; const cometd = new CometD(); @@ -78,7 +78,7 @@ cometd.unsubscribe(subscription3, additionalInfoUnsubscribe, unsubscribeReply => // Subscribers versus Listeners // ============================ -let _reportListener: Listener | undefined; +let _reportListener: SubscriptionHandle | undefined; cometd.addListener("/meta/handshake", message => { // Only subscribe if the handshake is successful @@ -106,7 +106,7 @@ cometd.addListener("/meta/handshake", message => { // Dynamic Resubscription // ====================== -let _subscription: Listener | undefined; +let _subscription: SubscriptionHandle | undefined; class Controller { dynamicSubscribe = () => { diff --git a/types/cometd/index.d.ts b/types/cometd/index.d.ts index 32e4f962bb..cd829d444c 100644 --- a/types/cometd/index.d.ts +++ b/types/cometd/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for CometD 4.0 // Project: http://cometd.org -// Definitions by: Derek Cicerone , Daniel Perez Alvarez +// Definitions by: Derek Cicerone , Daniel Perez Alvarez , Alex Henry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -75,6 +75,15 @@ export interface Message { } export type Listener = (message: Message) => void; +export type Callback = (data: any) => void; + +export interface SubscriptionHandle { + id: number; + channel: string; + listener: boolean; + callback: Callback; + scope?: any; +} export interface Extension { incoming?: Listener; @@ -202,14 +211,14 @@ export class CometD { * @param callback the callback to call when a message is sent to the channel * @returns the subscription handle to be passed to `removeListener` */ - addListener(channel: string, callback: Listener): Listener; + addListener(channel: string, callback: Listener): SubscriptionHandle; /** * Removes the subscription obtained with a call to `addListener`. * * @param subscription the subscription to unsubscribe. */ - removeListener(subscription: Listener): void; + removeListener(subscription: SubscriptionHandle): void; /** * Removes all listeners registered with `addListener` or `subscribe`. @@ -234,7 +243,7 @@ export class CometD { * @param subscribeCallback a function to be invoked when the subscription is acknowledged * @return the subscription handle to be passed to `unsubscribe` */ - subscribe(channel: string, callback: Listener, subscribeCallback?: Listener): Listener; + subscribe(channel: string, callback: Callback, subscribeCallback?: Listener): SubscriptionHandle; /** * Subscribes to the given channel, performing the given callback in the given scope when a @@ -255,7 +264,7 @@ export class CometD { * @param subscribeCallback a function to be invoked when the subscription is acknowledged * @return the subscription handle to be passed to `unsubscribe` */ - subscribe(channel: string, callback: Listener, subscribeProps: object, subscribeCallback?: Listener): Listener; + subscribe(channel: string, callback: Callback, subscribeProps: object, subscribeCallback?: Listener): SubscriptionHandle; /** * Unsubscribes the subscription obtained with a call to `subscribe`. @@ -263,7 +272,7 @@ export class CometD { * @param subscription the subscription to unsubscribe. * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged */ - unsubscribe(subscription: Listener, unsubscribeCallback?: Listener): void; + unsubscribe(subscription: SubscriptionHandle, unsubscribeCallback?: Listener): void; /** * Unsubscribes the subscription obtained with a call to `subscribe`. @@ -272,12 +281,12 @@ export class CometD { * @param unsubscribeProps an object to be merged with the unsubscribe message * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged */ - unsubscribe(subscription: Listener, unsubscribeProps: object, unsubscribeCallback?: Listener): void; + unsubscribe(subscription: SubscriptionHandle, unsubscribeProps: object, unsubscribeCallback?: Listener): void; /** * Resubscribes as necessary in case of a re-handshake. */ - resubscribe(subscription: Listener, subscribeProps?: object): Listener; + resubscribe(subscription: SubscriptionHandle, subscribeProps?: object): SubscriptionHandle; /** * Removes all subscriptions added via `subscribe`, but does not remove the listeners added via @@ -463,5 +472,5 @@ export class CometD { * @param isListener whether it was a listener * @param message the message received from the Bayeux server */ - onListenerException: (exception: any, subscriptionHandle: Listener, isListener: boolean, message: string) => void; + onListenerException: (exception: any, subscriptionHandle: SubscriptionHandle, isListener: boolean, message: string) => void; } diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 1c6cbcaea8..11f208f869 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -596,6 +596,7 @@ numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => { // getting a permutation of array elements mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); mergedArray = d3Array.permute(readonlyMergedArray, [1, 0, 2, 5, 3, 4, 6]); +mergedArray = d3Array.permute(readonlyMergedArray, nums); // Getting an ordered array with object properties @@ -606,7 +607,10 @@ const testObject = { more: [10, 30, 40] }; -const x: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); +const p1: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); +const p2: Array = d3Array.permute(testObject, ['when', 'more']); +// $ExpectError +const p3 = d3Array.permute(testObject, ['when', 'unknown']); // range() --------------------------------------------------------------------- @@ -913,7 +917,7 @@ mixedObject = binMixedObject_DateOrUndefined[0]; dateOrUndefined = binMixedObject_DateOrUndefined.x0; dateOrUndefined = binMixedObject_DateOrUndefined.x1; -// Histogram Tresholds ========================================================= +// Histogram Thresholds ======================================================== numbersArray = [-1, 0, 1, 1, 3, 20, 234]; typedArray = new Uint8Array(numbersArray); diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 45bd86a704..391e2786be 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -228,19 +228,23 @@ export function pairs(array: ArrayLike): Array<[T, T]>; * Returns the empty array if the input array has fewer than two elements. * * @param array Array of input elements - * @param reducer A reducer function taking as input to adjecent elements of the input array and returning a reduced value. + * @param reducer A reducer function taking as input to adjacent elements of the input array and returning a reduced value. */ export function pairs(array: ArrayLike, reducer: (a: T, b: T) => U): U[]; /** - * Given the specified array, return an array corresponding to the list of indices in 'keys'. + * Returns a permutation of the specified array using the specified array of indexes. + * The returned array contains the corresponding element in array for each index in indexes, in order. + * For example, `permute(["a", "b", "c"], [1, 2, 0]) // ["b", "c", "a"]` */ export function permute(array: { [key: number]: T }, keys: ArrayLike): T[]; /** - * Given the specified object, return an array corresponding to the list of property names in 'keys'. + * Extract the values from an object into an array with a stable order. For example: + * `var object = {yield: 27, year: 1931, site: "University Farm"};` + * `d3.permute(object, ["site", "yield"]); // ["University Farm", 27]` */ -export function permute(object: { [key: string]: T }, keys: ArrayLike): T[]; +export function permute(object: T, keys: ArrayLike): Array; /** * Generates a 0-based numeric sequence. The output range does not include 'stop'. @@ -347,6 +351,11 @@ export type ThresholdNumberArrayGenerator = export type ThresholdDateArrayGenerator = (values: ArrayLike, min: Date, max: Date) => Value[]; +/** + * @deprecated Use ThresholdNumberArrayGenerator or ThresholdDateArrayGenerator. + */ +export type ThresholdArrayGenerator = ThresholdNumberArrayGenerator; + /** * @deprecated Use `HistogramGeneratorNumber` for `number` values and `HistogramGeneratorDate for `Date` values. */ @@ -403,7 +412,7 @@ export interface HistogramGeneratorDate e * and the last bin.x1 is always equal to the maximum domain value. * * @param thresholds A function which accepts as arguments the array of materialized values, and - * optionally the domain minimum and maximum. The function calcutates and returns the array of values to be used as + * optionally the domain minimum and maximum. The function calculates and returns the array of values to be used as * thresholds in determining the bins. */ thresholds(thresholds: ThresholdDateArrayGenerator): this; @@ -434,7 +443,7 @@ export interface HistogramGeneratorNumber): this; @@ -456,7 +465,7 @@ export interface HistogramGeneratorNumber): this; diff --git a/types/datatables.net-autofill/tsconfig.json b/types/datatables.net-autofill/tsconfig.json index e17d5de5da..f9373c0cbc 100644 --- a/types/datatables.net-autofill/tsconfig.json +++ b/types/datatables.net-autofill/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/detox/detox-tests.ts b/types/detox/detox-tests.ts index 7fc2aaa579..58fe5c1912 100644 --- a/types/detox/detox-tests.ts +++ b/types/detox/detox-tests.ts @@ -21,6 +21,9 @@ describe('Test', () => { await element(by.id('scrollView')).swipe('down', 'fast'); await element(by.type('UIPickerView')).setColumnToValue(1, "6"); + await expect(element(by.id('element').withAncestor(by.id('parent_element')))).toNotExist(); + await expect(element(by.id('element').withDescendant(by.id('child_element')))).toNotExist(); + await waitFor(element(by.id('element'))).toBeVisible().withTimeout(2000); await device.pressBack(); await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index d2eae49f8d..7ef085e25d 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for detox 7.3 +// Type definitions for detox 9.0 // Project: https://github.com/wix/detox -// Definitions by: Tareq El-Masri +// Definitions by: Tareq El-Masri , Steve Chun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const detox: Detox.Detox; @@ -22,7 +22,7 @@ declare namespace Detox { * await detox.init(config); * }); */ - init(config: any, options: DetoxInitOptions): Promise; + init(config: any, options?: DetoxInitOptions): Promise; /** * Artifacts currently include only logs from the app process before each task * @param args @@ -157,18 +157,6 @@ declare namespace Detox { interface Element { (by: Matchers): DetoxAny; - /** - * Select by parent element - * @param parent - * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); - */ - withAncestor(parent: Element): DetoxAny; - /** - * Select by child element - * @param parent - * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); - */ - withDescendant(child: Element): DetoxAny; /** * Choose from multiple elements matching the same matcher using index * @param index @@ -177,6 +165,8 @@ declare namespace Detox { atIndex(index: number): DetoxAny; } interface Matchers { + (by: Matchers): Matchers; + /** * by.id will match an id that is given to the view via testID prop. * @param id @@ -209,6 +199,24 @@ declare namespace Detox { * @example await element(by.traits(['button'])); */ traits(traits: string[]): Matchers; + /** + * Find an element by a matcher with a parent matcher + * @param parentBy + * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); + */ + withAncestor(parentBy: Matchers): Matchers; + /** + * Find an element by a matcher with a child matcher + * @param childBy + * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); + */ + withDescendant(childBy: Matchers): Matchers; + /** + * Find an element by multiple matchers + * @param by + * @example await element(by.text('Product').and(by.id('product_name')); + */ + and(by: Matchers): Matchers; } interface Expect { (element: Element): Expect; @@ -275,7 +283,7 @@ declare namespace Detox { withTimeout(millis: number): Promise; /** * Performs the action repeatedly on the element until an expectation is met - * @param element + * @param by * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); */ whileElement(by: Matchers): DetoxAny; diff --git a/types/dwt/addon.pdf.d.ts b/types/dwt/addon.pdf.d.ts index 2e7b1d5a84..6a2a8636ee 100644 --- a/types/dwt/addon.pdf.d.ts +++ b/types/dwt/addon.pdf.d.ts @@ -6,7 +6,7 @@ * * Copyright 2018, Dynamsoft Corporation * Author: Dynamsoft Support Team -* Version: 13.4 +* Version: 14.2 */ declare enum EnumDWT_ConvertMode { diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts index 0656236f08..12813a9b40 100644 --- a/types/dwt/index.d.ts +++ b/types/dwt/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dwt 13.4 +// Type definitions for dwt 14.2 // Project: http://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx // Definitions by: Xiao Ling // Josh Hall @@ -14,7 +14,7 @@ * * Copyright 2018, Dynamsoft Corporation * Author: Dynamsoft Support Team -* Version: 13.4 +* Version: 14.2 */ /** @@ -2889,12 +2889,12 @@ interface WebTwain { * @return {number} */ GetImageYResolution(sImageIndex: number): number; - + /** * Return the runtime license info. * @method WebTwain#GetLicenseInfo */ - GetLicenseInfo(): { Domain: string, Detail: LicenseDetailItem[] }; + GetLicenseInfo(optionalAsyncSuccessFunc?: (result: any) => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; /** * Returns the index of the selected image. diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index a9dc133545..69c881e700 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -39,8 +39,8 @@ export class Client { deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; deleteTemplate(params: DeleteTemplateParams): Promise; deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; - exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; + exists(params: ExistsParams): Promise; + exists(params: ExistsParams, callback: (error: any, response: boolean, status?: any) => void): void; explain(params: ExplainParams): Promise; explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; fieldStats(params: FieldStatsParams): Promise; @@ -443,7 +443,7 @@ export interface IndexDocumentParams extends GenericParams { waitForActiveShards?: string; opType?: "index" | "create"; parent?: string; - refresh?: string; + refresh?: Refresh; routing?: string; timeout?: TimeSpan; timestamp?: Date | number; @@ -1036,14 +1036,14 @@ export class Indices { deleteAlias(params: IndicesDeleteAliasParams): Promise; deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; deleteTemplate(params: IndicesDeleteTemplateParams): Promise; - exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; - exists(params: IndicesExistsParams): Promise; - existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; - existsAlias(params: IndicesExistsAliasParams): Promise; - existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; - existsTemplate(params: IndicesExistsTemplateParams): Promise; - existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; - existsType(params: IndicesExistsTypeParams): Promise; + exists(params: IndicesExistsParams, callback: (error: any, response: boolean, status: any) => void): void; + exists(params: IndicesExistsParams): Promise; + existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: boolean, status: any) => void): void; + existsAlias(params: IndicesExistsAliasParams): Promise; + existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: boolean, status: any) => void): void; + existsTemplate(params: IndicesExistsTemplateParams): Promise; + existsType(params: IndicesExistsTypeParams, callback: (error: any, response: boolean, status: any) => void): void; + existsType(params: IndicesExistsTypeParams): Promise; flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; flush(params: IndicesFlushParams): Promise; flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; diff --git a/types/electron-window-state/package.json b/types/electron-window-state/package.json index 880e1b40f6..89bd2f24e6 100644 --- a/types/electron-window-state/package.json +++ b/types/electron-window-state/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "electron": "^1.7.5" + "electron": "*" } } diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json index 03cadac59d..f476362aaf 100644 --- a/types/ember-data/tsconfig.json +++ b/types/ember-data/tsconfig.json @@ -14,18 +14,31 @@ "../" ], "paths": { - "@ember/debug": ["ember__debug"], - "@ember/debug/*": ["ember__debug/*"], - "@ember/service": ["ember__service"], + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"], "@ember/array": ["ember__array"], "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], "@ember/debug": ["ember__debug"], "@ember/debug/*": ["ember__debug/*"], - "@ember/controller": ["ember__controller"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], + "@ember/object": ["ember__object"], + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], "@ember/routing": ["ember__routing"], "@ember/routing/*": ["ember__routing/*"], - "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-feature-flags/tsconfig.json b/types/ember-feature-flags/tsconfig.json index 54f7acecb3..5b5dc17f2d 100644 --- a/types/ember-feature-flags/tsconfig.json +++ b/types/ember-feature-flags/tsconfig.json @@ -14,9 +14,31 @@ "../" ], "paths": { - "@ember/service": ["ember__service"], + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-mocha/ember-mocha-tests.ts b/types/ember-mocha/ember-mocha-tests.ts index 09662096b6..fd637a81b3 100644 --- a/types/ember-mocha/ember-mocha-tests.ts +++ b/types/ember-mocha/ember-mocha-tests.ts @@ -248,6 +248,6 @@ describe('rendering test', function() { // render the component await this.render(hbs`{{ x-foo value=value}}`); - chai.expect(this.element.querySelector('div>.value').textContent.trim()).to.equal('cat', 'The component shows the correct value'); + chai.expect(this.element.querySelector('div>.value')!.textContent!.trim()).to.equal('cat', 'The component shows the correct value'); }); }); diff --git a/types/ember-mocha/tsconfig.json b/types/ember-mocha/tsconfig.json index 2c00d52341..4e9b406e2e 100644 --- a/types/ember-mocha/tsconfig.json +++ b/types/ember-mocha/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -13,12 +14,31 @@ "../" ], "paths": { - "@ember/engine": ["ember__engine"], - "@ember/engine/*": ["ember__engine/*"], "@ember/application": ["ember__application"], "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-modal-dialog/tsconfig.json b/types/ember-modal-dialog/tsconfig.json index 9a842ee744..0b0b6f91fb 100644 --- a/types/ember-modal-dialog/tsconfig.json +++ b/types/ember-modal-dialog/tsconfig.json @@ -14,10 +14,31 @@ "../" ], "paths": { + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], "@ember/object": ["ember__object"], "@ember/object/*": ["ember__object/*"], - "@ember/component": ["ember__component"], - "@ember/component/*": ["ember__component/*"] + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-qunit/tsconfig.json b/types/ember-qunit/tsconfig.json index 7b184205af..df4899b37c 100644 --- a/types/ember-qunit/tsconfig.json +++ b/types/ember-qunit/tsconfig.json @@ -14,14 +14,31 @@ "../" ], "paths": { - "@ember/engine": ["ember__engine"], - "@ember/engine/*": ["ember__engine/*"], "@ember/application": ["ember__application"], "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], + "@ember/object": ["ember__object"], + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], "@ember/test": ["ember__test"], "@ember/test/*": ["ember__test/*"], - "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-resolver/tsconfig.json b/types/ember-resolver/tsconfig.json index e8dfb6e8ce..bc476c5723 100644 --- a/types/ember-resolver/tsconfig.json +++ b/types/ember-resolver/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -13,12 +14,31 @@ "../" ], "paths": { - "@ember/engine": ["ember__engine"], - "@ember/engine/*": ["ember__engine/*"], "@ember/application": ["ember__application"], "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember-resolver/v4/index.d.ts b/types/ember-resolver/v4/index.d.ts index fd5359cff4..88ace683f3 100644 --- a/types/ember-resolver/v4/index.d.ts +++ b/types/ember-resolver/v4/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dan Freeman // Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import Ember from 'ember'; diff --git a/types/ember-resolver/v4/tsconfig.json b/types/ember-resolver/v4/tsconfig.json index 2539233e16..2c47c95ba1 100644 --- a/types/ember-resolver/v4/tsconfig.json +++ b/types/ember-resolver/v4/tsconfig.json @@ -2,12 +2,13 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": true, + "strictFunctionTypes": false, "baseUrl": "../../", "typeRoots": [ "../../" diff --git a/types/ember-test-helpers/tsconfig.json b/types/ember-test-helpers/tsconfig.json index 2d9eb44d16..2e0ddf49b1 100644 --- a/types/ember-test-helpers/tsconfig.json +++ b/types/ember-test-helpers/tsconfig.json @@ -14,12 +14,31 @@ "../" ], "paths": { - "@ember/engine": ["ember__engine"], - "@ember/engine/*": ["ember__engine/*"], "@ember/application": ["ember__application"], "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], "@ember/object": ["ember__object"], - "@ember/object/*": ["ember__object/*"] + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember/tsconfig.json b/types/ember/tsconfig.json index 8a2cec5578..be47225e72 100755 --- a/types/ember/tsconfig.json +++ b/types/ember/tsconfig.json @@ -15,31 +15,31 @@ "../" ], "paths": { - "@ember/string": ["ember__string"], + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], "@ember/engine": ["ember__engine"], "@ember/engine/*": ["ember__engine/*"], "@ember/error": ["ember__error"], - "@ember/service": ["ember__service"], - "@ember/utils": ["ember__utils"], - "@ember/utils/*": ["ember__utils/*"], - "@ember/array": ["ember__array"], - "@ember/array/*": ["ember__array/*"], - "@ember/debug": ["ember__debug"], - "@ember/debug/*": ["ember__debug/*"], - "@ember/runloop": ["ember__runloop"], - "@ember/runloop/*": ["ember__runloop/*"], - "@ember/routing": ["ember__routing"], - "@ember/routing/*": ["ember__routing/*"], - "@ember/test": ["ember__test"], - "@ember/test/*": ["ember__test/*"], "@ember/object": ["ember__object"], "@ember/object/*": ["ember__object/*"], - "@ember/component": ["ember__component"], - "@ember/component/*": ["ember__component/*"], - "@ember/application": ["ember__application"], - "@ember/application/*": ["ember__application/*"], - "@ember/controller": ["ember__controller"], - "@ember/polyfills": ["ember__polyfills"] + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/ember__application/tsconfig.json b/types/ember__application/tsconfig.json index c83da0b13d..46e1acb468 100644 --- a/types/ember__application/tsconfig.json +++ b/types/ember__application/tsconfig.json @@ -21,8 +21,10 @@ "@ember/engine/*": ["ember__engine/*"], "@ember/routing": ["ember__routing"], "@ember/routing/*": ["ember__routing/*"], + "@ember/service": ["ember__service"], "@ember/application": ["ember__application"], - "@ember/application/*": ["ember__application/*"] + "@ember/application/*": ["ember__application/*"], + "@ember/controller": ["ember__controller"] }, "types": [], "noEmit": true, diff --git a/types/ember__object/test/core.ts b/types/ember__object/test/core.ts index 984f5eec12..740daa78b0 100644 --- a/types/ember__object/test/core.ts +++ b/types/ember__object/test/core.ts @@ -1,8 +1,8 @@ -import Ember from 'ember'; import { assertType } from './lib/assert'; +import CoreObject from '@ember/object/core'; /** Newable tests */ -const co1 = new Ember.CoreObject(); +const co1 = new CoreObject(); // TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 // co1.concatenatedProperties; // $ExpectType string[] @@ -12,7 +12,7 @@ co1.destroy(); // $ExpectType CoreObject co1.toString(); // $ExpectType string /** .create tests */ -const co2 = Ember.CoreObject.create(); +const co2 = CoreObject.create(); // TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 // co2.concatenatedProperties; // $ExpectType string[] co2.isDestroyed; // $ExpectType boolean @@ -21,13 +21,13 @@ co2.destroy(); // $ExpectType CoreObject co2.toString(); // $ExpectType string /** .create tests w/ initial instance data passed in */ -const co3 = Ember.CoreObject.create({ foo: '123', bar: 456 }); +const co3 = CoreObject.create({ foo: '123', bar: 456 }); co3.foo; // $ExpectType string co3.bar; // $ExpectType number /** .extend with a zero-argument .create() */ -const co4 = Ember.CoreObject.extend({ +const co4 = CoreObject.extend({ foo: '123', bar: 456, baz(): [string, number] { @@ -40,8 +40,8 @@ co4.bar; // $ExpectType number co4.baz; // $ExpectType () => [string, number] /** .extend with inconsistent arguments passed into .create() */ -const class05 = Ember.CoreObject.extend({ - foo: '123' as (string | boolean), +const class05 = CoreObject.extend({ + foo: '123' as string | boolean, bar: 456, baz() { return [this.foo, this.bar]; @@ -54,33 +54,36 @@ assertType(c05b.foo); // $ExpectError assertType(c05c.foo); // $ExpectError /** two .extend arguments with a zero-argument .create() */ -const co6 = Ember.CoreObject.extend({ - foo: '123', - bar: 456, - baz() { - return [this.foo, this.bar]; +const co6 = CoreObject.extend( + { + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } }, - func1() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.foo; // $ExpectType string - // this does not include stuff from later extend args - this.bee; // $ExpectError + { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } } -}, { - foo: 99, - bee: 'honey', - func2() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 - this.foo; // $ExpectType string & number - // this includes stuff from earlier extend-args - this.bar; // $ExpectType number - } -}).create(); +).create(); // TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 // assertType(co6.foo); // $ExpectError @@ -88,45 +91,49 @@ assertType(co6.bar); // $ExpectType number assertType<() => Array>(co6.baz); // $ExpectType () => (string | number)[] /** three .extend arguments with a zero-argument .create() */ -const co7 = Ember.CoreObject.extend({ - foo: '123', - bar: 456, - baz() { - return [this.foo, this.bar]; +const co7 = CoreObject.extend( + { + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } }, - func1() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.foo; // $ExpectType string - // this does not include stuff from later extend args - this.bee; // $ExpectError + { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } + }, + { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + } } -}, { - foo: 99, - bee: 'honey', - func2() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 - this.foo; // $ExpectType string & number - // this includes stuff from earlier extend-args - this.bar; // $ExpectType number - } -}, { - foo: '99', - money: 'in the banana stand', - func3() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.money; // $ExpectType string - // this includes stuff from earlier extend-args - this.bee; // $ExpectType string - this.bar; // $ExpectType number - } -}).create(); +).create(); // TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 // assertType(co7.foo); // $ExpectError assertType(co7.bar); // $ExpectType number @@ -134,62 +141,67 @@ assertType(co7.money); // $ExpectType string assertType<() => Array>(co7.baz); // $ExpectType () => (string | number)[] /** four .extend arguments with a zero-argument .create() */ -const co8 = Ember.CoreObject.extend({ - foo: '123', - bar: 456, - baz() { - return [this.foo, this.bar]; +const co8 = CoreObject.extend( + { + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } }, - func1() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.foo; // $ExpectType string - // this does not include stuff from later extend args - this.bee; // $ExpectError + { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.money; // $ExpectError + } + }, + { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.neighborhood; // $ExpectError + } + }, + { + foo: '99', + neighborhood: 'sudden valley', + func4() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.neighborhood; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + this.money; // $ExpectType string + } } -}, { - foo: 99, - bee: 'honey', - func2() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 - this.foo; // $ExpectType string & number - // this includes stuff from earlier extend-args - this.bar; // $ExpectType number - // this does not include stuff from later extend args - this.money; // $ExpectError - } -}, { - foo: '99', - money: 'in the banana stand', - func3() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.money; // $ExpectType string - // this includes stuff from earlier extend-args - this.bee; // $ExpectType string - this.bar; // $ExpectType number - // this does not include stuff from later extend args - this.neighborhood; // $ExpectError - } -}, { - foo: '99', - neighborhood: 'sudden valley', - func4() { - // this includes stuff from CoreObject - this.init; // $ExpectType () => void - // this includes stuff from this extend-arg - this.neighborhood; // $ExpectType string - // this includes stuff from earlier extend-args - this.bee; // $ExpectType string - this.bar; // $ExpectType number - this.money; // $ExpectType string - } -}).create(); +).create(); // TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 // assertType(co8.foo); // $ExpectError diff --git a/types/ember__object/test/create-negative.ts b/types/ember__object/test/create-negative.ts index 2298ae8cf3..dadd2a2176 100644 --- a/types/ember__object/test/create-negative.ts +++ b/types/ember__object/test/create-negative.ts @@ -1,5 +1,4 @@ import { assertType } from './lib/assert'; -import Ember from 'ember'; import { PersonWithNumberName, Person } from './create'; Person.create({ firstName: 99 }); // $ExpectError diff --git a/types/ember__test-helpers/tsconfig.json b/types/ember__test-helpers/tsconfig.json index 18e1faee35..7b167f14d5 100644 --- a/types/ember__test-helpers/tsconfig.json +++ b/types/ember__test-helpers/tsconfig.json @@ -17,14 +17,31 @@ "noEmit": true, "forceConsistentCasingInFileNames": true, "paths": { + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], "@ember/engine": ["ember__engine"], "@ember/engine/*": ["ember__engine/*"], "@ember/error": ["ember__error"], - "@ember/application": ["ember__application"], - "@ember/application/*": ["ember__application/*"], "@ember/object": ["ember__object"], "@ember/object/*": ["ember__object/*"], - "@ember/test-helpers": ["ember__test-helpers"] + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] } }, "files": [ diff --git a/types/ember__test/tsconfig.json b/types/ember__test/tsconfig.json index e5405575cc..da00f05337 100644 --- a/types/ember__test/tsconfig.json +++ b/types/ember__test/tsconfig.json @@ -15,12 +15,31 @@ "../" ], "paths": { - "@ember/engine": ["ember__engine"], - "@ember/engine/*": ["ember__engine/*"], "@ember/application": ["ember__application"], "@ember/application/*": ["ember__application/*"], + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"], + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"], + "@ember/controller": ["ember__controller"], + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"], + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"], + "@ember/error": ["ember__error"], + "@ember/object": ["ember__object"], + "@ember/object/*": ["ember__object/*"], + "@ember/polyfills": ["ember__polyfills"], + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"], + "@ember/runloop": ["ember__runloop"], + "@ember/runloop/*": ["ember__runloop/*"], + "@ember/service": ["ember__service"], + "@ember/string": ["ember__string"], "@ember/test": ["ember__test"], - "@ember/test/*": ["ember__test/*"] + "@ember/test/*": ["ember__test/*"], + "@ember/utils": ["ember__utils"], + "@ember/utils/*": ["ember__utils/*"] }, "types": [], "noEmit": true, diff --git a/types/expect-puppeteer/tsconfig.json b/types/expect-puppeteer/tsconfig.json index 7ca516e3c2..8a3d56b626 100644 --- a/types/expect-puppeteer/tsconfig.json +++ b/types/expect-puppeteer/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/express-graphql/index.d.ts b/types/express-graphql/index.d.ts index 78c988204f..5f49e62308 100644 --- a/types/express-graphql/index.d.ts +++ b/types/express-graphql/index.d.ts @@ -7,7 +7,7 @@ // Margus Lamp // Firede // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { Request, Response } from "express"; import { DocumentNode, GraphQLSchema, GraphQLError } from "graphql"; diff --git a/types/express-graphql/tsconfig.json b/types/express-graphql/tsconfig.json index 7924c82706..ac6ad5f138 100644 --- a/types/express-graphql/tsconfig.json +++ b/types/express-graphql/tsconfig.json @@ -3,7 +3,8 @@ "module": "commonjs", "target": "es2015", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/express-mung/express-mung-tests.ts b/types/express-mung/express-mung-tests.ts index 86106e2c59..77aebc6c05 100644 --- a/types/express-mung/express-mung-tests.ts +++ b/types/express-mung/express-mung-tests.ts @@ -1,7 +1,35 @@ import { Request, Response } from "express"; import * as mung from "express-mung"; -function redact(body: Object, req: Request, res: Response) { -    return body; +function redact(body: {}, req: Request, res: Response) { + return body; } + mung.json(redact); +mung.json(redact, { mungError: true }); + +function redactAsync(body: {}, req: Request, res: Response) { + return Promise.resolve(body); +} + +mung.jsonAsync(redactAsync); +mung.jsonAsync(redactAsync, { mungError: true }); + +function transformHeaders(req: Request, res: Response) { + return; +} + +mung.headers(transformHeaders); + +function transformHeadersAsync(req: Request, res: Response) { + return Promise.resolve(); +} + +mung.headersAsync(transformHeadersAsync); + +function transformChunk(chunk: string | Buffer, encoding: string | null, req: Request, res: Response) { + return 'chunk'; +} + +mung.write(transformChunk); +mung.write(transformChunk, { mungError: true }); diff --git a/types/express-mung/index.d.ts b/types/express-mung/index.d.ts index e6de726cd8..1236dc86dc 100644 --- a/types/express-mung/index.d.ts +++ b/types/express-mung/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for express-mung 0.4.2 +// Type definitions for express-mung 0.5.1 // Project: https://github.com/richardschneider/express-mung // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,37 +8,50 @@ /// declare module "express-mung" { - import { Request, Response } from "express"; - import * as http from "http"; + import { Request, Response, RequestHandler } from "express"; type Transform = (body: {}, request: Request, response: Response) => any; - type TransformHeader = (body: http.IncomingMessage, request: Request, response: Response) => any; + type TransformAsync = (body: {}, request: Request, response: Response) => PromiseLike; + type TransformHeader = (request: Request, response: Response) => any; + type TransformHeaderAsync = (request: Request, response: Response) => PromiseLike; + type TransformChunk = (chunk: string | Buffer, encoding: string | null, request: Request, response: Response) => string | Buffer; + type Options = { mungError: boolean }; /** * Transform the JSON body of the response. * @param {Transform} fn A transformation function. - * @return {any} The body. + * @param {Options} [options] json options. + * @return {RequestHandler} Middleware to transform the body */ - export function json(fn: Transform): any; + export function json(fn: Transform, options?: Options): RequestHandler; /** - * Transform the JSON body of the response. - * @param {Transform} fn A transformation function. - * @return {any} The body. + * Asynchronously transform the JSON body of the response. + * @param {TransformAsync} fn A transformation function. + * @param {Options} [options] jsonAsync options. + * @return {RequestHandler} Middleware to transform the body */ - export function jsonAsync(fn: Transform): PromiseLike; + export function jsonAsync(fn: TransformAsync, options?: Options): RequestHandler; /** * Transform the HTTP headers of the response. - * @param {Transform} fn A transformation function. - * @return {any} The body. + * @param {TransformHeader} fn A transformation function. + * @return {RequestHandler} Middleware to transform the headers */ - export function headers(fn: TransformHeader): any; + export function headers(fn: TransformHeader): RequestHandler; /** - * Transform the HTTP headers of the response. - * @param {Transform} fn A transformation function. - * @return {any} The body. + * Asynchronously transform the HTTP headers of the response. + * @param {TransformHeaderAsync} fn A transformation function. + * @return {RequestHandler} Middleware to transform the headers */ - export function headersAsync(fn: TransformHeader): PromiseLike; + export function headersAsync(fn: TransformHeaderAsync): RequestHandler; + + /** + * Transform chunks as they are written to the response + * @param {TransformChunk} fn A transformation function. + * @param {Options} [options] Write options. + * @return {RequestHandler} Middleware to transform chunks. + */ + export function write(fn: TransformChunk, options?: Options): RequestHandler; } diff --git a/types/express-mung/tsconfig.json b/types/express-mung/tsconfig.json index 9dd04b84e6..1588655c88 100644 --- a/types/express-mung/tsconfig.json +++ b/types/express-mung/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "express-mung-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/express-ntlm/express-ntlm-tests.ts b/types/express-ntlm/express-ntlm-tests.ts new file mode 100644 index 0000000000..6874b2a0e7 --- /dev/null +++ b/types/express-ntlm/express-ntlm-tests.ts @@ -0,0 +1,22 @@ +import express = require('express'); +import ntlm = require('express-ntlm'); + +const app = express(); + +app.use(ntlm({ + debug() { + const args = Array.prototype.slice.apply(arguments); + console.log.apply(null, args); + }, + domain: 'MYDOMAIN', + domaincontroller: 'ldap://myad.example', + + // use different port (default: 389) + // domaincontroller: 'ldap://myad.example:3899', +})); + +app.all('*', (request, response) => { + response.end(JSON.stringify(request.ntlm)); // {"DomainName":"MYDOMAIN","UserName":"MYUSER","Workstation":"MYWORKSTATION"} +}); + +app.listen(80); diff --git a/types/express-ntlm/index.d.ts b/types/express-ntlm/index.d.ts new file mode 100644 index 0000000000..58949d0394 --- /dev/null +++ b/types/express-ntlm/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for express-ntlm 2.3 +// Project: https://github.com/einfallstoll/express-ntlm +// Definitions by: Emily Marigold Klassen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { ConnectionOptions } from 'tls'; + +import { Handler } from 'express'; + +declare function expressNtlm(options?: expressNtlm.Options): Handler; + +declare namespace expressNtlm { + interface Options { + prefix?: string; + badrequest?: Handler; + internalservererror?: Handler; + forbidden?: Handler; + unauthorized?: Handler; + domain?: string; + domaincontroller?: string; + tlsOptions?: ConnectionOptions; + debug?(prefix: string, message: string): void; + } + interface RequestNtlm { + DomainName?: string; + UserName?: string; + Workstation?: string; + } +} + +declare global { + namespace Express { + interface Request { + ntlm?: expressNtlm.RequestNtlm; + } + } +} + +export = expressNtlm; diff --git a/types/express-ntlm/tsconfig.json b/types/express-ntlm/tsconfig.json new file mode 100644 index 0000000000..fd451d5b7b --- /dev/null +++ b/types/express-ntlm/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", + "express-ntlm-tests.ts" + ] +} diff --git a/types/express-ntlm/tslint.json b/types/express-ntlm/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-ntlm/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-sitemap-xml/express-sitemap-xml-tests.ts b/types/express-sitemap-xml/express-sitemap-xml-tests.ts index f68dbf9696..9882f11c2a 100644 --- a/types/express-sitemap-xml/express-sitemap-xml-tests.ts +++ b/types/express-sitemap-xml/express-sitemap-xml-tests.ts @@ -1,16 +1,22 @@ import * as express from 'express'; -import expressSitemapXml from 'express-sitemap-xml'; +import expressSitemapXml, { LeafObject } from 'express-sitemap-xml'; -const urls = ['/page1', '/page2']; +const page2Leaf: LeafObject = { + changeFreq: 'weekly', + lastMod: new Date(), + url: '/page2' +}; + +const leaves = ['/page1', page2Leaf]; const base = 'http://example.com'; -const getUrls = () => urls; -const getUrlsPromise = () => Promise.resolve(urls); +const getLeaves = () => leaves; +const getLeavesPromise = () => Promise.resolve(leaves); -expressSitemapXml.buildSitemaps(urls, base).then(sitemap => typeof sitemap === 'object'); +expressSitemapXml.buildSitemaps(leaves, base).then(sitemap => typeof sitemap === 'object'); -const sitemap1 = expressSitemapXml(getUrls, base); -const sitemap2 = expressSitemapXml(getUrlsPromise, base); +const sitemap1 = expressSitemapXml(getLeaves, base); +const sitemap2 = expressSitemapXml(getLeavesPromise, base); express().use(sitemap1); express().use(sitemap2); diff --git a/types/express-sitemap-xml/index.d.ts b/types/express-sitemap-xml/index.d.ts index 6460fad25a..1926878bb5 100644 --- a/types/express-sitemap-xml/index.d.ts +++ b/types/express-sitemap-xml/index.d.ts @@ -6,14 +6,22 @@ import * as express from 'express'; -export interface Sitemap { - [url: string]: string; +export interface LeafObject { + changeFreq?: string; + lastMod?: string | Date; + url: string; } -declare function expressSitemapXml(getUrls: (() => (string[] | Promise)), base: string): express.RequestHandler; +export type SitemapLeaf = string | LeafObject; + +export interface Sitemap { + [leaf: string]: string; +} + +declare function expressSitemapXml(getUrls: (() => (SitemapLeaf[] | Promise)), base: string): express.RequestHandler; declare namespace expressSitemapXml { - function buildSitemaps(urls: string[], base: string): Promise; + function buildSitemaps(urls: SitemapLeaf[], base: string): Promise; } export default expressSitemapXml; diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index d9e9e8df7c..2497d3b53d 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -5890,7 +5890,7 @@ declare namespace browser.contextMenus { /** A list of all contexts that apply to the menu. */ contexts: ContextType[]; editable: boolean; - mediaType: string; + mediaType?: string; linkUrl?: string; linkText?: string; srcUrl?: string; @@ -6131,7 +6131,7 @@ declare namespace browser.menus { /** A list of all contexts that apply to the menu. */ contexts: ContextType[]; editable: boolean; - mediaType: string; + mediaType?: string; linkUrl?: string; linkText?: string; srcUrl?: string; @@ -6915,7 +6915,7 @@ declare namespace browser.tabs { type _TabsOnUpdatedEvent { + response.json.results.forEach(result => { + console.log( + result.geometry.location + ); + }); + }); diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts new file mode 100644 index 0000000000..4759d412dd --- /dev/null +++ b/types/google__maps/index.d.ts @@ -0,0 +1,3439 @@ +// Type definitions for @google/maps 0.5 +// Project: https://github.com/googlemaps/google-maps-services-js +// Definitions by: Indri Muska +// Definitions: https://github.com/indrimuska/google-maps-api-typings +// TypeScript Version: 2.3 + +/** + * Creates a Google Maps client. The client object contains all the API methods. + */ +export interface CreateClientOptions { + /** API key (required, unless clientID and clientSecret provided). */ + key: string; + /** Maps API for Work client ID. */ + clientId?: string; + /** Maps API for Work client secret (a.k.a. private key). */ + clientSecret?: string; + /** Maps API for Work channel. */ + channel?: string; + /** Timeout in milliseconds. (Default: 60 * 1000 ms). */ + timeout?: number; + /** Default language for all queries. */ + language?: Language; + /** Promise constructor (optional). */ + Promise?: PromiseConstructor; + /** Rate options. */ + rate?: RateOptions; + /** Retry options. */ + retryOptions?: RetryOptions; +} + +export interface RateOptions { + /** Controls rate-limiting of requests. Maximum number of requests per period. (Default: 50). */ + limit?: number; + /** Period for rate limit, in milliseconds. (Default: 1000 ms). */ + period?: number; +} + +export interface RetryOptions { + /** If a transient server error occurs, how long to wait before retrying the request, in milliseconds. (Default: 500 ms). */ + interval?: number; +} + +export function createClient(options: CreateClientOptions): GoogleMapsClient; + +/** + * A callback function, which is called asynchronously when an API method completes. + * The callback is given either: + * - a successful `ClientResponse` object; or + * - an error, one of: + * - the string `"timeout"`; or + * - an error from the underlying `http` library; or + * - a `ClientResponse` whose status is not `OK`. + * + * API methods don't require a callback function, if you use the Promise API. + */ +export type ResponseCallback = (err: 'timeout' | ClientResponse, response: ClientResponse) => void; + +/** + * The object given to the ResponseCallback, containing the HTTP status and headers, as well as the response JSON. + */ +export interface ClientResponse { + /** The HTTP headers. */ + headers: { [index: string]: string }; + /** Deserialized JSON object for the API response. */ + json: T; + /** The HTTP status. */ + status: number; +} + +/** A handle that allows cancelling a request, or obtaining a Promise. */ +export interface RequestHandle { + /** + * Returns the response as a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * This method is only available if you supplied the `Promise` constructor to the `createClient()` method when you constructed + * the client object. + */ + asPromise(): Promise>; + /** + * Cancels the request. + * The ResponseCallback will not be invoked, and promises will not be settled. + * Use the RequestHandle#finally handler will still be called. + */ + cancel(): void; + /** + * Registers a callback that will be called when the response is finished, either successfully, or with an error, + * or having been cancelled. Use this to clean up resources. + * Returns this handle, for chaining. + */ + finally(callback: () => void): RequestHandle; +} + +export type LatLngArray = [number, number]; + +export type LatLngString = string; + +export interface LatLngLiteral { + lat: number; + lng: number; +} + +export interface LatLngLiteralVerbose { + latitude: number; + longitude: number; +} + +/** + * A latitude, longitude pair. The API methods accept either: + * - a two-item array of [latitude, longitude]; + * - a comma-separated string; + * - an object with 'lat', 'lng' properties; or + * - an object with 'latitude', 'longitude' properties. + */ +export type LatLng = ( + LatLngArray | + LatLngString | + LatLngLiteral | + LatLngLiteralVerbose +); + +/** The bounds parameter defines the latitude/longitude coordinates of the southwest and northeast corners of this bounding box. */ +export interface LatLngBounds { + northeast: LatLngLiteral; + southwest: LatLngLiteral; +} + +/** + * By default the API will attempt to load the most appropriate language based on the users location or browser settings. + * Some APIs allow you to explicitly set a language when you make a request + * + * @see https://developers.google.com/maps/faq#languagesupport + */ +export type Language = ( + /** Arabic */ + 'ar' | + /** Belarusian */ + 'be' | + /** Bulgarian */ + 'bg' | + /** Bengali */ + 'bn' | + /** Catalan */ + 'ca' | + /** Czech */ + 'cs' | + /** Danish */ + 'da' | + /** German */ + 'de' | + /** Greek */ + 'el' | + /** English */ + 'en' | + /** English (Australian) */ + 'en-Au' | + /** English (Great Britain) */ + 'en-GB' | + /** Spanish */ + 'es' | + /** Basque */ + 'eu' | + /** Farsi */ + 'fa' | + /** Finnish */ + 'fi' | + /** Filipino */ + 'fil' | + /** French */ + 'fr' | + /** Galician */ + 'gl' | + /** Gujarati */ + 'gu' | + /** Hindi */ + 'hi' | + /** Croatian */ + 'hr' | + /** Hungarian */ + 'hu' | + /** Indonesian */ + 'id' | + /** Italian */ + 'it' | + /** Hebrew */ + 'iw' | + /** Japanese */ + 'ja' | + /** Kazakh */ + 'kk' | + /** Kannada */ + 'kn' | + /** Korean */ + 'ko' | + /** Kyrgyz */ + 'ky' | + /** Lithuanian */ + 'lt' | + /** Latvian */ + 'lv' | + /** Macedonian */ + 'mk' | + /** Malayalam */ + 'ml' | + /** Marathi */ + 'mr' | + /** Burmese */ + 'my' | + /** Dutch */ + 'nl' | + /** Norwegian */ + 'no' | + /** Punjabi */ + 'pa' | + /** Polish */ + 'pl' | + /** Portuguese */ + 'pt' | + /** Portuguese (Brazil) */ + 'pt-BR' | + /** Portuguese (Portugal) */ + 'pt-PT' | + /** Romanian */ + 'ro' | + /** Russian */ + 'ru' | + /** Slovak */ + 'sk' | + /** Slovenian */ + 'sl' | + /** Albanian */ + 'sq' | + /** Serbian */ + 'sr' | + /** Swedish */ + 'sv' | + /** Tamil */ + 'ta' | + /** Telugu */ + 'te' | + /** Thai */ + 'th' | + /** Tagalog */ + 'tl' | + /** Turkish */ + 'tr' | + /** Ukrainian */ + 'uk' | + /** Uzbek */ + 'uz' | + /** Vietnamese */ + 'vi' | + /** Chinese (Simlified) */ + 'zh-CN' | + /** Chinese (Traditional) */ + 'zh-TW' +); + +export type GoogleMapsClientEndpoint = (query: Request, callback?: ResponseCallback) => RequestHandle; + +export interface GoogleMapsClient { + /** + * The Directions API is a service that calculates directions between locations using an HTTP request. + * + * With the Directions API, you can: + * - Search for directions for several modes of transportation, including transit, driving, walking or cycling. + * - Return multi-part directions using a series of waypoints. + * - Specify origins, destinations, and waypoints as text strings + * (e.g. "Chicago, IL" or "Darwin, NT, Australia"), or as latitude/longitude coordinates, or as place IDs. + * + * The API returns the most efficient routes when calculating directions. Travel time is the primary factor optimized, + * but the API may also take into account other factors such as distance, number of turns and many more when deciding + * which route is the most efficient. + * + * **Tip:** Calculating directions is a time and resource intensive task. Whenever possible, use the service to calculate + * known addresses ahead of time and store the results in a + * [**temporary cache**](https://developers.google.com/maps/documentation/directions/policies#pre-fetching-caching-or-storage-of-content) + * of your own design. + * + * **Note:** This service is not designed to respond in real time to user input. For dynamic directions calculations + * (for example, within a user interface element), consult the documentation for the + * [Maps JavaScript API Directions Service](https://developers.google.com/maps/documentation/javascript/directions) + * + * @see https://developers.google.com/maps/documentation/directions/intro + */ + directions: GoogleMapsClientEndpoint; + /** + * The Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations. + * The API returns information based on the recommended route between start and end points, as calculated by the Google Maps API, + * and consists of rows containing duration and distance values for each pair. + * + * @see https://developers.google.com/maps/documentation/distance-matrix/intro + */ + distanceMatrix: GoogleMapsClientEndpoint; + /** + * The Elevation API provides a simple interface to query locations on the earth for elevation data. With the Elevation API, + * you can develop hiking and biking applications, positioning applications, or low resolution surveying applications. + * + * Elevation data is available for all locations on the surface of the earth, including depth locations on the ocean floor + * (which return negative values). In those cases where Google does not possess exact elevation measurements at the precise + * location you request, the service interpolates and returns an averaged value using the four nearest locations. + * Elevation values are expressed relative to local mean sea level (LMSL). + * + * You access the Elevation API through an HTTP interface. Users of the Maps JavaScript API may also access this API directly + * by using the `ElevationService()` object. + * (See [Elevation Service](https://developers.google.com/maps/documentation/javascript/elevation) for more information.) + * + * @see https://developers.google.com/maps/documentation/elevation/intro + */ + elevation: GoogleMapsClientEndpoint; + /** + * You may request sampled elevation data along paths, allowing you to calculate elevation changes along routes. + * With the Elevation API, you can develop hiking and biking applications, positioning applications, + * or low resolution surveying applications. + * + * @see https://developers.google.com/maps/documentation/elevation/intro + */ + elevationAlongPath: GoogleMapsClientEndpoint; + /** + * The Places API allows you to query for place information on a variety of categories, such as: establishments, + * prominent points of interest, geographic locations, and more. You can search for places either by proximity or a text string. + * A Place Search returns a list of places along with summary information about each place; additional information is available + * via a [Place Details](https://developers.google.com/places/web-service/details) query. + * + * A Find Place request takes a text input, and returns a place. + * The text input can be any kind of Places data, for example, a name, address, or phone number. + * + * @see https://developers.google.com/places/web-service/search#FindPlaceRequests + */ + findPlace: GoogleMapsClientEndpoint; + /** + * **Geocoding** is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") + * into geographic coordinates (like latitude 37.423021 and longitude -122.083739), + * which you can use to place markers on a map, or position the map. + * + * **Note:** This service is generally designed for geocoding static (known in advance) addresses for placement + * of application content on a map; this service is not designed to respond in real time to user input. + * For dynamic geocoding (for example, within a user interface element), consult the documentation for the + * [Maps JavaScript API client geocoder](https://developers.google.com/maps/documentation/javascript/geocoding) and/or the + * [Google Play services Location APIs](https://developer.android.com/google/play-services/location.html). + * + * **Tip:** Geocoding is a time and resource intensive task. Whenever possible, pre-geocode known addresses + * (using the Geocoding API described here or another geocoding service), and store your results in a + * [**temporary cache**](https://developers.google.com/maps/documentation/geocoding/policies#pre-fetching-caching-or-storage-of-content) + * of your own design. + * + * @see https://developers.google.com/maps/documentation/geocoding/intro#GeocodingRequests + */ + geocode: GoogleMapsClientEndpoint; + /** + * The Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes + * that the mobile client can detect. This document describes the protocol used to send this data to the server and + * to return a response to the client. + * + * @see https://developers.google.com/maps/documentation/geolocation/intro + */ + geolocate: GoogleMapsClientEndpoint; + /** + * The Roads API takes up to 100 independent coordinates, and returns the closest road segment for each point. + * The points passed do not need to be part of a continuous path. + * + * If you are working with sequential GPS points, use [Snap to Roads](https://developers.google.com/maps/documentation/roads/snap). + * + * @see https://developers.google.com/maps/documentation/roads/nearest + */ + nearestRoads: GoogleMapsClientEndpoint; + /** + * Once you have a `place_id` from a Place Search, you can request more details about a particular establishment + * or point of interest by initiating a Place Details request. A Place Details request returns more comprehensive + * information about the indicated place such as its complete address, phone number, user rating and reviews. + * + * @see https://developers.google.com/places/web-service/details + */ + place: GoogleMapsClientEndpoint; + /** + * The Google Places API Text Search Service is a web service that returns information about a set of places + * based on a string — for example "pizza in New York" or "shoe stores near Ottawa" or "123 Main Street". + * The service responds with a list of places matching the text string and any location bias that has been set. + * + * The service is especially useful for making + * [ambiguous address queries](https://developers.google.com/maps/documentation/geocoding/best-practices) in an automated system, + * and non-address components of the string may match businesses as well as addresses. + * Examples of ambiguous address queries are incomplete addresses, poorly formatted addresses, + * or a request that includes non-address components such as business names. + * + * The search response will include a list of places. You can send a Place Details request + * for more information about any of the places in the response. + * + * @see https://developers.google.com/places/web-service/search#TextSearchRequests + */ + places: GoogleMapsClientEndpoint; + /** + * The Place Autocomplete service is a web service that returns place predictions in response to an HTTP request. + * The request specifies a textual search string and optional geographic bounds. + * The service can be used to provide autocomplete functionality for text-based geographic searches, + * by returning places such as businesses, addresses and points of interest as a user types. + * + * @see https://developers.google.com/places/web-service/autocomplete + */ + placesAutoComplete: GoogleMapsClientEndpoint; + /** + * A Nearby Search lets you search for places within a specified area. + * You can refine your search request by supplying keywords or specifying the type of place you are searching for. + * + * @see https://developers.google.com/places/web-service/search#PlaceSearchRequests + */ + placesNearby: GoogleMapsClientEndpoint; + /** + * The Place Photo service, part of the Places API, is a read- only API that allows you to add high quality photographic content + * to your application. The Place Photo service gives you access to the millions of photos stored in the Places database. + * When you get place information using a Place Details request, photo references will be returned for relevant photographic content. + * The Nearby Search and Text Search requests also return a single photo reference per place, when relevant. + * Using the Photo service you can then access the referenced photos and resize the image to the optimal size for your application. + * + * @see https://developers.google.com/places/web-service/photos + */ + placesPhoto: GoogleMapsClientEndpoint; + /** + * The Query Autocomplete service can be used to provide a query prediction for text-based geographic searches, + * by returning suggested queries as you type. + * + * The Query Autocomplete service allows you to add on-the-fly geographic query predictions to your application. + * Instead of searching for a specific location, a user can type in a categorical search, such as "pizza near New York" + * and the service responds with a list of suggested queries matching the string. As the Query Autocomplete service can match + * on both full words and substrings, applications can send queries as the user types to provide on-the-fly predictions. + * + * @see https://developers.google.com/places/web-service/query + */ + placesQueryAutoComplete: GoogleMapsClientEndpoint; + /** + * The Google Places API Radar Search Service allows you to search for up to 200 places at once, + * but with less detail than is typically returned from a Text Search or Nearby Search request. + * With Radar Search, you can create applications that help users identify specific areas of interest within a geographic area. + * + * The search response will include up to 200 places, and will include only the following information about each place: + * - The `geometry` field containing geographic coordinates. + * - The `place_id`, which you can use in a Place Details request to get more information about the place. + * + * @deprecated Radar search is deprecated as of June 30, 2018. After that time, this feature will no longer be available. + * + * @see https://developers.google.com/places/web-service/search#RadarSearchRequests + */ + placesRadar: GoogleMapsClientEndpoint; + /** + * Reverse geocoding is the process of converting geographic coordinates into a human-readable address. + * + * @see https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding + */ + reverseGeocode: GoogleMapsClientEndpoint; + /** + * The Roads API returns the posted speed limit for a given road segment. + * In the case of road segments with variable speed limits, the default speed limit for the segment is returned. + * + * The accuracy of speed limit data returned by the Roads API cannot be guaranteed. + * The speed limit data provided is not real-time, and may be estimated, inaccurate, incomplete, and/or outdated. + * You may report inaccuracies in our speed limit data by filing a case in the + * [Google Cloud Support Portal](https://developers.google.com/maps/premium/support#support_portal). + * + * @see https://developers.google.com/maps/documentation/roads/speed-limits + */ + snappedSpeedLimits: GoogleMapsClientEndpoint; + /** + * The Roads API takes up to 100 GPS points collected along a route, and returns a similar set of data, + * with the points snapped to the most likely roads the vehicle was traveling along. + * Optionally, you can request that the points be interpolated, resulting in a path that smoothly follows the geometry of the road. + * + * @see https://developers.google.com/maps/documentation/roads/snap + */ + snapToRoads: GoogleMapsClientEndpoint; + /** + * The Roads API returns the posted speed limit for a given road segment. + * In the case of road segments with variable speed limits, the default speed limit for the segment is returned. + * + * The accuracy of speed limit data returned by the Roads API cannot be guaranteed. + * The speed limit data provided is not real-time, and may be estimated, inaccurate, incomplete, and/or outdated. + * You may report inaccuracies in our speed limit data by filing a case in the + * [Google Cloud Support Portal](https://developers.google.com/maps/premium/support#support_portal). + * + * @see https://developers.google.com/maps/documentation/roads/speed-limits + */ + speedLimits: GoogleMapsClientEndpoint; + /** + * The Time Zone API provides a simple interface to request the time zone for locations on the surface of the earth, + * as well as the time offset from UTC for each of those locations. You request the time zone information for + * a specific latitude/longitude pair and date. The API returns the name of that time zone, the time offset from UTC, + * and the daylight savings offset. + * + * @see https://developers.google.com/maps/documentation/timezone/intro + */ + timezone: GoogleMapsClientEndpoint; +} + +export interface DirectionsRequest { + /** + * The address, textual latitude/longitude value, or place ID from which you wish to calculate directions. + * - If you pass an address, the Directions service geocodes the string and converts it to a latitude/longitude coordinate + * to calculate directions. This coordinate may be different from that returned by the Geocoding API, for example a building + * entrance rather than its center. + * + * `origin=24+Sussex+Drive+Ottawa+ON` + * + * - If you pass coordinates, they are used unchanged to calculate directions. Ensure that no space exists between the latitude + * and longitude values. + * + * `origin=41.43206,-81.38992` + * + * - Place IDs must be prefixed with `place_id:`. The place ID may only be specified if the request includes an API key or a + * Google Maps APIs Premium Plan client ID. You can retrieve place IDs from the Geocoding API and the Places SDK + * (including Place Autocomplete). For an example using place IDs from Place Autocomplete, see [Place Autocomplete and + * Directions](https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions). + * + * `origin=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE` + */ + origin: LatLng; + /** + * The address, textual latitude/longitude value, or place ID to which you wish to calculate directions. + * The options for the `destination` parameter are the same as for the `origin` parameter, described above + */ + destination: LatLng; + /** + * Specifies the mode of transport to use when calculating directions + * + * @default TravelMode.driving + */ + mode?: TravelMode; + /** + * Specifies an array of waypoints. + * Waypoints alter a route by routing it through the specified location(s). + * A waypoint is specified as a latitude/longitude coordinate, an encoded polyline, a place ID, or an address which will be geocoded. + * Encoded polylines must be prefixed with `enc:` and followed by a colon (`:`). Place IDs must be prefixed with `place_id:`. + * The place ID may only be specified if the request includes an API key or a Google Maps APIs Premium Plan client ID. + * Waypoints are only supported for driving, walking and bicycling directions. + */ + waypoints?: LatLng[]; + /** + * If set to `true`, specifies that the Directions service may provide more than one route alternative in the response. + * Note that providing route alternatives may increase the response time from the server. + */ + alternatives?: boolean; + /** Indicates that the calculated route(s) should avoid the indicated features. */ + avoid?: TravelRestriction[]; + /** + * The language in which to return results. + * + * - If `language` is not supplied, the API attempts to use the preferred language as specified in the `Accept-Language` header, + * or the native language of the domain from which the request is sent. + * - The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, + * it returns street addresses in the local language, transliterated to a script readable by the user if necessary, + * observing the preferred language. All other addresses are returned in the preferred language. + * Address components are all returned in the same language, which is chosen from the first component. + * - If a name is not available in the preferred language, the API uses the closest match. + * - The preferred language has a small influence on the set of results that the API chooses to return, + * and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, + * such as the abbreviations for street types, or synonyms that may be valid in one language but not in another. + * For example, utca and tér are synonyms for street in Hungarian. + */ + language?: Language; + /** Specifies the unit system to use when displaying results. */ + units?: UnitSystem; + /** Specifies the region code, specified as a ccTLD ("top-level domain") two-character value. */ + region?: string; + /** + * Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. + * You can specify either `departure_time` or `arrival_time`, but not both. + * Note that `arrival_time` must be specified as an integer. + */ + arrival_time?: Date | number; + /** + * Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. + * Alternatively, you can specify a value of `now`, which sets the departure time to the current time (correct to the nearest second). + * + * The departure time may be specified in two cases: + * - For requests where the travel mode is transit: You can optionally specify one of `departure_time` or `arrival_time`. + * If neither time is specified, the `departure_time` defaults to now (that is, the departure time defaults to the current time). + * - For requests where the travel mode is driving: You can specify the `departure_time` to receive a route and trip duration + * (response field: `duration_in_traffic`) that take traffic conditions into account. + * This option is only available if the request contains a valid API key, or a valid Google Maps APIs Premium Plan client ID + * and signature. The `departure_time` must be set to the current time or some time in the future. It cannot be in the past. + */ + departure_time?: Date | number; + /** + * Specifies the assumptions to use when calculating time in traffic. + * This setting affects the value returned in the `duration_in_traffic` field in the response, which contains the predicted time + * in traffic based on historical averages. The `traffic_model` parameter may only be specified for driving directions + * where the request includes a `departure_time`, and only if the request includes an API key or a Google Maps APIs Premium Plan client ID. + * + * The default value of `best_guess` will give the most useful predictions for the vast majority of use cases. + * It is possible the `best_guess` travel time prediction may be *shorter* than `optimistic`, or alternatively, + * *longer* than `pessimistic`, due to the way the `best_guess` prediction model integrates live traffic information. + * + * @default TrafficModel.best_guess + */ + traffic_model?: TrafficModel; + /** + * Specifies one or more preferred modes of transit. + * This parameter may only be specified for transit directions, and only if the request includes an API key or + * a Google Maps APIs Premium Plan client ID. + */ + transit_mode?: TransitMode[]; + /** + * Specifies preferences for transit routes. + * Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. + * This parameter may only be specified for transit directions, and only if the request includes an API key or + * a Google Maps APIs Premium Plan client ID. + */ + transit_routing_preference?: TransitRoutingPreference; + /** Wherever to optimize the provided route by rearranging the waypoints in a more efficient order. */ + optimize?: boolean; +} + +/** + * When you calculate directions, you may specify the transportation mode to use. + * By default, directions are calculated as `driving` directions. + * + * **Note:** Both walking and bicycling directions may sometimes not include clear pedestrian or bicycling paths, + * so these directions will return warnings in the returned result which you must display to the user. + */ +export type TravelMode = ( + /** (default) indicates standard driving directions using the road network. */ + 'driving' | + /** requests walking directions via pedestrian paths & sidewalks (where available). */ + 'walking' | + /** requests bicycling directions via bicycle paths & preferred streets (where available). */ + 'bicycling' | + /** + * requests directions via public transit routes (where available). + * If you set the mode to transit, you can optionally specify either a departure_time or an arrival_time. + * If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). + * You can also optionally include a transit_mode and/or a transit_routing_preference. + */ + 'transit' +); + +export type TravelRestriction = ( + /** indicates that the calculated route should avoid toll roads/bridges. */ + 'tolls' | + /** indicates that the calculated route should avoid highways. */ + 'highways' | + /** indicates that the calculated route should avoid ferries. */ + 'ferries' | + /** + * indicates that the calculated route should avoid indoor steps for walking and transit directions. + * Only requests that include an API key or a Google Maps APIs Premium Plan client ID will receive indoor steps by default. + */ + 'indoor' +); + +/** + * Directions results contain text within distance fields that may be displayed to the user to indicate the distance of + * a particular "step" of the route. By default, this text uses the unit system of the origin's country or region. + */ +export type UnitSystem = ( + /** specifies usage of the metric system. Textual distances are returned using kilometers and meters. */ + 'metric' | + /** specifies usage of the Imperial (English) system. Textual distances are returned using miles and feet. */ + 'imperial' +); + +export interface DirectionsResponse { + /** contains metadata on the request. */ + status: DirectionsReponseStatus; + /** + * contains an array with details about the geocoding of origin, destination and waypoints. + * + * These details will not be present for waypoints specified as textual latitude/longitude values if the service returns no results. + * This is because such waypoints are only reverse geocoded to obtain their representative address after a route has been found. + * An empty JSON object will occupy the corresponding places in the `geocoded_waypoints` array. + */ + geocoded_waypoints: GeocodedWaypoint[]; + /** + * contains an array of routes from the origin to the destination. + * + * When the Directions API returns results, it places them within a (JSON) `routes` array. Even if the service returns no results + * (such as if the origin and/or destination doesn't exist) it still returns an empty `routes` array. + * (XML responses consist of zero or more `` elements.) + * + * Each element of the `routes` array contains a single result from the specified origin and destination. + * This route may consist of one or more `legs` depending on whether any waypoints were specified. + * As well, the route also contains copyright and warning information which must be displayed to the user in addition to the + * routing information. + */ + routes: DirectionsRoute[]; + /** + * contains an array of available travel modes. This field is returned when a request specifies a travel `mode` and gets no results. + * The array contains the available travel modes in the countries of the given set of waypoints. + * This field is not returned if one or more of the waypoints are `via:` waypoints. + */ + available_travel_modes: string[]; +} + +export type TrafficModel = ( + /** + * indicates that the returned `duration_in_traffic` should be the best estimate of travel time given what is known about + * both historical traffic conditions and live traffic. Live traffic becomes more important the closer the `departure_time` is to now. + */ + 'best_guess' | + /** + * indicates that the returned `duration_in_traffic` should be longer than the actual travel time on most days, + * though occasional days with particularly bad traffic conditions may exceed this value. + */ + 'pessimistic' | + /** + * indicates that the returned `duration_in_traffic` should be shorter than the actual travel time on most days, + * though occasional days with particularly good traffic conditions may be faster than this value. + */ + 'optimistic' +); + +export type TransitMode = ( + /** indicates that the calculated route should prefer travel by bus. */ + 'bus' | + /** indicates that the calculated route should prefer travel by subway. */ + 'subway' | + /** indicates that the calculated route should prefer travel by train. */ + 'train' | + /** indicates that the calculated route should prefer travel by tram and light rail. */ + 'tram' | + /** + * indicates that the calculated route should prefer travel by train, tram, light rail, and subway. + * This is equivalent to `transit_mode=train|tram|subway` + */ + 'rail' +); + +export type TransitRoutingPreference = ( + /** indicates that the calculated route should prefer limited amounts of walking. */ + 'less_walking' | + /** indicates that the calculated route should prefer a limited number of transfers. */ + 'fewer_transfers' +); + +/** + * The `status` field within the Directions response object contains the status of the request, and may contain debugging information + * to help you track down why the Directions service failed. + */ +export type DirectionsReponseStatus = ( + /** indicates the response contains a valid `result`. */ + 'OK' | + /** indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded. */ + 'NOT_FOUND' | + /** indicates no route could be found between the origin and destination. */ + 'ZERO_RESULTS' | + /** + * indicates that too many `waypoints` were provided in the request. For applications using the Directions API as a web service, + * or the [directions service in the Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/directions), + * the maximum allowed number of `waypoints` is 23, plus the origin and destination. + */ + 'MAX_WAYPOINTS_EXCEEDED' | + /** + * indicates the requested route is too long and cannot be processed. + * This error occurs when more complex directions are returned. + * Try reducing the number of waypoints, turns, or instructions. + */ + 'MAX_ROUTE_LENGTH_EXCEEDED ' | + /** indicates that the provided request was invalid. Common causes of this status include an invalid parameter or parameter value. */ + 'INVALID_REQUEST' | + /** + * indicates any of the following: + * - The API key is missing or invalid. + * - Billing has not been enabled on your account. + * - A self-imposed usage cap has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this. + */ + 'OVER_DAILY_LIMIT' | + /** indicates the service has received too many requests from your application within the allowed time period. */ + 'OVER_QUERY_LIMIT' | + /** indicates that the service denied use of the directions service by your application. */ + 'REQUEST_DENIED' | + /** indicates a directions request could not be processed due to a server error. The request may succeed if you try again. */ + 'UNKNOWN_ERROR' +); + +/** + * Elements in the `geocoded_waypoints` array correspond, by their zero-based position, to the origin, + * the waypoints in the order they are specified, and the destination. + */ +export interface GeocodedWaypoint { + /** indicates the status code resulting from the geocoding operation. */ + geocoder_status: GeocodedWaypointStatus; + /** + * indicates that the geocoder did not return an exact match for the original request, though it was able to match part of the + * requested address. You may wish to examine the original request for misspellings and/or an incomplete address. + * + * Partial matches most often occur for street addresses that do not exist within the locality you pass in the request. + * Partial matches may also be returned when a request matches two or more locations in the same locality. + * For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street. + * Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address. + * Suggestions triggered in this way will also be marked as a partial match. + */ + partial_match: boolean; + /** unique identifier that can be used with other Google APIs. */ + place_id: string; + /** + * indicates the *address type* of the geocoding result used for calculating directions. + * + * An empty list of types indicates there are no known types for the particular address component, for example, Lieu-dit in France. + */ + types: AddressType[]; +} + +export type GeocodedWaypointStatus = ( + /** indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned. */ + 'OK' | + /** + * indicates that the geocode was successful but returned no results. + * This may occur if the geocoder was passed a non-existent `address`. + */ + 'ZERO_RESULTS' +); + +export type AddressType = ( + /** indicates a precise street address. */ + 'street_address' | + /** indicates a named route (such as "US 101"). */ + 'route' | + /** indicates a major intersection, usually of two major roads. */ + 'intersection' | + /** indicates a political entity. Usually, this type indicates a polygon of some civil administration. */ + 'political' | + /** indicates the national political entity, and is typically the highest order type returned by the Geocoder. */ + 'country' | + /** + * indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. + * Not all nations exhibit these administrative levels. In most cases, `administrative_area_level_1` short names will closely match + * ISO 3166-2 subdivisions and other widely circulated lists; however this is not guaranteed as our geocoding results are based + * on a variety of signals and location data. + */ + 'administrative_area_level_1' | + /** + * indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. + * Not all nations exhibit these administrative levels. + */ + 'administrative_area_level_2' | + /** + * indicates a third-order civil entity below the country level. This type indicates a minor civil division. + * Not all nations exhibit these administrative levels. + */ + 'administrative_area_level_3' | + /** + * indicates a fourth-order civil entity below the country level. This type indicates a minor civil division. + * Not all nations exhibit these administrative levels. + */ + 'administrative_area_level_4' | + /** + * indicates a fifth-order civil entity below the country level. This type indicates a minor civil division. + * Not all nations exhibit these administrative levels. + */ + 'administrative_area_level_5' | + /** indicates a commonly-used alternative name for the entity. */ + 'colloquial_area' | + /** indicates an incorporated city or town political entity. */ + 'locality' | + /** + * indicates a specific type of Japanese locality, to facilitate distinction between multiple locality components within a + * Japanese address. + */ + 'ward' | + /** + * indicates a first-order civil entity below a locality. For some locations may receive one of the additional types: + * `sublocality_level_1` to `sublocality_level_5`. Each sublocality level is a civil entity. Larger numbers indicate a smaller + * geographic area. + */ + 'sublocality' | + /** indicates a named neighborhood */ + 'neighborhood' | + /** indicates a named location, usually a building or collection of buildings with a common name */ + 'premise' | + /** + * indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a + * common name. + */ + 'subpremise' | + /** indicates a postal code as used to address postal mail within the country. */ + 'postal_code' | + /** indicates a prominent natural feature. */ + 'natural_feature' | + /** indicates an airport. */ + 'airport' | + /** indicates a named park. */ + 'park' | + /** + * indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category, + * such as "Empire State Building" or "Statue of Liberty". + */ + 'point_of_interest' +); + +/** + * This route may consist of one or more `legs` depending on whether any waypoints were specified. As well, the route also contains + * copyright and warning information which must be displayed to the user in addition to the routing information. + */ +export interface DirectionsRoute { + /** contains a short textual description for the route, suitable for naming and disambiguating the route from alternatives. */ + summary: string; + /** + * contains an array which contains information about a leg of the route, between two locations within the given route. + * A separate leg will be present for each waypoint or destination specified. + * (A route with no waypoints will contain exactly one leg within the `legs` array.) + * Each leg consists of a series of `steps`. + */ + legs: RouteLeg[]; + /** + * contains an array indicating the order of any waypoints in the calculated route. + * This waypoints may be reordered if the request was passed `optimize:true` within its `waypoints` parameter. + */ + waypoint_order: number[]; + /** + * contains a single `points` object that holds an encoded polyline representation of the route. + * This polyline is an approximate (smoothed) path of the resulting directions. + */ + overview_polyline: string; + /** contains the viewport bounding box of the `overview_polyline`. */ + bounds: LatLngBounds; + /** contains the copyrights text to be displayed for this route. You must handle and display this information yourself. */ + copyrights: string; + /** contains an array of warnings to be displayed when showing these directions. You must handle and display these warnings yourself. */ + warnings: string[]; + /** + * If present, contains the total fare (that is, the total ticket costs) on this route. + * This property is only returned for transit requests and only for routes where fare information is available for all transit legs. + * + * **Note:** The Directions API only returns fare information for requests that contain either an API key or a client ID + * and digital signature. + */ + fare: TransitFare; + /** + * An array of LatLngs representing the entire course of this route. The path is simplified in order to make + * it suitable in contexts where a small number of vertices is required (such as Static Maps API URLs). + */ + overview_path: LatLngLiteral[]; +} + +export interface TransitFare { + /** An [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217) indicating the currency that the amount is expressed in. */ + currency: string; + /** The total fare amount, in the currency specified above. */ + value: number; + /** The total fare amount, formatted in the requested language. */ + text: string; +} + +/** + * A single leg of the journey from the origin to the destination in the calculated route. + * For routes that contain no waypoints, the route will consist of a single "leg," but for routes that define one or more waypoints, + * the route will consist of one or more legs, corresponding to the specific legs of the journey. + */ +export interface RouteLeg { + /** contains an array of steps denoting information about each separate step of the leg of the journey. */ + steps: DirectionsStep[]; + /** + * indicates the total distance covered by this leg, as a field with the following elements. + * + * This field may be absent if the distance is unknown. + */ + distance: Distance; + /** + * indicates the total duration of this leg. + * + * This field may be absent if the duration is unknown. + */ + duration: Duration; + /** + * indicates the total duration of this leg. + * This value is an estimate of the time in traffic based on current and historical traffic conditions. + * See the `traffic_model` request parameter for the options you can use to request that the returned value is optimistic, pessimistic, + * or a best-guess estimate. The duration in traffic is returned only if all of the following are true: + * + * - The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature. + * - The request does not include stopover waypoints. If the request includes waypoints, they must be prefixed with `via:` + * to avoid stopovers. + * - The request is specifically for driving directions—the `mode` parameter is set to `driving`. + * - The request includes a `departure_time` parameter. + * - Traffic conditions are available for the requested route. + */ + duration_in_traffic: Duration; + /** contains the estimated time of arrival for this leg. This property is only returned for transit directions. */ + arrival_time: Time; + /** + * contains the estimated time of departure for this leg, specified as a `Time` object. + * The `departure_time` is only available for transit directions. + */ + departure_time: Time; + /** + * contains the latitude/longitude coordinates of the origin of this leg. + * Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road) + * at the start and end points, `start_location` may be different than the provided origin of this leg if, for example, + * a road is not near the origin. + */ + start_location: LatLngLiteral; + /** + * contains the latitude/longitude coordinates of the given destination of this leg. + * Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road) + * at the start and end points, `end_location` may be different than the provided destination of this leg if, for example, + * a road is not near the destination. + */ + end_location: LatLngLiteral; + /** contains the human-readable address (typically a street address) resulting from reverse geocoding the `start_location` of this leg. */ + start_address: string; + /** contains the human-readable address (typically a street address) from reverse geocoding the `end_location` of this leg. */ + end_address: string; +} + +/** + * A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey. + * E.g. "Turn left at W. 4th St." The step not only describes the instruction but also contains distance and duration information relating to + * how this step relates to the following step. For example, a step denoted as "Merge onto I-80 West" may contain a duration of + * "37 miles" and "40 minutes," indicating that the next step is 37 miles/40 minutes from this step. + * + * When using the Directions API to search for transit directions, the steps array will include additional transit details in the form of + * a `transit_details` array. If the directions include multiple modes of transportation, detailed directions will be provided for walking or + * driving steps in an inner `steps` array. For example, a walking step will include directions from the start and end locations: + * "Walk to Innes Ave & Fitch St". That step will include detailed walking directions for that route in the inner `steps` array, such as: + * "Head north-west", "Turn left onto Arelious Walker", and "Turn left onto Innes Ave". + */ +export interface DirectionsStep { + /** contains formatted instructions for this step, presented as an HTML text string. */ + html_instructions: string; + /** + * contains the distance covered by this step until the next step. (See the discussion of this field in Directions Legs) + * + * This field may be undefined if the distance is unknown. + */ + distance: Distance; + /** + * contains the typical time required to perform the step, until the next step. (See the description in Directions Legs) + * + * This field may be undefined if the duration is unknown + */ + duration: Duration; + /** contains the location of the starting point of this step, as a single set of `lat` and `lng` fields. */ + start_location: LatLngLiteral; + /** contains the location of the last point of this step, as a single set of `lat` and `lng` fields. */ + end_location: LatLngLiteral; + /** + * contains the action to take for the current step (turn left, merge, straight, etc.). + * This field is used to determine which icon to display. + */ + maneuver: Maneuver; + /** + * contains a single points object that holds an encoded polyline representation of the step. + * This polyline is an approximate (smoothed) path of the step. + */ + polyline: string; + /** + * contains detailed directions for walking or driving steps in transit directions. + * Substeps are only available when `travel_mode` is set to "transit". + * The inner `steps` array is of the same type as `steps`. + */ + steps: DirectionsStep; + /** contains transit specific information. This field is only returned with travel_mode is set to "transit". */ + transit_details: TransitDetails; +} + +export interface Distance { + /** indicates the distance in meters. */ + value: number; + /** + * contains a human-readable representation of the distance, displayed in units as used at the origin + * (or as overridden within the `units` parameter in the request). + * (For example, miles and feet will be used for any origin within the United States.) + */ + text: string; +} + +export interface Duration { + /** indicates the duration in seconds. */ + value: number; + /** contains a human-readable representation of the duration. */ + text: string; +} + +export interface Time { + /** the time specified as a JavaScript `Date` object. */ + value: Date; + /** the time specified as a string. The time is displayed in the time zone of the transit stop. */ + text: string; + /** + * contains the time zone of this station. The value is the name of the time zone as defined in the + * [IANA Time Zone Database](http://www.iana.org/time-zones), e.g. "America/New_York". + */ + time_zone: string; +} + +export type Maneuver = ( + 'turn-slight-left' | + 'turn-sharp-left' | + 'uturn-left' | + 'turn-left' | + 'turn-slight-right' | + 'turn-sharp-right' | + 'uturn-right' | + 'turn-right' | + 'straight' | + 'ramp-left' | + 'ramp-right' | + 'merge' | + 'fork-left' | + 'fork-right' | + 'ferry' | + 'ferry-train' | + 'roundabout-left' | + 'roundabout-right' +); + +/** + * Transit directions return additional information that is not relevant for other modes of transportation. + * These additional properties are exposed through the `transit_details` object, returned as a field of an element in the `steps[]` array. + * From the `TransitDetails` object you can access additional information about the transit stop, transit line and transit agency + */ +export interface TransitDetails { + /** contains information about the stop for this part of the trip. */ + arrival_stop: TransitStop; + /** contains information about the station for this part of the trip. */ + departure_stop: TransitStop; + /** contain the arrival time for this leg of the journey. */ + arrival_time: Time; + /** contain the departure time for this leg of the journey. */ + departure_time: Time; + /** + * specifies the direction in which to travel on this line, as it is marked on the vehicle or at the departure stop. + * This will often be the terminus station. + */ + headsign: string; + /** + * specifies the expected number of seconds between departures from the same stop at this time. + * For example, with a `headway` value of 600, you would expect a ten minute wait if you should miss your bus. + */ + headway: number; + /** + * contains the number of stops in this step, counting the arrival stop, but not the departure stop. + * For example, if your directions involve leaving from Stop A, passing through stops B and C, and arriving at stop D, + * `num_stops` will return 3. + */ + num_stops: number; + /** contains information about the transit line used in this step. */ + line: TransitLine; +} + +export interface TransitStop { + /** the name of the transit station/stop. eg. "Union Square". */ + name: string; + /** the location of the transit station/stop, represented as a `lat` and `lng` field. */ + location: LatLngLiteral; +} + +export interface TransitLine { + /** contains the full name of this transit line. eg. "7 Avenue Express". */ + name: string; + /** contains the short name of this transit line. This will normally be a line number, such as "M7" or "355". */ + short_name: string; + /** contains the color commonly used in signage for this transit line. The color will be specified as a hex string such as: #FF0033. */ + color: string; + /** + * is an array containing a single `TransitAgency` object. + * The `TransitAgency` object provides information about the operator of the line + */ + agencies: TransitAgency[]; + /** contains the URL for this transit line as provided by the transit agency. */ + url: string; + /** contains the URL for the icon associated with this line. */ + icon: string; + /** contains the color of text commonly used for signage of this line. The color will be specified as a hex string. */ + text_color: string; + /** contains the type of vehicle used on this line. */ + vehicle: TransitVehicle; +} + +/** You must display the names and URLs of the transit agencies servicing the trip results. */ +export interface TransitAgency { + /** contains the name of the transit agency. */ + name: string; + /** contains the phone number of the transit agency. */ + phone: string; + /** contains the URL for the transit agency. */ + url: string; +} + +export interface TransitVehicle { + /** contains the name of the vehicle on this line. eg. "Subway.". */ + name: string; + /** contains the type of vehicle that runs on this line. */ + type: VehicleType; + /** contains the URL for an icon associated with this vehicle type. */ + icon: string; + /** contains the URL for the icon associated with this vehicle type, based on the local transport signage. */ + local_icon: string; +} + +/** @see https://developers.google.com/maps/documentation/directions/intro#VehicleType. */ +export type VehicleType = ( + /** Rail. */ + 'RAIL' | + /** Light rail transit. */ + 'METRO_RAIL' | + /** Underground light rail. */ + 'SUBWAY' | + /** Above ground light rail. */ + 'TRAM' | + /** Monorail. */ + 'MONORAIL' | + /** Heavy rail. */ + 'HEAVY_RAIL' | + /** Commuter rail. */ + 'COMMUTER_TRAIN' | + /** High speed train. */ + 'HIGH_SPEED_TRAIN' | + /** Bus. */ + 'BUS' | + /** Intercity bus. */ + 'INTERCITY_BUS' | + /** Trolleybus. */ + 'TROLLEYBUS' | + /** Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route. */ + 'SHARE_TAXI' | + /** Ferry. */ + 'FERRY' | + /** A vehicle that operates on a cable, usually on the ground. Aerial cable cars may be of the type `GONDOLA_LIFT`. */ + 'CABLE_CAR' | + /** An aerial cable car. */ + 'GONDOLA_LIFT' | + /** + * A vehicle that is pulled up a steep incline by a cable. + * A Funicular typically consists of two cars, with each car acting as a counterweight for the other. + */ + 'FUNICULAR' | + /** All other vehicles will return this type. */ + 'OTHER' +); + +export interface DistanceMatrixRequest { + /** + * The starting point for calculating travel distance and time. + * You can supply one or more locations separated by the pipe character (`|`), in the form of an address, latitude/longitude coordinates, + * or a place ID: + * - If you pass an address, the service geocodes the string and converts it to a latitude/longitude coordinate to calculate distance. + * This coordinate may be different from that returned by the Geocoding API, for example a building entrance rather than its center. + * + * `origins=Bobcaygeon+ON|24+Sussex+Drive+Ottawa+ON` + * + * - If you pass latitude/longitude coordinates, they are used unchanged to calculate distance. + * Ensure that no space exists between the latitude and longitude values. + * + * `origins=41.43206,-81.38992|-33.86748,151.20699` + * + * - If you supply a place ID, you must prefix it with `place_id:`. + * You can only specify a place ID if the request includes an API key or a Google Maps APIs Premium Plan client ID. + * You can retrieve place IDs from the Geocoding API and the Places SDK (including Place Autocomplete). + * + * `origins=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE` + * + * - Alternatively, you can supply an encoded set of coordinates using the + * [Encoded Polyline Algorithm](https://developers.google.com/maps/documentation/utilities/polylinealgorithm). + * This is particularly useful if you have a large number of origin points, because the URL is significantly shorter when using + * an encoded polyline. + * + * - Encoded polylines must be prefixed with `enc:` and followed by a colon (`:`). For example: `origins=enc:gfo}EtohhU:` + * - You can also include multiple encoded polylines, separated by the pipe character (`|`). + * For example: `origins=enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:|enc:udymA{~bxM:` + */ + origins: LatLng[]; + /** + * One or more locations to use as the finishing point for calculating travel distance and time. + * The options for the destinations parameter are the same as for the origins parameter, described above. + */ + destinations: LatLng[]; + /** + * Specifies the mode of transport to use when calculating distance. + * Valid values and other request details are specified in the Travel Modes section of this document. + * + * @default TravelMode.driving + */ + mode?: TravelMode; + /** + * The language in which to return results. + * - If `language` is not supplied, the API attempts to use the preferred language as specified in the `Accept-Language` header, + * or the native language of the domain from which the request is sent. + * - The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, + * it returns street addresses in the local language, transliterated to a script readable by the user if necessary, + * observing the preferred language. All other addresses are returned in the preferred language. + * Address components are all returned in the same language, which is chosen from the first component. + * - If a name is not available in the preferred language, the API uses the closest match. + * - The preferred language has a small influence on the set of results that the API chooses to return, + * and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, + * such as the abbreviations for street types, or synonyms that may be valid in one language but not in another. + * For example, utca and tér are synonyms for street in Hungarian. + */ + language?: string; + /** + * The region code, specified as a [ccTLD](https://en.wikipedia.org/wiki/CcTLD) (country code top-level domain) two-character value. + * Most ccTLD codes are identical to ISO 3166-1 codes, with some exceptions. + * This parameter will only influence, not fully restrict, results from the geocoder. + * If more relevant results exist outside of the specified region, they may be included. + */ + region?: string; + /** + * Introduces restrictions to the route. Valid values are specified in the Restrictions section of this document. + * Only one restriction can be specified. + */ + avoid?: TravelRestriction[]; + /** Specifies the unit system to use when expressing distance as text. */ + units?: UnitSystem; + /** + * Specifies the desired time of arrival for transit requests, in seconds since midnight, January 1, 1970 UTC. + * You can specify either `departure_time` or `arrival_time`, but not both. + * Note that `arrival_time` must be specified as an integer. + */ + arrival_time?: Date | number; + /** + * The desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. + * Alternatively, you can specify a value of now, which sets the departure time to the current time (correct to the nearest second). + * + * The departure time may be specified in two cases: + * + * - For requests where the travel mode is transit: You can optionally specify one of `departure_time` or `arrival_time`. + * If neither time is specified, the `departure_time` defaults to now (that is, the departure time defaults to the current time). + * + * - For requests where the travel mode is driving: You can specify the `departure_time` to receive a route and trip duration + * (response field: `duration_in_traffic`) that take traffic conditions into account. + * This option is only available if the request contains a valid API key, or a valid + * Google Maps APIs Premium Plan client ID and signature. + * The `departure_time` must be set to the current time or some time in the future. It cannot be in the past. + * + * **Note:** Distance Matrix requests specifying `departure_time` when `mode=driving` are limited + * to a maximum of 100 elements per request. The number of origins times the number of destinations defines the number of elements. + */ + departure_time?: Date | number; + /** + * Specifies the assumptions to use when calculating time in traffic. + * This setting affects the value returned in the `duration_in_traffic` field in the response, + * which contains the predicted time in traffic based on historical averages. + * The `traffic_model` parameter may only be specified for requests where the travel mode is `driving`, + * and where the request includes a `departure_time`, and only if the request includes an API key or + * a Google Maps APIs Premium Plan client ID. + * + * @default TrafficModel.best_guess + */ + traffic_model?: TrafficModel; + /** Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the `mode` is `transit`. */ + transit_mode?: TransitMode[]; + /** + * Specifies preferences for transit requests. Using this parameter, you can bias the options returned, + * rather than accepting the default best route chosen by the API. + * This parameter may only be specified for requests where the `mode` is `transit`. + */ + transit_routing_preference?: TransitRoutingPreference; +} + +export interface DistanceMatrixResponse { + /** contains metadata on the request. See Status Codes below. */ + status: DistanceMatrixResponseTopLevelStatus; + /** + * When the top-level status code is other than `OK`, this field contains more detailed information + * about the reasons behind the given status code. + */ + error_message: string; + /** + * contains an array of addresses as returned by the API from your original request. + * These are formatted by the geocoder and localized according to the language parameter passed with the request. + */ + origin_addresses: string; + /** + * contains an array of addresses as returned by the API from your original request. + * As with origin_addresses, these are localized if appropriate. + */ + destination_addresses: string[]; + /** contains an array of elements, which in turn each contain a status, duration, and distance element. */ + rows: DistanceMatrixRow[]; +} + +/** + * The status fields within the response object contain the status of the request, and may contain useful debugging information. + * The Distance Matrix API returns a top-level status field, with information about the request in general, + * as well as a status field for each element field, with information about that particular origin-destination pairing. + */ +export type DistanceMatrixResponseTopLevelStatus = ( + /** indicates the response contains a valid result. */ + 'OK' | + /** indicates that the provided request was invalid. */ + 'INVALID_REQUEST' | + /** indicates that the product of origins and destinations exceeds the per-query limit. */ + 'MAX_ELEMENTS_EXCEEDED' | + /** + * indicates any of the following: + * - The API key is missing or invalid. + * - Billing has not been enabled on your account. + * - A self-imposed usage cap has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this. + */ + 'OVER_DAILY_LIMIT' | + /** indicates the service has received too many requests from your application within the allowed time period. */ + 'OVER_QUERY_LIMIT' | + /** indicates that the service denied use of the Distance Matrix service by your application. */ + 'REQUEST_DENIED' | + /** indicates a Distance Matrix request could not be processed due to a server error. The request may succeed if you try again. */ + 'UNKNOWN_ERROR' +); + +export type DistanceMatrixResponseElementLevelStatus = ( + /** indicates the response contains a valid result. */ + 'OK' | + /** indicates that the origin and/or destination of this pairing could not be geocoded. */ + 'NOT_FOUND' | + /** indicates no route could be found between the origin and destination. */ + 'ZERO_RESULTS' | + /** indicates the requested route is too long and cannot be processed. */ + 'MAX_ROUTE_LENGTH_EXCEEDED' +); + +/** + * When the Distance Matrix API returns results, it places them within a JSON `rows` array. + * Even if no results are returned (such as when the origins and/or destinations don't exist), it still returns an empty array. + * XML responses consist of zero or more `` elements. + * + * Rows are ordered according to the values in the `origin` parameter of the request. + * Each row corresponds to an origin, and each `element` within that row corresponds to a pairing of the origin with a `destination` value. + * + * Each `row` array contains one or more `element` entries, which in turn contain the information about a single origin-destination pairing. + */ +export interface DistanceMatrixRow { + elements: DistanceMatrixRowElement[]; +} + +/** The information about each origin-destination pairing is returned in an `element` entry. */ +export interface DistanceMatrixRowElement { + /** possible status codes */ + status: DistanceMatrixResponseElementLevelStatus; + /** + * The length of time it takes to travel this route, expressed in seconds (the `value` field) and as `text`. + * The textual representation is localized according to the query's `language` parameter. + */ + duration: Duration; + /** + * The length of time it takes to travel this route, based on current and historical traffic conditions. + * See the `traffic_model` request parameter for the options you can use to request that the returned value is + * `optimistic`, `pessimistic`, or a `best-guess` estimate. The duration is expressed in seconds (the `value` field) and as `text`. + * The textual representation is localized according to the query's `language` parameter. + * The duration in traffic is returned only if all of the following are true: + * - The request includes a `departure_time` parameter. + * - The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature. + * - Traffic conditions are available for the requested route. + * - The `mode` parameter is set to `driving`. + */ + duration_in_traffic: Duration; + /** + * The total distance of this route, expressed in meters (`value`) and as `text`. + * The textual value uses the `unit` system specified with the unit parameter of the original request, or the origin's region. + */ + distance: Distance; + /** + * If present, contains the total fare (that is, the total ticket costs) on this route. + * This property is only returned for transit requests and only for transit providers where fare information is available. + */ + fare: TransitFare; +} + +export interface ElevationRequest { + /** + * defines the location(s) on the earth from which to return elevation data. + * This parameter takes either a single location as a comma-separated {latitude,longitude} pair (e.g. "40.714728,-73.998672") + * or multiple latitude/longitude pairs passed as an array or as an encoded polyline. + */ + locations: LatLng[]; +} + +export interface ElevationResponse { + /** An Elevation status code. */ + status: ElevationResponseStatus; + /** + * When the status code is other than `OK`, there may be an additional `error_message` field within the Elevation response object. + * This field contains more detailed information about the reasons behind the given status code. + */ + error_message: string; + /** An Elevation results array. */ + results: ElevationResult[]; +} + +export type ElevationResponseStatus = ( + /** indicating the API request was successful. */ + 'OK' | + /** indicating the API request was malformed. */ + 'INVALID_REQUEST' | + /** + * indicating any of the following: + * The API key is missing or invalid. + * - Billing has not been enabled on your account. + * - A self-imposed usage cap has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this. + */ + 'OVER_DAILY_LIMIT' | + /** indicating the requestor has exceeded quota. */ + 'OVER_QUERY_LIMIT' | + /** indicating the API did not complete the request. */ + 'REQUEST_DENIED' | + /** indicating an unknown error. */ + 'UNKNOWN_ERROR' +); + +export interface ElevationResult { + /** + * A `location` element (containing `lat` and `lng` elements) of the position for which elevation data is being computed. + * Note that for path requests, the set of `location` elements will contain the sampled points along the path. + */ + location: LatLngLiteral; + /** An `elevation` element indicating the elevation of the location in meters. */ + elevation: number; + /** + * A `resolution` value, indicating the maximum distance between data points from which the elevation was interpolated, in meters. + * This property will be missing if the resolution is not known. + * Note that elevation data becomes more coarse (larger `resolution` values) when multiple points are passed. + * To obtain the most accurate elevation value for a point, it should be queried independently. + */ + resolution: number; +} + +export interface ElevationAlongPathRequest { + /** + * defines a path on the earth for which to return elevation data. + * This parameter defines a set of two or more ordered {latitude,longitude} pairs defining a path along the surface of the earth. + */ + path: LatLng[] | string; + /** + * specifies the number of sample points along a path for which to return elevation data. + * The samples parameter divides the given path into an ordered set of equidistant points along the path. + */ + samples: number; +} + +export interface FindPlaceRequest { + /** The text input specifying which place to search for (for example, a name, address, or phone number). */ + input: string; + /** The type of input. This can be one of either `textquery` or `phonenumber`. */ + inputtype: 'textquery' | 'phonenumber'; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Searches are also biased to the selected language; results in the selected language may be given a higher ranking + */ + language?: Language; + /** + * The fields specifying the types of place data to return. + * + * **Note:** If you omit the fields parameter from a Find Place request, only the place_id for the result will be returned. + */ + fields?: Array; + /** + * Prefer results in a specified area, by specifying either a radius plus lat/lng, or two lat/lng pairs representing + * the points of a rectangle. If this parameter is not specified, the API uses IP address biasing by default. + */ + locationbias?: string; +} + +/** A Find Place response contains only the data types that were specified using the fields parameter, plus `html_attributions`. */ +export interface FindPlaceFromTextResponse { + status: SearchResponseStatus; + candidates: Array>; +} + +export interface PlaceSearchResponse { + /** contains metadata on the request. */ + status: SearchResponseStatus; + /** + * When the Google Places service returns a status code other than `OK`, there may be an additional `error_message` field + * within the search response object. This field contains more detailed information about the reasons behind the given status code. + */ + error_message: string; + /** + * contains an array of places, with information about each. + * The Places API returns up to 20 `establishment` results per query. + * Additionally, political results may be returned which serve to identify the area of the request. + */ + results: PlaceSearchResult[]; + /** may contain a set of attributions about this listing which must be displayed to the user (some listings may not have attribution). */ + html_attributions: string[]; + /** + * contains a token that can be used to return up to 20 additional results. + * A `next_page_token` will not be returned if there are no additional results to display. + * The maximum number of results that can be returned is 60. + * There is a short delay between when a `next_page_token` is issued, and when it will become valid. + */ + next_page_token: string; +} + +/** + * The `"status"` field within the search response object contains the status of the request, + * and may contain debugging information to help you track down why the request failed. + */ +export type SearchResponseStatus = ( + /** indicates that no errors occurred; the place was successfully detected and at least one result was returned. */ + 'OK' | + /** + * indicates that the search was successful but returned no results. + * This may occur if the search was passed a latlng in a remote location. + */ + 'ZERO_RESULTS' | + /** indicates that you are over your quota. */ + 'OVER_QUERY_LIMIT' | + /** indicates that your request was denied, generally because of lack of an invalid key parameter. */ + 'REQUEST_DENIED' | + /** generally indicates that a required query parameter (location or radius) is missing. */ + 'INVALID_REQUEST' | + /** indicates a server-side error; trying again may be successful. */ + 'UNKNOWN_ERROR' +); + +/** + * When the Google Places service returns JSON results from a search, it places them within a `results` array. + * Even if the service returns no results (such as if the `location` is remote) it still returns an empty `results` array. + * XML responses consist of zero or more `` elements. + */ +export interface PlaceSearchResult { + /** contains the URL of a recommended icon which may be displayed to the user when indicating this result. */ + icon: string; + /** + * contains geometry information about the result, generally including the `location` (geocode) + * of the place and (optionally) the viewport identifying its general area of coverage + */ + geometry: AddressGeometry; + /** + * is an encoded location reference, derived from latitude and longitude coordinates, that represents an area: + * 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller. + * Plus codes can be used as a replacement for street addresses in places where they do not exist + * (where buildings are not numbered or streets are not named). + * + * The plus code is formatted as a global code and a compound code: + * - `global_code` is a 4 character area code and 6 character or longer local code (849VCWC8+R9). + * - `compound_code` is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA). + * + * Typically, both the global code and compound code are returned. + * However, if the result is in a remote location (for example, an ocean or desert) only the global code may be returned. + * + * @see [Open Location Code](https://en.wikipedia.org/wiki/Open_Location_Code) + * @see [plus codes](https://plus.codes/) + */ + plus_code: PlusCode; + /** contains the human-readable name for the returned result. For `establishment` results, this is usually the business name. */ + name: string; + /** information on the opening hours. */ + opening_hours: OpeningHours; + /** + * an array of `photo` objects, each containing a reference to an image. + * A Place Search will return at most one `photo` object. + * Performing a Place Details request on the place may return up to ten photos. + * More information about Place Photos and how you can use the images in your application can be found in the + * [Place Photos](https://developers.google.com/places/web-service/photos) documentation. + */ + photos: PlacePhoto[]; + /** + * a textual identifier that uniquely identifies a place. + * To retrieve information about the place, pass this identifier in the `placeId` field of a Places API request + */ + place_id: string; + /** + * Indicates the scope of the `place_id`. + * + * **Note:** The `scope` field is included only in Nearby Search results and Place Details results. + * You can only retrieve app-scoped places via the Nearby Search and the Place Details requests. + * If the `scope` field is not present in a response, it is safe to assume the scope is `GOOGLE`. + */ + scope: PlaceIdScope; + /** + * An array of zero, one or more alternative place IDs for the place, with a scope related to each alternative ID. + * Note: This array may be empty or not present. + */ + alt_ids: AlternativePlaceId[]; + /** + * The price level of the place, on a scale of 0 to 4. + * The exact amount indicated by a specific value will vary from region to region. + * + * Price levels are interpreted as follows: + * - `0`: Free + * - `1`: Inexpensive + * - `2`: Moderate + * - `3`: Expensive + * - `4`: Very Expensive + */ + price_level: number; + /** contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews. */ + rating: number; + /** + * contains an array of feature types describing the given result. + * XML responses include multiple `` elements if more than one type is assigned to the result. + */ + types: Array; + /** + * contains a feature name of a nearby location. Often this feature refers to a street or neighborhood within the given results. + * The `vicinity` property is only returned for a Nearby Search. + */ + vicinity: number; + /** + * is a string containing the human-readable address of this place. Often this address is equivalent to the "postal address". + * The `formatted_address` property is only returned for a Text Search. + */ + formatted_address: string; + /** + * is a boolean flag indicating whether the place has permanently shut down (value `true`). + * If the place is not permanently closed, the flag is absent from the response. + */ + permanently_closed: boolean; +} + +export interface OpeningHours { + /** is a boolean value indicating if the place is open at the current time. */ + open_now: boolean; + /** is an array of opening periods covering seven days, starting from Sunday, in chronological order. */ + periods: OpeningPeriod[]; +} + +export interface OpeningPeriod { + /** contains a pair of day and time objects describing when the place opens. */ + open: OpeningHoursTime; + /** + * may contain a pair of day and time objects describing when the place closes. + * **Note:** If a place is **always open**, the `close` section will be missing from the response. + * Clients can rely on always-open being represented as an `open` period containing `day` with value 0 + * and `time` with value 0000, and no `close`. + */ + close?: OpeningHoursTime; + /** + * is an array of seven strings representing the formatted opening hours for each day of the week. + * If a `language` parameter was specified in the Place Details request, the Places Service will format + * and localize the opening hours appropriately for that language. The ordering of the elements in this array + * depends on the `language` parameter. Some languages start the week on Monday while others start on Sunday. + */ + weekday_text: string[]; +} + +export interface OpeningHoursTime { + /** a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday. */ + day: number; + /** + * may contain a time of day in 24-hour hhmm format. Values are in the range 0000–2359. The `time` + * will be reported in the place's time zone. + */ + time?: string; +} + +/** + * All requests to the Place Photo service must include a `photoreference`, returned in the response to a Nearby Search, + * Text Search, or Place Details request. The response to these requests will contain a photos[] field if the place has related + * photographic content. + * + * **Note:** The number of photos returned varies by request. + * - A Nearby Search or a Text Search will return at most one photo element in the array. + * - Radar Searches do not return any photo information. + * - A Details request will return up to ten photo elements. + */ +export interface PlacePhoto { + /** a string used to identify the photo when you perform a Photo request. */ + photo_reference: string; + /** the maximum height of the image. */ + height: number; + /** the maximum width of the image. */ + width: number; + /** contains any required attributions. This field will always be present, but may be empty. */ + html_attributions: string[]; +} + +export type PlaceIdScope = ( + /** + * The place ID is recognised by your application only. + * This is because your application added the place, and the place has not yet passed the moderation process. + */ + 'APP' | + /** The place ID is available to other applications and on Google Maps. */ + 'GOOGLE' +); + +export interface AlternativePlaceId { + /** + * The most likely reason for a place to have an alternative place ID is if your application adds a place and receives + * an application-scoped place ID, then later receives a Google-scoped place ID after passing the moderation process. + */ + place_id: string; + /** + * The scope of an alternative place ID will always be `APP`, + * indicating that the alternative place ID is recognised by your application only. + */ + scope: 'APP'; +} + +/** + * Table 1: Types supported in place search and addition + * + * You can use the following values in the types filter for place searches and when adding a place. + * + * @see https://developers.google.com/places/web-service/supported_types#table1 + */ +export type PlaceType1 = ( + 'accounting' | + 'airport' | + 'amusement_park' | + 'aquarium' | + 'art_gallery' | + 'atm' | + 'bakery' | + 'bank' | + 'bar' | + 'beauty_salon' | + 'bicycle_store' | + 'book_store' | + 'bowling_alley' | + 'bus_station' | + 'cafe' | + 'campground' | + 'car_dealer' | + 'car_rental' | + 'car_repair' | + 'car_wash' | + 'casino' | + 'cemetery' | + 'church' | + 'city_hall' | + 'clothing_store' | + 'convenience_store' | + 'courthouse' | + 'dentist' | + 'department_store' | + 'doctor' | + 'electrician' | + 'electronics_store' | + 'embassy' | + 'fire_station' | + 'florist' | + 'funeral_home' | + 'furniture_store' | + 'gas_station' | + 'gym' | + 'hair_care' | + 'hardware_store' | + 'hindu_temple' | + 'home_goods_store' | + 'hospital' | + 'insurance_agency' | + 'jewelry_store' | + 'laundry' | + 'lawyer' | + 'library' | + 'liquor_store' | + 'local_government_office' | + 'locksmith' | + 'lodging' | + 'meal_delivery' | + 'meal_takeaway' | + 'mosque' | + 'movie_rental' | + 'movie_theater' | + 'moving_company' | + 'museum' | + 'night_club' | + 'painter' | + 'park' | + 'parking' | + 'pet_store' | + 'pharmacy' | + 'physiotherapist' | + 'plumber' | + 'police' | + 'post_office' | + 'real_estate_agency' | + 'restaurant' | + 'roofing_contractor' | + 'rv_park' | + 'school' | + 'shoe_store' | + 'shopping_mall' | + 'spa' | + 'stadium' | + 'storage' | + 'store' | + 'subway_station' | + 'supermarket' | + 'synagogue' | + 'taxi_stand' | + 'train_station' | + 'transit_station' | + 'travel_agency' | + 'veterinary_care' | + 'zoo' +); + +/** + * Table 2: Additional types returned by the Places service + * + * The following types may be returned in the results of a place search, in addition to the types in table 1 above. + * For more details on these types, refer to [Address Types](https://developers.google.com/maps/documentation/geocoding/intro#Types) + * in Geocoding Responses. + * + * @see https://developers.google.com/places/web-service/supported_types#table2 + */ +export type PlaceType2 = ( + 'administrative_area_level_1' | + 'administrative_area_level_2' | + 'administrative_area_level_3' | + 'administrative_area_level_4' | + 'administrative_area_level_5' | + 'colloquial_area' | + 'country' | + 'establishment' | + 'finance' | + 'floor' | + 'food' | + 'general_contractor' | + 'geocode' | + 'health' | + 'intersection' | + 'locality' | + 'natural_feature' | + 'neighborhood' | + 'place_of_worship' | + 'political' | + 'point_of_interest' | + 'post_box' | + 'postal_code' | + 'postal_code_prefix' | + 'postal_code_suffix' | + 'postal_town' | + 'premise' | + 'room' | + 'route' | + 'street_address' | + 'street_number' | + 'sublocality' | + 'sublocality_level_4' | + 'sublocality_level_5' | + 'sublocality_level_3' | + 'sublocality_level_2' | + 'sublocality_level_1' | + 'subpremise' +); + +export interface GeocodingRequest { + /** + * The street address that you want to geocode, in the format used by the national postal service of the country concerned. + * Additional address elements such as business names and unit, suite or floor numbers should be avoided. + */ + address?: string; + /** + * The bounding box of the viewport within which to bias geocode results more prominently. + * This parameter will only influence, not fully restrict, results from the geocoder. + */ + bounds?: LatLngBounds; + /** + * The language in which to return results. + * - If `language` is not supplied, the geocoder attempts to use the preferred language as specified in the `Accept-Language` header, + * or the native language of the domain from which the request is sent. + * - The geocoder does its best to provide a street address that is readable for both the user and locals. + * To achieve that goal, it returns street addresses in the local language, transliterated to a script readable + * by the user if necessary, observing the preferred language. All other addresses are returned in the preferred language. + * Address components are all returned in the same language, which is chosen from the first component. + * - If a name is not available in the preferred language, the geocoder uses the closest match. + * - The preferred language has a small influence on the set of results that the API chooses to return, + * and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, + * such as the abbreviations for street types, or synonyms that may be valid in one language but not in another. + * For example, utca and tér are synonyms for street in Hungarian. + */ + language?: string; + /** + * The region code, specified as a ccTLD ("top-level domain") two-character value. + * This parameter will only influence, not fully restrict, results from the geocoder. + */ + region?: string; + /** + * A components filter with elements separated by a pipe (`|`). + * The components filter is *required* if the request doesn't include an `address`. + * Each element in the components filter consists of a `component:value` pair, and fully restricts the results from the geocoder. + */ + components?: GeocodingComponents; +} + +/** + * Notes about component filtering: + * + * - If the request contains multiple component filters, the API evaluates them as an AND, not an OR. + * For example, if the request includes multiple countries `components=country:GB|country:AU`, + * the API looks for locations where country=GB AND country=AU, and returns `ZERO_RESULTS`. + * - Results are consistent with Google Maps, which occasionally yields unexpected `ZERO_RESULTS` responses. + * Using Place Autocomplete may provide better results in some use cases. + * To learn more, see [this FAQ](https://developers.google.com/maps/documentation/geocoding/faq#trbl_component_filtering). + * - For each address component, either specify it in the `address` parameter or in a `components` filter, but not both. + * Specifying the same values in both may result in `ZERO_RESULTS`. + * + * A geocode for "High St, Hastings" with `components=country:GB` returns a result in Hastings, England rather than in Hastings-On-Hudson, USA + */ +export interface GeocodingComponents { + /** matches `postal_code` and `postal_code_prefix`. */ + postalCode?: string; + /** + * matches a country name or a two letter [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code. + * **Note:** The API follows the ISO standard for defining countries, and the filtering works best when using + * the corresponding ISO code of the country + */ + country?: string | string[]; + /** matches the long or short name of a route. */ + route?: string; + /** matches against `locality` and `sublocality` types. */ + locality?: string; + /** matches all the administrative_area levels. */ + administrativeArea?: string; +} + +export interface GeocodingResponse { + /** contains metadata on the request. */ + status: STATUSES; + /** + * When the geocoder returns a status code other than `OK`, there may be an additional `error_message` field + * within the Geocoding response object. This field contains more detailed information about the reasons behind the given status code. + */ + error_meesage: string; + /** + * contains an array of geocoded address information and geometry information. + * + * Generally, only one entry in the `"results"` array is returned for address lookups,though the geocoder may return several results + * when address queries are ambiguous. + */ + results: GeocodingResult[]; +} + +/** + * The `"status" `field within the Geocoding response object contains the status of the request, + * and may contain debugging information to help you track down why geocoding is not working. + */ +export type GeocodingResponseStatus = ( + /** indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned. */ + 'OK' | + /** + * indicates that the geocode was successful but returned no results. + * This may occur if the geocoder was passed a non-existent `address`. + */ + 'ZERO_RESULTS' | + /** + * indicates any of the following: + * - The API key is missing or invalid. + * - Billing has not been enabled on your account. + * - A self-imposed usage cap has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this. + */ + 'OVER_DAILY_LIMIT' | + /** indicates that you are over your quota. */ + 'OVER_QUERY_LIMIT' | + /** indicates that your request was denied. */ + 'REQUEST_DENIED' | + /** generally indicates that the query (`address`, `components` or `latlng`) is missing. */ + 'INVALID_REQUEST' | + /** indicates that the request could not be processed due to a server error. The request may succeed if you try again. */ + 'UNKNOWN_ERROR' +); + +/** + * When the geocoder returns results, it places them within a (JSON) `results` array. + * Even if the geocoder returns no results (such as if the address doesn't exist) it still returns an empty `results` array. + * (XML responses consist of zero or more `` elements.) + */ +export interface GeocodingResult { + /** + * array indicates the type of the returned result. + * This array contains a set of zero or more tags identifying the type of feature returned in the result. + * For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, + * and also returns "political" which indicates it is a political entity. + */ + types: AddressType[]; + /** + * is a string containing the human-readable address of this location. + * + * Often this address is equivalent to the postal address. Note that some countries, such as the United Kingdom, + * do not allow distribution of true postal addresses due to licensing restrictions. + * + * The formatted address is logically composed of one or more address components. + * For example, the address "111 8th Avenue, New York, NY" consists of the following components: "111" (the street number), + * "8th Avenue" (the route), "New York" (the city) and "NY" (the US state). + * + * Do not parse the formatted address programmatically. Instead you should use the individual address components, + * which the API response includes in addition to the formatted address field. + */ + formatted_address: string; + /** + * is an array containing the separate components applicable to this address. + * + * Note the following facts about the `address_components[]` array: + * - The array of address components may contain more components than the `formatted_address`. + * - The array does not necessarily include all the political entities that contain an address, + * apart from those included in the `formatted_address`. To retrieve all the political entities that contain a specific address, + * you should use reverse geocoding, passing the latitude/longitude of the address as a parameter to the request. + * - The format of the response is not guaranteed to remain the same between requests. + * In particular, the number of `address_components` varies based on the address requested and can change + * over time for the same address. A component can change position in the array. + * The type of the component can change. A particular component may be missing in a later response. + */ + address_components: AddressComponent[]; + /** + * is an array denoting all the localities contained in a postal code. + * This is only present when the result is a postal code that contains multiple localities. + */ + postcode_localities: string[]; + /** address geometry. */ + geometry: AddressGeometry; + /** + * is an encoded location reference, derived from latitude and longitude coordinates, + * that represents an area: 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller. + * Plus codes can be used as a replacement for street addresses in places where they do not exist + * (where buildings are not numbered or streets are not named). + * + * The plus code is formatted as a global code and a compound code: + * - `global_code` is a 4 character area code and 6 character or longer local code (849VCWC8+R9). + * - `compound_code` is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA). + * Typically, both the global code and compound code are returned. However, if the result is in a remote location + * (for example, an ocean or desert) only the global code may be returned. + * + * @see [Open Location Code](https://en.wikipedia.org/wiki/Open_Location_Code) + * @see [plus codes](https://plus.codes/) + */ + plus_code: PlusCode; + /** + * indicates that the geocoder did not return an exact match for the original request, + * though it was able to match part of the requested address. + * You may wish to examine the original request for misspellings and/or an incomplete address. + * + * Partial matches most often occur for street addresses that do not exist within the locality you pass in the request. + * Partial matches may also be returned when a request matches two or more locations in the same locality. + * For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street. + * Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address. + * Suggestions triggered in this way will also be marked as a partial match. + */ + partial_match: boolean; + /** is a unique identifier that can be used with other Google APIs. */ + place_id: string; +} + +export type GeocodingAddressComponentType = ( + /** indicates the floor of a building address. */ + 'floor' | + /** typically indicates a place that has not yet been categorized. */ + 'establishment' | + /** indicates a named point of interest. */ + 'point_of_interest' | + /** indicates a parking lot or parking structure. */ + 'parking' | + /** indicates a specific postal box. */ + 'post_box' | + /** indicates a grouping of geographic areas, such as locality and sublocality, used for mailing addresses in some countries. */ + 'postal_town' | + /** indicates the room of a building address. */ + 'room' | + /** indicates the precise street number. */ + 'street_number' | + /** indicate the location of a bus. */ + 'bus_station' | + /** indicate the location of a train. */ + 'train_station' | + /** indicate the location of a public transit stop. */ + 'transit_station' +); + +export interface AddressComponent { + /** is an array indicating the *type* of the address component. */ + types: Array; + /** is the full text description or name of the address component as returned by the Geocoder. */ + long_name: string; + /** + * is an abbreviated textual name for the address component, if available. + * For example, an address component for the state of Alaska may have a `long_name` of "Alaska" and a `short_name` of "AK" + * using the 2-letter postal abbreviation. + */ + short_name: string; +} + +export interface AddressGeometry { + /** contains the geocoded latitude, longitude value. For normal address lookups, this field is typically the most important. */ + location: LatLngLiteral; + /** stores additional data about the specified location. */ + location_type: LocationType; + /** + * contains the recommended viewport for displaying the returned result, specified as two latitude, longitude values + * defining the `southwest` and `northeast` corner of the viewport bounding box. + * Generally the viewport is used to frame a result when displaying it to a user. + */ + viewport: LatLngBounds; + /** + * (optionally returned) stores the bounding box which can fully contain the returned result. + * Note that these bounds may not match the recommended viewport. + * (For example, San Francisco includes the [Farallon islands](https://en.wikipedia.org/wiki/Farallon_Islands), + * which are technically part of the city, but probably should not be returned in the viewport.) + */ + bounds: LatLngBounds; +} + +export type LocationType = ( + /** + * indicates that the returned result is a precise geocode for which we have location information + * accurate down to street address precision + */ + 'ROOFTOP' | + /** + * indicates that the returned result reflects an approximation (usually on a road) interpolated between two precise points + * (such as intersections). Interpolated results are generally returned when rooftop geocodes are unavailable for a street address. + */ + 'RANGE_INTERPOLATED' | + /** + * indicates that the returned result is the geometric center of a result such as a polyline + * (for example, a street) or polygon (region). + */ + 'GEOMETRIC_CENTER' | + /** indicates that the returned result is approximate. */ + 'APPROXIMATE' +); + +export interface PlusCode { + /** is a 4 character area code and 6 character or longer local code (849VCWC8+R9). */ + global_code: string; + /** is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA). */ + compound_code: string; +} + +export interface GeolocationRequest { + /** The mobile country code (MCC) for the device's home network. */ + homeMobileCountryCode?: number; + /** The mobile network code (MNC) for the device's home network. */ + homeMobileNetworkCode?: number; + /** The mobile radio type. While this field is optional, it should be included if a value is available, for more accurate results. */ + radioType?: RadioType; + /** The carrier name. */ + carrier?: string; + /** + * Specifies whether to fall back to IP geolocation if wifi and cell tower signals are not available. + * Defaults to `true`. Set `considerIp` to `false` to disable fall back. + */ + considerIp?: boolean; + /** An array of cell tower objects. */ + cellTowers?: CellTower[]; + /** An array of WiFi access point objects. */ + wifiAccessPoints?: WifiAccessPoint[]; +} + +export type RadioType = ( + 'lte' | + 'gsm' | + 'cdma' | + 'wcdma' +); + +export interface CellTower { + /** + * Unique identifier of the cell. + * On GSM, this is the Cell ID (CID); + * CDMA networks use the Base Station ID (BID). + * WCDMA networks use the UTRAN/GERAN Cell Identity (UC-Id), which is a 32-bit value concatenating the Radio Network Controller (RNC) + * and Cell ID. Specifying only the 16-bit Cell ID value in WCDMA networks may return inaccurate results. + */ + cellId: number; + /** The Location Area Code (LAC) for GSM and WCDMA networks. The Network ID (NID) for CDMA networks. */ + locationAreaCode: number; + /** The cell tower's Mobile Country Code (MCC). */ + mobileCountryCode: number; + /** The cell tower's Mobile Network Code. This is the MNC for GSM and WCDMA; CDMA uses the System ID (SID). */ + mobileNetworkCode: number; + /** The number of milliseconds since this cell was primary. If age is 0, the `cellId` represents a current measurement. */ + age?: number; + /** Radio signal strength measured in dBm. */ + signalStrength?: number; + /** The [timing advance](https://en.wikipedia.org/wiki/Timing_advance) value. */ + timingAdvance?: number; +} + +export interface WifiAccessPoint { + /** The MAC address of the WiFi node. It's typically called a BSS, BSSID or MAC address. Separators must be `:` (colon). */ + macAddress: string; + /** The current signal strength measured in dBm. */ + signalStrength?: number; + /** The number of milliseconds since this access point was detected. */ + age?: number; + /** The channel over which the client is communicating with the acces. */ + channel?: number; + /** The current signal to noise ratio measured in dB. */ + signalToNoiseRatio?: number; +} + +export interface GeolocationResponse { + /** The user's estimated latitude and longitude, in degrees. Contains one `lat` and one `lng` subfield. */ + location: LatLngLiteral; + /** The accuracy of the estimated location, in meters. This represents the radius of a circle around the given location. */ + accuracy: number; +} + +/** + * In the case of an error, a standard format error response body will be returned + * and the HTTP status code will be set to an error status. + */ +export interface GeolocationError { + error: { + /** This is the same as the HTTP status of the response. */ + code: number; + /** A short description of the error. */ + message: string; + /** + * A list of errors which occurred. Each error contains an identifier for the type of error (the `reason`) + * and a short description (the `message`). + */ + errors: Array<{ + domain: string; + reason: GeolocationErrorReason; + message: string; + }>; + }; +} + +export type GeolocationErrorReason = ( + /** + * You have exceeded your daily limit. + * Domain: usageLimits + * Code: 403 + */ + 'dailyLimitExceeded' | + /** + * Your API key is not valid for the Geolocation API. Please ensure that you've included the entire key, + * and that you've either purchased the API or have enabled billing and activated the API to obtain the free quota. + * Domain: usageLimits + * Code: 400 + */ + 'keyInvalid' | + /** + * You have exceeded the requests per second per user limit that you configured in the Google Cloud Platform Console. + * This limit should be configured to prevent a single or small group of users from exhausting your daily quota, + * while still allowing reasonable access to all users. + * Domain: usageLimits + * Code: 403 + */ + 'userRateLimitExceeded' | + /** + * The request was valid, but no results were returned. + * Domain: geolocation + * Code: 404 + */ + 'notFound' | + /** + * The request body is not valid JSON. Refer to the Request Body section for details on each field. + * Domain: global + * Code: 400 + */ + 'parseError' +); + +export interface NearestRoadsRequest { + /** + * A list of latitude/longitude pairs. Latitude and longitude values should be separated by commas. + * Coordinates should be separated by the pipe character: "|". + * For example: `points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796`. + */ + points: LatLng[]; +} + +export interface NearestRoadsResponse { + /** An array of snapped points. */ + snappedPoints: Array<{ + /** Contains a `latitude` and `longitude` value. */ + location: LatLngLiteralVerbose; + /** + * An integer that indicates the corresponding value in the original request. + * Each point in the request maps to at most two segmentsin the response: + * - If there are no nearby roads, no segment is returned. + * - If the nearest road is one-way, one segment is returned. + * - If the nearest road is bidirectional, two segments are returned. + */ + originalIndex: number; + /** + * A unique identifier for a place. All place IDs returned by the Roads API correspond to road segments. + * Place IDs can be used with other Google APIs, including the Places SDK and the Maps JavaScript API. + * For example, if you need to get road names for the snapped points returned by the Roads API, + * you can pass the `placeId` to the Places SDK or the Geocoding API. Within the Roads API, + * you can pass the `placeId` in a speed limits request to determine the speed limit along that road segment. + */ + placeId: string; + }>; +} + +export interface PlaceDetailsRequest { + /** A textual identifier that uniquely identifies a place, returned from a Place Search. */ + placeid: string; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Note that some fields may not be available in the requested language. + * Note that we often update supported languages so this list may not be exhaustive. + */ + language?: Language; + /** + * The region code, specified as a ccTLD (country code top-level domain) two-character value. + * Most ccTLD codes are identical to ISO 3166-1 codes, with some exceptions. + * This parameter will only influence, not fully restrict, results. + * If more relevant results exist outside of the specified region, they may be included. + * When this parameter is used, the country name is omitted from the resulting `formatted_address` + * for results in the specified region. + */ + region?: string; + /** + * A random string which identifies an autocomplete session for billing purposes. + * Use this for Place Details requests that are called following an autocomplete request in the same user session + */ + sessiontoken?: string; + /** + * One or more fields, specifying the types of place data to return, separated by a comma. + * + * **Warning: If you do not specify at least one field with a request, or if you omit the **fields** + * parameter from a request, ALL possible fields will be returned, and you will be billed accordingly. + * This applies only to Place Details requests. + */ + fields?: Array; +} + +export interface PlaceDetailsResponse { + /** contains metadata on the request. */ + status: PlaceDetailsResponseStatus; + /** + * When the Google Places service returns a status code other than `OK`, there may be an additional `error_message` field + * within the details response object. This field contains more detailed information about the reasons behind the given status code. + */ + /** contains the detailed information about the place requested. */ + result: PlaceDetailsResult; + /** contains a set of attributions about this listing which must be displayed to the user. */ + html_attributions: string[]; +} + +/** + * The `"status"` field within the place response object contains the status of the request, + * and may contain debugging information to help you track down why the place request failed + */ +export type PlaceDetailsResponseStatus = ( + /** indicates that no errors occurred; the place was successfully detected and at least one result was returned. */ + 'OK' | + /** indicates a server-side error; trying again may be successful. */ + 'UNKNOWN_ERROR' | + /** + * indicates that the referenced location (placeid) was valid but no longer refers to a valid result. + * This may occur if the establishment is no longer in business. + */ + 'ZERO_RESULTS' | + /** + * indicates any of the following: + * - You have exceeded the QPS limits. + * - The request is missing an API key. + * - Billing has not been enabled on your account. + * - The monthly $200 credit, or a self-imposed usage cap, has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) for more information + * about how to resolve this error. + */ + 'OVER_QUERY_LIMIT' | + /** indicates that your request was denied, generally because an invalid key parameter. */ + 'REQUEST_DENIED' | + /** generally indicates that the query (placeid) is missing. */ + 'INVALID_REQUEST' | + /** indicates that the referenced location (placeid) was not found in the Places database. */ + 'NOT_FOUND' +); + +/** When the Places service returns results from a details request, it places them within a single `result`. */ +export interface PlaceDetailsResult { + /** + * is an array containing the separate components applicable to this address. + * + * Note the following facts about the `address_components[]` array: + * - The array of address components may contain more components than the `formatted_address`. + * - The array does not necessarily include all the political entities that contain an address, + * apart from those included in the `formatted_address`. To retrieve all the political entities + * that contain a specific address, you should use reverse geocoding, passing the latitude/longitude + * of the address as a parameter to the request. + * - The format of the response is not guaranteed to remain the same between requests. + * In particular, the number of `address_components` varies based on the address requested + * and can change over time for the same address. A component can change position in the array. + * The type of the component can change. A particular component may be missing in a later response. + */ + address_components: AddressComponent[]; + /** + * is a string containing the human-readable address of this place. + * + * Often this address is equivalent to the postal address. Note that some countries, such as the United Kingdom, + * do not allow distribution of true postal addresses due to licensing restrictions. + * + * The formatted address is logically composed of one or more address components. + * For example, the address "111 8th Avenue, New York, NY" consists of the following components: "111" + * (the street number), "8th Avenue" (the route), "New York" (the city) and "NY" (the US state). + * + * Do not parse the formatted address programmatically. Instead you should use the individual address components, + * which the API response includes in addition to the formatted address field. + */ + formatted_address: string; + /** + * contains the place's phone number in its local format. + * For example, the `formatted_phone_number` for Google's Sydney, Australia office is `(02) 9374 4000`. + */ + formatted_phone_number: string; + /** is a representation of the place's address in the [adr microformat](http://microformats.org/wiki/adr). */ + adr_address: string; + /** + * contains the following information: + * - `location`: contains the geocoded latitude,longitude value for this place. + * - `viewport`: contains the preferred viewport when displaying this place on a map as a `LatLngBounds` if it is known. + */ + geometry: AddressGeometry; + /** + * is an encoded location reference, derived from latitude and longitude coordinates, that represents an area: + * 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller. + * Plus codes can be used as a replacement for street addresses in places where they do not exist + * (where buildings are not numbered or streets are not named). + * + * The plus code is formatted as a global code and a compound code: + * - `global_code` is a 4 character area code and 6 character or longer local code (849VCWC8+R9). + * - `compound_code` is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA). + * + * Typically, both the global code and compound code are returned. + * However, if the result is in a remote location (for example, an ocean or desert) only the global code may be returned. + * + * @see [Open Location Code](https://en.wikipedia.org/wiki/Open_Location_Code) + * @see [plus codes](https://plus.codes/) + */ + plus_code: PlusCode; + /** contains the URL of a suggested icon which may be displayed to the user when indicating this result on a map. */ + icon: string; + /** + * contains the place's phone number in international format. + * International format includes the country code, and is prefixed with the plus (+) sign. + * For example, the `international_phone_number` for Google's Sydney, Australia office is `+61 2 9374 4000`. + */ + international_phone_number: string; + /** + * contains the human-readable name for the returned result. + * For establishment results, this is usually the canonicalized business name. + */ + name: string; + /** place opening hours. */ + opening_hours: OpeningHours; + /** + * is a boolean flag indicating whether the place has permanently shut down (value `true`). + * If the place is not permanently closed, the flag is absent from the response. + */ + permanently_closed: boolean; + /** + * an array of photo objects, each containing a reference to an image. + * A Place Details request may return up to ten photos. + * More information about place photos and how you can use the images in your application can be found in the Place Photos documentation. + */ + photos: PlacePhoto[]; + /** + * A textual identifier that uniquely identifies a place. + * To retrieve information about the place, pass this identifier in the `placeId` field of a Places API request. + */ + place_id: string; + /** Indicates the scope of the `place_id`. */ + scope: PlaceIdScope; + /** + * An array of zero, one or more alternative place IDs for the place, with a scope related to each alternative ID. + * Note: This array may be empty or not present. + */ + alt_ids: AlternativePlaceId[]; + /** + * The price level of the place, on a scale of 0 to 4. + * The exact amount indicated by a specific value will vary from region to region. + * + * Price levels are interpreted as follows: + * - `0`: Free + * - `1`: Inexpensive + * - `2`: Moderate + * - `3`: Expensive + * - `4`: Very Expensive + */ + price_level: number; + /** contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews. */ + rating: number; + /** + * a JSON array of up to five reviews. If a `language` parameter was specified in the Place Details request, + * the Places Service will bias the results to prefer reviews written in that language. + */ + reviews: PlaceReview[]; + /** + * contains an array of feature types describing the given result. + * XML responses include multiple `` elements if more than one type is assigned to the result. + */ + types: AddressType[]; + /** + * contains the URL of the official Google page for this place. + * This will be the Google-owned page that contains the best available information about the place. + * Applications must link to or embed this page on any screen that shows detailed results about the place to the user. + */ + url: string; + /** + * contains the number of minutes this place’s current timezone is offset from UTC. + * For example, for places in Sydney, Australia during daylight saving time this would be 660 (+11 hours from UTC), + * and for places in California outside of daylight saving time this would be -480 (-8 hours from UTC). + */ + utc_offset: number; + /** + * lists a simplified address for the place, including the street name, street number, and locality, + * but not the province/state, postal code, or country. For example, Google's Sydney, Australia office + * has a `vicinity` value of `48 Pirrama Road, Pyrmont`. + */ + vicinity: number; + /** lists the authoritative website for this place, such as a business' homepage. */ + website: string; +} + +export interface PlaceReview { + /** + * contains a collection of `AspectRating` objects, each of which provides a rating of a single attribute of the establishment. + * The first object in the collection is considered the primary aspect. + */ + aspects: AspectRating[]; + /** the name of the user who submitted the review. Anonymous reviews are attributed to "A Google user". */ + author_name: string; + /** the URL to the user's Google Maps Local Guides profile, if available. */ + author_url?: string; + /** + * an IETF language code indicating the language used in the user's review. + * This field contains the main language tag only, and not the secondary tag indicating country or region. + * For example, all the English reviews are tagged as 'en', and not 'en-AU' or 'en-UK' and so on. + */ + language: string; + /** the user's overall rating for this place. This is a whole number, ranging from 1 to 5. */ + rating: number; + /** + * the user's review. When reviewing a location with Google Places, text reviews are considered optional. + * Therefore, this field may by empty. Note that this field may include simple HTML markup. + * For example, the entity reference `&` may represent an ampersand character. + */ + text: string; + /** the time that the review was submitted, measured in the number of seconds since since midnight, January 1, 1970 UTC. */ + time: string; +} + +export interface AspectRating { + /** the name of the aspect that is being rated. */ + type: AspectRatingType; + /** the user's rating for this particular aspect, from 0 to 3. */ + rating: number; +} + +export type AspectRatingType = ( + 'appeal' | + 'atmosphere' | + 'decor' | + 'facilities' | + 'food' | + 'overall' | + 'quality' | + 'service' +); + +export interface PlacesRequest { + /** + * The text string on which to search, for example: "restaurant" or "123 Main Street". + * The Google Places service will return candidate matches based on this string and order the results + * based on their perceived relevance. This parameter becomes optional if the `type` parameter + * is also used in the search request. + */ + query: string; + /** + * The region code, specified as a ccTLD (country code top-level domain) two-character value. + * Most ccTLD codes are identical to ISO 3166-1 codes, with some exceptions. + * This parameter will only influence, not fully restrict, search results. + * If more relevant results exist outside of the specified region, they may be included. + * When this parameter is used, the country name is omitted from the resulting `formatted_address` + * for results in the specified region. + */ + region?: string; + /** + * The latitude/longitude around which to retrieve place information. + * This must be specified as latitude,longitude. If you specify a location parameter, + * you must also specify a radius parameter. + */ + location?: LatLng; + /** + * Defines the distance (in meters) within which to bias place results. + * The maximum allowed radius is 50 000 meters. + * Results inside of this region will be ranked higher than results outside of the search circle; + * however, prominent results from outside of the search radius may be included. + */ + radius?: number; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Note that we often update supported languages so this list may not be exhaustive + */ + language?: Language; + /** + * Restricts results to only those places within the specified price level. + * Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + minprice?: number; + /** + * Restricts results to only those places within the specified price level. + * Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + maxprice?: number; + /** + * Returns only those places that are open for business at the time the query is sent. + * Places that do not specify opening hours in the Google Places database will not be returned + * if you include this parameter in your query. + */ + opennow?: boolean; + /** + * Returns the next 20 results from a previously run search. + * Setting a `pagetoken` parameter will execute a search with the same parameters used previously — + * all parameters other than `pagetoken` will be ignored. + */ + pagetoken?: string; + /** + * Restricts the results to places matching the specified type. + * Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). + */ + type?: PlaceType1; +} + +/** + * The Place Autocomplete service can match on full words as well as substrings. + * Applications can therefore send queries as the user types, to provide on-the-fly place predictions. + * + * The returned predictions are designed to be presented to the user to aid them in selecting the desired place. + * You can send a [Place Details request](https://developers.google.com/places/web-service/details#PlaceDetailsRequests) + * for more information about any of the places which are returned. + */ +export interface PlaceAutocompleteRequest { + /** + * The text string on which to search. The Place Autocomplete service will return candidate matches + * based on this string and order results based on their perceived relevance. + */ + input: string; + /** + * A random string which identifies an autocomplete + * [session](https://developers.google.com/places/web-service/autocomplete#session_tokens) for billing purposes. + * If this parameter is omitted from an autocomplete request, the request is billed independently + */ + sessiontoken: string; + /** + * The position, in the input term, of the last character that the service uses to match predictions. + * For example, if the input is 'Google' and the `offset` is 3, the service will match on 'Goo'. + * The string determined by the `offset` is matched against the first word in the input term only. + * For example, if the input term is 'Google abc' and the offset is 3, the service will attempt to match against 'Goo abc'. + * If no `offset` is supplied, the service will use the whole term. + * The `offset` should generally be set to the position of the text caret. + */ + offset?: number; + /** The point around which you wish to retrieve place information. */ + location?: LatLng; + /** + * The distance (in meters) within which to return place results. Note that setting a radius biases results to the indicated area, + * but may not fully restrict results to the specified area. + */ + radius?: number; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Searches are also biased to the selected language; results in the selected language may be given a higher ranking. + * See the list of supported languages and their codes. + * Note that we often update supported languages so this list may not be exhaustive. + * If language is not supplied, the Place Autocomplete service will attempt to use the native language + * of the domain from which the request is sent. + */ + language?: string; + /** The types of place results to return. */ + types?: PlaceAutocompleteType; + /** + * A grouping of places to which you would like to restrict your results. + * Currently, you can use `components` to filter by up to 5 countries. + * Countries must be passed as a two character, ISO 3166-1 Alpha-2 compatible country code. + * For example: `components=country:fr` would restrict your results to places within France. + * Multiple countries must be passed as multiple `country:XX` filters, with the pipe character (`|`) as a separator. + * For example: `components=country:us|country:pr|country:vi|country:gu|country:mp` would restrict your results + * to places within the United States and its unincorporated organized territories. + */ + components?: string[]; + /** + * Returns only those places that are strictly within the region defined by `location` and `radius`. + * This is a restriction, rather than a bias, meaning that results outside this region + * will not be returned even if they match the user input. + */ + strictbounds?: boolean; +} + +/** + * You may restrict results from a Place Autocomplete request to be of a certain type by passing a types parameter. + * The parameter specifies a type or a type collection, as listed in the supported types below. + * If nothing is specified, all types are returned. In general only a single type is allowed. + * The exception is that you can safely mix the geocode and establishment types, + * but note that this will have the same effect as specifying no types. + */ +export type PlaceAutocompleteType = ( + /** + * instructs the Place Autocomplete service to return only geocoding results, rather than business results. + * Generally, you use this request to disambiguate results where the location specified may be indeterminate. + */ + 'geocode' | + /** + * instructs the Place Autocomplete service to return only geocoding results with a precise address. + * Generally, you use this request when you know the user will be looking for a fully specified address. + */ + 'address' | + /** instructs the Place Autocomplete service to return only business results. */ + 'establishment' | + /** + * the `(regions)` type collection instructs the Places service to return any result matching the following types: + * - `locality` + * - `sublocality` + * - `postal_code` + * - `country` + * - `administrative_area_level_1` + * - `administrative_area_level_2` + */ + '(regions)' | + /** the (cities) type collection instructs the Places service to return results that match `locality` or `administrative_area_level_3`. */ + '(cities)' +); + +export interface PlaceAutocompleteResponse { + /** contains metadata on the request. */ + status: PlaceAutocompleteResponseStatus; + /** + * When the Places service returns a status code other than `OK`, there may be an additional `error_message` field + * within the response object. This field contains more detailed information about the reasons behind the given status code. + */ + error_message: string; + /** + * contains an array of places, with information about the place. + * See [Place Autocomplete Results](https://developers.google.com/places/web-service/autocomplete#place_autocomplete_results) + * for information about these results. The Places API returns up to 5 results. + */ + predictions: PlaceAutocompleteResult[]; +} + +/** + * The `status` field within the Place Autocomplete response object contains the status of the request, + * and may contain debugging information to help you track down why the Place Autocomplete request failed. + */ +export type PlaceAutocompleteResponseStatus = ( + /** indicates that no errors occurred and at least one result was returned. */ + 'OK' | + /** + * indicates that the search was successful but returned no results. + * This may occur if the search was passed a bounds in a remote location. + */ + 'ZERO_RESULTS' | + /** indicates that you are over your quota. */ + 'OVER_QUERY_LIMIT' | + /** indicates that your request was denied, generally because of lack of an invalid key parameter. */ + 'REQUEST_DENIED' | + /** generally indicates that the input parameter is missing. */ + 'INVALID_REQUEST' | + /** indicates a server-side error; trying again may be successful. */ + 'UNKNOWN_ERROR' +); + +/** + * When the Places service returns JSON results from a search, it places them within a `predictions` array. + * Even if the service returns no results (such as if the `location` is remote) it still returns an empty `predictions` array. + * XML responses consist of zero or more `` elements. + * + * **Note:** The Place Autocomplete response does not include the `scope` or `alt_ids` fields that you may see + * in search results or place details. This is because Autocomplete returns only Google-scoped place IDs. + * It does not return app-scoped place IDs that have not yet been accepted into the Google Places database. + */ +export interface PlaceAutocompleteResult { + /** + * contains the human-readable name for the returned result. + * For `establishment` results, this is usually the business name. + */ + description: string; + /** + * is a textual identifier that uniquely identifies a place. + * To retrieve information about the place, pass this identifier in the `placeId` field of a Places API request. + */ + place_id: string; + /** + * contains an array of terms identifying each section of the returned description + * (a section of the description is generally terminated with a comma). + */ + terms: PredictionTerm[]; + /** + * contains an array of types that apply to this place. + * For example: `[ "political", "locality" ]` or `[ "establishment", "geocode" ]`. + */ + types: AddressType[]; + /** + * contains an array with `offset` value and `length`. These describe the location of + * the entered term in the prediction result text, so that the term can be highlighted if desired. + */ + matched_substrings: PredictionSubstring[]; + /** contains details on the prediction. */ + structured_formatting: StructuredFormatting; +} + +export interface PredictionTerm { + /** containing the text of the term. */ + value: string; + /** start position of this term in the description, measured in Unicode characters. */ + offset: number; +} + +export interface PredictionSubstring { + /** location of the entered term. */ + offset: number; + /** length of the entered term. */ + length: number; +} + +export interface StructuredFormatting { + /** contains the main text of a prediction, usually the name of the place. */ + main_text: string; + /** + * contains an array with `offset` value and `length`. These describe the location of + * the entered term in the prediction result text, so that the term can be highlighted if desired. + */ + main_text_matched_substrings: PredictionSubstring[]; + /** contains the secondary text of a prediction, usually the location of the place. */ + secondary_text: string; +} + +export interface PlacesNearbyRequest { + /** The latitude/longitude around which to retrieve place information. This must be specified as latitude,longitude. */ + location: LatLng; + /** + * Defines the distance (in meters) within which to return place results. + * The maximum allowed radius is 50 000 meters. + * Note that `radius` must not be included if `rankby=distance` is specified. + */ + radius?: number; + /** + * A term to be matched against all content that Google has indexed for this place, including but not limited to + * name, type, and address, as well as customer reviews and other third-party content. + */ + keyword?: string; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Note that we often update supported languages so this list may not be exhaustive. + */ + language?: Language; + /** + * Restricts results to only those places within the specified range. + * Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + minprice?: number; + /** + * Restricts results to only those places within the specified range. + * Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + maxprice?: number; + /** + * A term to be matched against all content that Google has indexed for this place. + * Equivalent to `keyword`. The `name` field is no longer restricted to place names. + * Values in this field are combined with values in the `keyword` field and passed as part of the same search string. + * We recommend using only the `keyword` parameter for all search terms. + */ + name?: string; + /** + * Returns only those places that are open for business at the time the query is sent. + * Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. + */ + opennow?: boolean; + /** + * Specifies the order in which results are listed. + * Note that `rankby` must not be included if `radius` is specified. + * + * @default PlacesNearbyRanking.prominence + */ + rankby?: PlacesNearbyRanking; + /** + * Restricts the results to places matching the specified type. + * Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). + */ + type?: AddressType; + /** + * Returns the next 20 results from a previously run search. + * Setting a pagetoken parameter will execute a search with the same parameters used previously — + * all parameters other than pagetoken will be ignored. + */ + pagetoken?: string; +} + +export type PlacesNearbyRanking = ( + /** + * This option sorts results based on their importance. Ranking will favor prominent places within the specified area. + * Prominence can be affected by a place's ranking in Google's index, global popularity, and other factors. + */ + 'prominence' | + /** + * This option biases search results in ascending order by their distance from the specified `location`. + * When distance is specified, one or more of `keyword`, `name`, or `type` is required. + */ + 'distance' +); + +export interface PlacePhotoRequest { + /** + * string identifier that uniquely identifies a photo. + * Photo references are returned from either a Place Search or Place Details request. + */ + photoreference: string; + /** + * Specifies the maximum desired height or width, in pixels, of the image returned by the Place Photos service. + * If the image is smaller than the values specified, the original image will be returned. + * If the image is larger in either dimension, it will be scaled to match the smaller of the two dimensions, + * restricted to its original aspect ratio. Both the `maxheight` and `maxwidth` properties accept an integer between 1 and 1600. + */ + maxwidth?: number; + /** + * Specifies the maximum desired height or width, in pixels, of the image returned by the Place Photos service. + * If the image is smaller than the values specified, the original image will be returned. + * If the image is larger in either dimension, it will be scaled to match the smaller of the two dimensions, + * restricted to its original aspect ratio. Both the `maxheight` and `maxwidth` properties accept an integer between 1 and 1600. + */ + maxheight?: number; +} + +/** + * The response of a successful Place Photo request will be an image. + * The type of the image will depend upon the type of the originally submitted photo. + * + * If your request exceeds your available quota, the server will return an HTTP 403 status to indicate that the quota has been exceeded. + * + * If the server is unable to understand your request, it will return HTTP 400 status, which indicates an invalid request. + * + * The most common reasons why you might see an invalid request include: + * - The submitted photo reference was incorrectly specified. + * - Your request did not include either a `maxwidth` or `maxheight` parameter. + */ +export type PlacePhotoResponse = string; + +export interface QueryAutocompleteRequest { + /** + * The text string on which to search. + * The Places service will return candidate matches based on this string and order results based on their perceived relevance. + */ + input: string; + /** + * The character position in the input term at which the service uses text for predictions. + * For example, if the input is 'Googl' and the completion point is 3, the service will match on 'Goo'. + * The offset should generally be set to the position of the text caret. + * If no offset is supplied, the service will use the entire term. + */ + offset?: number; + /** The point around which you wish to retrieve place information. Must be specified as latitude,longitude. */ + location?: LatLng; + /** + * The distance (in meters) within which to return place results. + * Note that setting a radius biases results to the indicated area, but may not fully restrict results to the specified area. + */ + radius?: number; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Searches are also biased to the selected language; results in the selected language may be given a higher ranking. + * If language is not supplied, the Places service will attempt to use the native language of the domain from which the request is sent. + */ + language?: Language; +} + +export interface QueryAutocompleteResponse { + /** contains metadata on the request. */ + status: QueryAutocompleteResponseStatus; + /** + * When the Places service returns a status code other than `OK`, there may be an additional `error_message` field + * within the response object. This field contains more detailed information about the reasons behind the given status code. + */ + error_message: string; + /** containing information about a single query prediction. */ + predictions: QueryAutocompleteResult[]; +} + +/** + * The `status` field within the Query Autocomplete response object contains the status of the request, + * and may contain debugging information to help you track down why the request failed. + */ +export type QueryAutocompleteResponseStatus = ( + /** indicates that no errors occurred and at least one result was returned. */ + 'OK' | + /** + * indicates that the search was successful but returned no results. + * This may occur if the search was passed a bounds in a remote location. + */ + 'ZERO_RESULTS' | + /** indicates that you are over your quota. */ + 'OVER_QUERY_LIMIT' | + /** indicates that your request was denied, generally because the key parameter is missing or invalid. */ + 'REQUEST_DENIED' | + /** generally indicates that the input parameter is missing. */ + 'INVALID_REQUEST' | + /** indicates a server-side error; trying again may be successful. */ + 'UNKNOWN_ERROR' +); + +/** + * When the Places service returns JSON results from a search, it places them within a `predictions` array. + * Even if the service returns no results (such as if the `location` is remote) it still returns an empty `predictions` array. + * XML responses consist of zero or more `` elements. + * + * Note that some of the predictions may be places, and the `place_id` and `types` fields will be included with those predictions. + * See [Place Autocomplete Results](https://developers.google.com/places/web-service/autocomplete#place_autocomplete_results) + * for information about these results. + */ +export interface QueryAutocompleteResult { + /** contains the human-readable name for the returned result. For establishment results, this is usually the business name. */ + description: string; + /** + * contains an array of terms identifying each section of the returned description + * (a section of the description is generally terminated with a comma). + */ + terms: PredictionTerm[]; + /** + * contains an `offset` value and a `length`. + * These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired. + */ + matched_substring: PredictionSubstring[]; +} + +/** A Radar Search request must include at least one of `keyword`, `name`, or `type`. */ +export interface PlaceRadarRequest { + /** The latitude/longitude around which to retrieve place information. This must be specified as latitude,longitude. */ + location: LatLng; + /** Defines the distance (in meters) within which to return place results. The maximum allowed radius is 50 000 meters. */ + radius: number; + /** + * A term to be matched against all content that Google has indexed for this place, including but not limited to + * name, type, and address, as well as customer reviews and other third-party content. + */ + keyword?: string; + /** + * The language code, indicating in which language the results should be returned, if possible. + * Searches are also biased to the selected language; results in the selected language may be given a higher ranking. + * Note that we often update supported languages so this list may not be exhaustive. + */ + language?: string; + /** + * Restricts results to only those places within the specified price level. + * Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + minprice?: number; + /** + * Restricts results to only those places within the specified price level. + * Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. + * The exact amount indicated by a specific value will vary from region to region. + */ + maxprice?: number; + /** + * A term to be matched against all content that Google has indexed for this place. + * Equivalent to keyword. The `name` field is no longer restricted to place names. + * Values in this field are combined with values in the `keyword` field and passed as part of the same search string. + * We recommend using only the `keyword` parameter for all search terms. + */ + name?: string; + /** + * Returns only those places that are open for business at the time the query is sent. + * Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. + */ + opennow?: boolean; + /** + * Restricts the results to places matching the specified type. + * Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). + */ + type?: AddressType; +} + +/** + * If both `result_type` and `location_type` filters are present then the API returns only those results that match both the + * `result_type` and the `location_type` values. If none of the filter values are acceptable, the API returns `ZERO_RESULTS`. + */ +export interface ReverseGeocodingRequest { + /** The latitude and longitude values specifying the location for which you wish to obtain the closest, human-readable address. */ + latlng?: LatLng; + /** + * The place ID of the place for which you wish to obtain the human-readable address. + * The place ID is a unique identifier that can be used with other Google APIs. + * For example, you can use the `placeID` returned by the Roads API to get the address for a snapped point. + * The place ID may only be specified if the request includes an API key or a Google Maps APIs Premium Plan client ID. + */ + place_id?: string; + /** + * The language in which to return results. + * - Google often updates the supported languages, so this list may not be exhaustive. + * - If `language` is not supplied, the geocoder attempts to use the preferred language as specified in the + * `Accept-Language` header, or the native language of the domain from which the request is sent. + * - The geocoder does its best to provide a street address that is readable for both the user and locals. + * To achieve that goal, it returns street addresses in the local language, transliterated to a script readable by the user + * if necessary, observing the preferred language. All other addresses are returned in the preferred language. + * Address components are all returned in the same language, which is chosen from the first component. + * - If a name is not available in the preferred language, the geocoder uses the closest match. + */ + language?: Language; + /** + * A filter of one or more address types, separated by a pipe (`|`). + * If the parameter contains multiple address types, the API returns all addresses that match any of the types. + * A note about processing: The `result_type` parameter does not restrict the search to the specified address type(s). + * Rather, the `result_type` acts as a post-search filter: the API fetches all results for the specified `latlng`, + * then discards those results that do not match the specified address type(s). + * Note: This parameter is available only for requests that include an API key or a client ID. + */ + result_type?: AddressType; + /** + * A filter of one or more location types, separated by a pipe (`|`). + * If the parameter contains multiple location types, the API returns all addresses that match any of the types. + * A note about processing: The `location_type` parameter does not restrict the search to the specified location type(s). + * Rather, the `location_type` acts as a post-search filter: the API fetches all results for the specified `latlng`, + * then discards those results that do not match the specified location type(s). + * Note: This parameter is available only for requests that include an API key or a client ID. + */ + location_type?: ReverseGeocodingLocationType; +} + +export type ReverseGeocodingLocationType = ( + /** returns only the addresses for which Google has location information accurate down to street address precision. */ + 'ROOFTOP' | + /** + * returns only the addresses that reflect an approximation (usually on a road) interpolated between two precise points + * (such as intersections). An interpolated range generally indicates that rooftop geocodes are unavailable for a street address. + */ + 'RANGE_INTERPOLATED' | + /** returns only geometric centers of a location such as a polyline (for example, a street) or polygon (region). */ + 'GEOMETRIC_CENTER' | + /** returns only the addresses that are characterized as approximate. */ + 'APPROXIMATE' +); + +export type ReverseGeocodingResponse = GeocodingResponse; + +/** + * The `"status"` field within the Geocoding response object contains the status of the request, + * and may contain debugging information to help you track down why reverse geocoding is not working. + */ +export type ReverseGeocodingResponseStatus = ( + /** indicates that no errors occurred and at least one address was returned. */ + 'OK' | + /** + * indicates that the reverse geocoding was successful but returned no results. + * This may occur if the geocoder was passed a latlng in a remote location. + */ + 'ZERO_RESULTS' | + /** indicates that you are over your quota. */ + 'OVER_QUERY_LIMIT' | + /** + * indicates that the request was denied. + * Possibly because the request includes a `result_type` or `location_type` parameter but does not include + * an API key or client ID. + */ + 'REQUEST_DENIED' | + /** + * generally indicates one of the following: + * - The query (`address`, `components` or `latlng`) is missing. + * - An invalid `result_type` or `location_type` was given. + */ + 'INVALID_REQUEST' | + /** indicates that the request could not be processed due to a server error. The request may succeed if you try again. */ + 'UNKNOWN_ERROR' +); + +export interface SnappedSpeedLimitsRequest { + /** + * A list of latitude/longitude pairs representing a path. Latitude and longitude values must be separated by commas. + * Latitude/longitude pairs must be separated by the pipe character: "|". + * When you supply the `path` parameter, the API first snaps the path to the most likely road traveled by a vehicle + * (as it does for the [snapToRoads](https://developers.google.com/maps/documentation/roads/snap) request), + * then determines the speed limit for the relevant road segment. + * If you don't want the API to snap the path, you must pass a `placeId` parameter as explained below. + * The following example shows the `path` parameter with three latitude/longitude pairs: + * `path=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796`. + */ + path: LatLng[]; + /** + * Whether to return speed limits in kilometers or miles per hour. This can be set to either `KPH` or `MPH`. + * + * @default SpeedLimitUnit.KPH + */ + units?: SpeedLimitUnit; +} + +export interface SpeedLimitsRequest { + /** + * The place ID(s) representing one or more road segments. + * Make sure each place ID refers to a road segment and not a different type of place. + * You can pass up to 100 place IDs with each request. + * The API does not perform road-snapping on the supplied place IDs. + * The response includes a speed limit for each place ID in the request. + * You can send a [snapToRoads](https://developers.google.com/maps/documentation/roads/snap) or + * [nearestRoads](https://developers.google.com/maps/documentation/roads/nearest) request to find + * the relevant place IDs then supply them as input to the `speedLimits` request. + * The following example shows the `placeId` parameter with two place IDs: + * `placeId=ChIJX12duJAwGQ0Ra0d4Oi4jOGE&placeId=ChIJLQcticc0GQ0RoiNZJVa5GxU` + */ + placeId: string; + /** + * Whether to return speed limits in kilometers or miles per hour. This can be set to either `KPH` or `MPH`. + * + * @default SpeedLimitUnit.KPH + */ + units?: SpeedLimitUnit; +} + +export type SpeedLimitUnit = ( + 'KPH' | + 'MPH' +); + +export interface SpeedLimitsResponse { + /** An array of road metadata. */ + speedLimits: SpeedLimit[]; + /** an array of snapped points. This array is present only if the request contained a path parameter. */ + snappedPoints: SnappedPoint[]; +} + +export interface SpeedLimit { + /** A unique identifier for a place. All place IDs returned by the Roads API will correspond to road segments. */ + placeId: string; + /** The speed limit for that road segment. */ + speedLimit: number; + /** Returns either `KPH` or `MPH`. */ + units: SpeedLimitUnit; +} + +export interface SnappedPoint { + /** contains a `latitude` and `longitude` value. */ + location: LatLngLiteralVerbose; + /** + * An integer that indicates the corresponding value in the original request. + * Each value in the request should map to a snapped value in the response. + * These values are indexed from `0`, so a point with an `originalIndex` of `4` will be the snapped value + * of the 5th latitude/longitude passed to the `path` parameter. + */ + originalIndex: number; + /** + * A unique identifier for a place. All place IDs returned by the Roads API will correspond to road segments. + * The `placeId` can be passed in a speed limits request to determine the speed limit along that road segment. + */ + placeId: string; +} + +export interface SnapToRoadsRequest { + /** + * The path to be snapped. The `path` parameter accepts a list of latitude/longitude pairs. + * Latitude and longitude values should be separated by commas. Coordinates should be separated by the pipe character: `"|"`. + * For example: `path=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796`. + * + * **Note:** The snapping algorithm works best for points that are not too far apart. + * If you observe odd snapping behavior, try creating paths that have points closer together. + * To ensure the best snap-to-road quality, you should aim to provide paths on which consecutive pairs + * of points are within 300m of each other. This will also help in handling any isolated, long jumps between + * consecutive points caused by GPS signal loss, or noise. + */ + path: LatLng[]; + /** + * Whether to interpolate a path to include all points forming the full road-geometry. + * When true, additional interpolated points will also be returned, resulting in a path that smoothly follows + * the geometry of the road, even around corners and through tunnels. + * Interpolated paths will most likely contain more points than the original path. + * + * @default false + */ + interpolate?: boolean; +} + +export interface SnapToRoadsResponse { + /** An array of snapped points. */ + snappedPoints: SnappedPoint[]; +} + +/** + * Time Zone API requests are constructed as a URL string. + * The API returns time zone data for a point on the earth, specified by a latitude/longitude pair. + * Note that time zone data may not be available for locations over water, such as oceans or seas. + */ +export interface TimeZoneRequest { + /** a comma-separated `lat,lng` tuple (eg. `location=-33.86,151.20`), representing the location to look up. */ + location: LatLng; + /** + * specifies the desired time as seconds since midnight, January 1, 1970 UTC. + * The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied, + * based on the time zone of the location. Note that the API does not take historical time zones into account. + * That is, if you specify a past timestamp, the API does not take into account the possibility that + * the location was previously in a different time zone. + */ + timestamp?: Date | number; + /** + * The language in which to return results. + * Note that we often update supported languages so this list may not be exhaustive. + * + * @default Language.English + */ + language?: Language; +} + +/** For each valid request, the time zone service will return a response in the format indicated within the request URL. */ +export interface TimeZoneResponse { + /** + * the offset for daylight-savings time in seconds. + * This will be zero if the time zone is not in Daylight Savings Time during the specified `timestamp`. + */ + dstOffset: number; + /** the offset from UTC (in seconds) for the given location. This does not take into effect daylight savings. */ + rawOffset: number; + /** + * a string containing the ID of the time zone, such as "America/Los_Angeles" or "Australia/Sydney". + * These IDs are defined by [Unicode Common Locale Data Repository (CLDR) project](http://cldr.unicode.org/), + * and currently available in file [timezone.xml](http://unicode.org/repos/cldr/trunk/common/bcp47/timezone.xml). + * When a timezone has several IDs, the canonical one is returned. In timezone.xml, this is the first alias of each timezone. + * For example, "Asia/Calcutta" is returned, not "Asia/Kolkata". + */ + timeZoneId: string; + /** + * a string containing the long form name of the time zone. + * This field will be localized if the `language` parameter is set. + * eg. "Pacific Daylight Time" or "Australian Eastern Daylight Time" + */ + timeZoneName: string; + /** a string indicating the status of the response. */ + status: TimeZoneResponseStatus; + /** more detailed information about the reasons behind the given status code, if other than `OK`. */ + errorMessage: string; +} + +export type TimeZoneResponseStatus = ( + /** indicates that the request was successful. */ + 'OK' | + /** indicates that the request was malformed. */ + 'INVALID_REQUEST' | + /** + * indicates any of the following: + * - The API `key` is missing or invalid. + * - Billing has not been enabled on your account. + * - A self-imposed usage cap has been exceeded. + * - The provided method of payment is no longer valid (for example, a credit card has expired). + * See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this. + */ + 'OVER_DAILY_LIMIT' | + /** indicates the requestor has exceeded quota. */ + 'OVER_QUERY_LIMIT' | + /** indicates that the API did not complete the request. Confirm that the request was sent over HTTPS instead of HTTP. */ + 'REQUEST_DENIED' | + /** indicates an unknown error. */ + 'UNKNOWN_ERROR' | + /** + * indicates that no time zone data could be found for the specified position or time. Confirm that the request is for a location on land, + * and not over water. + */ + 'ZERO_RESULTS' +); diff --git a/types/google__maps/tsconfig.json b/types/google__maps/tsconfig.json new file mode 100644 index 0000000000..c3c1ee93b4 --- /dev/null +++ b/types/google__maps/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@google/maps": [ + "google__maps" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google__maps-tests.ts" + ] +} \ No newline at end of file diff --git a/types/google__maps/tslint.json b/types/google__maps/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/google__maps/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 531074b258..322c29c8dc 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -2613,6 +2613,7 @@ declare namespace google.maps { strictBounds?: boolean; types?: string[]; type?: string; + fields?: string[]; } export interface AutocompletePrediction { @@ -2727,6 +2728,7 @@ declare namespace google.maps { export interface PlaceResult { address_components: GeocoderAddressComponent[]; adr_address: string; + aspects: PlaceAspectRating[]; formatted_address: string; formatted_phone_number: string; geometry: PlaceGeometry; diff --git a/types/graphql-date/index.d.ts b/types/graphql-date/index.d.ts index 4615d424a1..009adebff9 100644 --- a/types/graphql-date/index.d.ts +++ b/types/graphql-date/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tjmehta/graphql-date // Definitions by: Eric Naeseth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLScalarType } from 'graphql'; diff --git a/types/graphql-date/tsconfig.json b/types/graphql-date/tsconfig.json index c55674e246..1db1103639 100644 --- a/types/graphql-date/tsconfig.json +++ b/types/graphql-date/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-depth-limit/tsconfig.json b/types/graphql-depth-limit/tsconfig.json index 5c59137102..cde0c3a496 100644 --- a/types/graphql-depth-limit/tsconfig.json +++ b/types/graphql-depth-limit/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-iso-date/index.d.ts b/types/graphql-iso-date/index.d.ts index 7f0731478e..24283e3d2f 100644 --- a/types/graphql-iso-date/index.d.ts +++ b/types/graphql-iso-date/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/excitement-engineer/graphql-iso-date // Definitions by: Jason Waldrip // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLScalarType } from "graphql"; diff --git a/types/graphql-iso-date/tsconfig.json b/types/graphql-iso-date/tsconfig.json index 1ea5d6fc91..09350f27bb 100644 --- a/types/graphql-iso-date/tsconfig.json +++ b/types/graphql-iso-date/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-list-fields/index.d.ts b/types/graphql-list-fields/index.d.ts index 362658deb9..b20bf869d6 100644 --- a/types/graphql-list-fields/index.d.ts +++ b/types/graphql-list-fields/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jakepusateri/graphql-list-fields#readme // Definitions by: Chris Filipowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLResolveInfo } from "graphql"; diff --git a/types/graphql-list-fields/tsconfig.json b/types/graphql-list-fields/tsconfig.json index 6f53c2c900..2f79913620 100644 --- a/types/graphql-list-fields/tsconfig.json +++ b/types/graphql-list-fields/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-query-complexity/index.d.ts b/types/graphql-query-complexity/index.d.ts index 4c5954fb4f..ba34b4f4e2 100644 --- a/types/graphql-query-complexity/index.d.ts +++ b/types/graphql-query-complexity/index.d.ts @@ -2,6 +2,6 @@ // Project: https://github.com/ivome/graphql-query-complexity // Definitions by: Abhik Mitra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import createQueryComplexityValidator from "./dist"; export default createQueryComplexityValidator; diff --git a/types/graphql-query-complexity/tsconfig.json b/types/graphql-query-complexity/tsconfig.json index d706752c48..4dcc6586aa 100644 --- a/types/graphql-query-complexity/tsconfig.json +++ b/types/graphql-query-complexity/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-relay/index.d.ts b/types/graphql-relay/index.d.ts index 87634b98c9..d4bba06948 100644 --- a/types/graphql-relay/index.d.ts +++ b/types/graphql-relay/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/graphql/graphql-relay-js // Definitions by: Arvitaly , nitintutlani , Grelinfo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLBoolean, diff --git a/types/graphql-relay/tsconfig.json b/types/graphql-relay/tsconfig.json index bf5b3ba6b6..f10d183985 100644 --- a/types/graphql-relay/tsconfig.json +++ b/types/graphql-relay/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-resolve-batch/index.d.ts b/types/graphql-resolve-batch/index.d.ts index 9908b7082a..2baa60d248 100644 --- a/types/graphql-resolve-batch/index.d.ts +++ b/types/graphql-resolve-batch/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/calebmer/graphql-resolve-batch#readme // Definitions by: Rutger Hendrickx // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLResolveInfo } from 'graphql'; diff --git a/types/graphql-resolve-batch/tsconfig.json b/types/graphql-resolve-batch/tsconfig.json index aa4ad6661d..ef3f8a1dc8 100644 --- a/types/graphql-resolve-batch/tsconfig.json +++ b/types/graphql-resolve-batch/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": ["es6", "esnext.asynciterable"], "strictFunctionTypes": true, "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql-type-json/index.d.ts b/types/graphql-type-json/index.d.ts index 2b10599e0e..a6a8ec87ee 100644 --- a/types/graphql-type-json/index.d.ts +++ b/types/graphql-type-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/taion/graphql-type-json#readme // Definitions by: Pavel Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { GraphQLScalarType } from "graphql"; diff --git a/types/graphql-type-json/tsconfig.json b/types/graphql-type-json/tsconfig.json index 479196f574..e0bed0c4f7 100644 --- a/types/graphql-type-json/tsconfig.json +++ b/types/graphql-type-json/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 26c32e3f8a..0b87d35222 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -17,7 +17,7 @@ // Curtis Layne // Jonathan Cardoso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 // The primary entry point into fulfilling a GraphQL request. export { graphql, graphqlSync, GraphQLArgs } from "./graphql"; diff --git a/types/graphql/tslint.json b/types/graphql/tslint.json index 2750cc0197..9e6ea4e366 100644 --- a/types/graphql/tslint.json +++ b/types/graphql/tslint.json @@ -1 +1,20 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "no-any-union": false, + "no-consecutive-blank-lines": false, + "no-duplicate-imports": false, + "no-empty-interface": false, + "no-redundant-undefined": false, + "no-unnecessary-generics": false, + "semicolon": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false, + "use-default-type-parameter": false, + "void-return": false + } +} diff --git a/types/gulp-filter/index.d.ts b/types/gulp-filter/index.d.ts index ba95977024..ae59b2bdb4 100644 --- a/types/gulp-filter/index.d.ts +++ b/types/gulp-filter/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sindresorhus/gulp-filter // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/gulp-filter/tsconfig.json b/types/gulp-filter/tsconfig.json index 43ae1fe5c5..b009c4b2ad 100644 --- a/types/gulp-filter/tsconfig.json +++ b/types/gulp-filter/tsconfig.json @@ -14,10 +14,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "uglify-js": ["uglify-js/v2"] - } + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/types/gulp-rev-replace/index.d.ts b/types/gulp-rev-replace/index.d.ts index 322604bf1d..b385d579a9 100644 --- a/types/gulp-rev-replace/index.d.ts +++ b/types/gulp-rev-replace/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jamesknelson/gulp-rev-replace // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/gulp-rev-replace/tsconfig.json b/types/gulp-rev-replace/tsconfig.json index dfef77b20b..d6b9abe0ba 100644 --- a/types/gulp-rev-replace/tsconfig.json +++ b/types/gulp-rev-replace/tsconfig.json @@ -14,12 +14,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "uglify-js": [ - "uglify-js/v2" - ] - } + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/types/gulp-uglify/index.d.ts b/types/gulp-uglify/index.d.ts index 823ce28e67..4dc340aa18 100644 --- a/types/gulp-uglify/index.d.ts +++ b/types/gulp-uglify/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Christopher Haws // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// @@ -13,17 +14,17 @@ declare namespace GulpUglify { /** * Pass false to skip mangling names. */ - mangle?: boolean; + mangle?: UglifyJS.MangleOptions | boolean; /** * Pass if you wish to specify additional output options. The defaults are optimized for best compression. */ - output?: UglifyJS.BeautifierOptions; + output?: UglifyJS.OutputOptions; /** * Pass an object to specify custom compressor options. Pass false to skip compression completely. */ - compress?: UglifyJS.CompressorOptions | boolean; + compress?: UglifyJS.CompressOptions | boolean; } } diff --git a/types/gulp-uglify/tsconfig.json b/types/gulp-uglify/tsconfig.json index 70663fcc71..b759e9fc57 100644 --- a/types/gulp-uglify/tsconfig.json +++ b/types/gulp-uglify/tsconfig.json @@ -14,12 +14,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "uglify-js": [ - "uglify-js/v2" - ] - } + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/types/gulp-useref/index.d.ts b/types/gulp-useref/index.d.ts index ba95c68308..36cd0ddc24 100644 --- a/types/gulp-useref/index.d.ts +++ b/types/gulp-useref/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jonkemp/gulp-useref // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/gulp-useref/tsconfig.json b/types/gulp-useref/tsconfig.json index f3867032fa..b8a3dc7bba 100644 --- a/types/gulp-useref/tsconfig.json +++ b/types/gulp-useref/tsconfig.json @@ -14,10 +14,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "uglify-js": ["uglify-js/v2"] - } + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 8745a6290e..dcde50413d 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -580,43 +580,43 @@ declare namespace Highcharts { * @default rgba(0, 0, 0, 0.75) * @since 6.0.0 */ - fill: string; + fill?: string; /** * The height of the shape. * @default undefined * @since 6.0.0 */ - height: number; + height?: number; /** * The radius of the shape. * @default 0 * @since 6.0.0 */ - r: number; + r?: number; /** * The color of the shape's stroke. * @default rgba(0, 0, 0, 0.75) * @since 6.0.0 */ - stroke: string; + stroke?: string; /** * The pixel stroke width of the shape. * @default 1 * @since 6.0.0 */ - strokeWidth: number; + strokeWidth?: number; /** * The type of the shape, e.g. circle or rectangle. * @default "rect" * @since 6.0.0 */ - type: "circle" | "path" | "rect"; + type?: "circle" | "path" | "rect"; /** * The width of the shape. * @default undefined * @since 6.0.0 */ - width: number; + width?: number; } interface AnnotationsShape extends AnnotationsShapeOptions { @@ -625,13 +625,13 @@ declare namespace Highcharts { * @default undefined * @since 6.0.0 */ - markerEnd: string; + markerEnd?: string; /** * Id of the marker which will be drawn at the final vertex of the path. Custom markers can be defined in defs property. * @default undefined * @since 6.0.0 */ - markerStart: string; + markerStart?: string; /** * This option defines the point to which the shape will be connected. * It can be either the point which exists in the series - it is referenced by the point's id diff --git a/types/history/createMemoryHistory.d.ts b/types/history/createMemoryHistory.d.ts index e1aca026e2..6142f4e3a4 100644 --- a/types/history/createMemoryHistory.d.ts +++ b/types/history/createMemoryHistory.d.ts @@ -1,4 +1,4 @@ -import { History, Location } from './index'; +import { History, Location, LocationState } from './index'; import { getConfirmation } from './DOMUtils'; export interface MemoryHistoryBuildOptions { @@ -8,9 +8,9 @@ export interface MemoryHistoryBuildOptions { keyLength?: number; } -export interface MemoryHistory extends History { +export interface MemoryHistory extends History { index: number; - entries: Location[]; + entries: Location[]; canGo(n: number): boolean; } diff --git a/types/history/history-tests.ts b/types/history/history-tests.ts index 0a63059b12..689035c9ed 100644 --- a/types/history/history-tests.ts +++ b/types/history/history-tests.ts @@ -1,4 +1,4 @@ -import { createBrowserHistory, createMemoryHistory, createHashHistory, createLocation, Location } from 'history'; +import { createBrowserHistory, createMemoryHistory, createHashHistory, createLocation, Location, History, MemoryHistory } from 'history'; import * as LocationUtils from 'history/LocationUtils'; import * as PathUtils from 'history/PathUtils'; import * as DOMUtils from 'history/DOMUtils'; @@ -7,7 +7,7 @@ import * as ExecutionEnvironment from 'history/ExecutionEnvironment'; let input = { value: "" }; { - let history = createBrowserHistory(); + let history: History<{some: 'state'}> = createBrowserHistory(); // Listen for changes to the current location. The // listener is called once immediately. @@ -43,7 +43,7 @@ let input = { value: "" }; } { - let history = createMemoryHistory(); + let history: MemoryHistory<{the: 'state'}> = createMemoryHistory(); // Pushing a path string. history.push('/the/path'); diff --git a/types/history/index.d.ts b/types/history/index.d.ts index 1c7b35b8f2..3fff510bd2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -8,20 +8,20 @@ export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; export type UnregisterCallback = () => void; -export interface History { +export interface History { length: number; action: Action; - location: Location; - push(path: Path, state?: LocationState): void; - push(location: LocationDescriptorObject): void; - replace(path: Path, state?: LocationState): void; - replace(location: LocationDescriptorObject): void; + location: Location; + push(path: Path, state?: HistoryLocationState): void; + push(location: LocationDescriptorObject): void; + replace(path: Path, state?: HistoryLocationState): void; + replace(location: LocationDescriptorObject): void; go(n: number): void; goBack(): void; goForward(): void; block(prompt?: boolean | string | TransitionPromptHook): UnregisterCallback; listen(listener: LocationListener): UnregisterCallback; - createHref(location: LocationDescriptorObject): Href; + createHref(location: LocationDescriptorObject): Href; } export interface Location { diff --git a/types/host-validation/host-validation-tests.ts b/types/host-validation/host-validation-tests.ts new file mode 100644 index 0000000000..a025432416 --- /dev/null +++ b/types/host-validation/host-validation-tests.ts @@ -0,0 +1,73 @@ +// Copyright (c) 2018 Brannon Dorsey +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import * as express from 'express'; +import * as hostValidation from 'host-validation'; + +const app = express(); + +// allow development hosts, a domain name, and a regex for all subdomains +// host can accept strings or regular expressions +app.use(hostValidation({ hosts: ['127.0.0.1:3000', + 'localhost:3000', + 'mydomain.com', + /.*\.mydomain\.com/] })); + +// referer headers can accept strings or regular expressions +app.use(hostValidation({ referers: ['http://trusted-site.com/login.php', + /^http:\/\/othersite\.com\/login\/.*/] })); + +// only accept POSTs from HTTPS referrers +app.use(hostValidation({ referers: [/^https:\/\//]})); + +// you can include both host and referer values in the config +// by default, only requests that match BOTH Host and Referer values will be allowed +app.use(hostValidation({ hosts: ['trusted-host.com'], + referers: ['https://trusted-host.com/login.php'] })); + +// you can use the { mode: 'either' } value in the config accept requests that match +// either the hosts or the referers requirements. Accepted values for mode include +// 'both' and 'either'. The default value is 'both' if none is specified. +app.use(hostValidation({ hosts: ['trusted-host.com'], + referers: ['https://trusted-host.com/login.php'], + mode: 'either' })); + +// route-specific rules can be specified like any Express.js middleware +app.use('/login', hostValidation({ hosts: ['trusted-host.com'] })); +app.use('/from-twitter', hostValidation({ referers: [/^https:\/\/twitter.com\//] })); + +// Add a custom error handler that's run when host or referer validation fails. +// This function overwrites the default behavior of responding to failed requests +// with a 403 Forbidden error. +app.use('/brew-tea', hostValidation({ + hosts: ['office-teapot'], + fail: (req, res, next) => { + // send a 418 "I'm a Teapot" Error + res.status(418).send('I\'m the office teapot. Refer to me only as such.'); + } +})); + +app.get('/', (req, res) => { + res.send('Hello trusted client, thanks for including 127.0.0.1 in your Host header.'); +}); + +app.listen(3000, () => { + console.log('server allowing HTTP requests from 127.0.0.1 on port 3000'); +}); diff --git a/types/host-validation/index.d.ts b/types/host-validation/index.d.ts new file mode 100644 index 0000000000..7dfc66b559 --- /dev/null +++ b/types/host-validation/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for host-validation 2.0 +// Project: https://github.com/brannondorsey/host-validation +// Definitions by: Rich Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Request, Response, NextFunction } from 'express'; + +declare namespace hostValidation { + interface config { + hosts?: Array; + referers?: Array; + mode?: 'both' | 'either'; + fail?(req: Request, res: Response, next: NextFunction): void; + } +} + +declare function hostValidation(opts: hostValidation.config): + (req: Request, res: Response, next: NextFunction) => void; + +export = hostValidation; diff --git a/types/host-validation/tsconfig.json b/types/host-validation/tsconfig.json new file mode 100644 index 0000000000..af2a26a4fb --- /dev/null +++ b/types/host-validation/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", + "host-validation-tests.ts" + ] +} diff --git a/types/host-validation/tslint.json b/types/host-validation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/host-validation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 61f00f70b2..84433c26ec 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -5,6 +5,7 @@ // Giedrius Grabauskas // Silas Rech // Philipp Katz +// Milan Konir // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -385,6 +386,12 @@ declare namespace i18next { * Compatibility JSON version */ compatibilityJSON?: string; + + /** + * options for i18n nessage format - check documentation of plugin + * @default undefined + */ + i18nFormat?: object; } // Add an indexer to assure that interpolation arguments can be passed @@ -466,6 +473,17 @@ declare namespace i18next { [key: string]: any; } + interface Services { + backendConnector: any; + i18nFormat: any; + interpolator: any; + languageDetector: any; + languageUtils: any; + logger: any; + pluralResolver: any; + resourceStore: Resource; + } + interface i18n { /** * The default export of the i18next module is an i18next instance ready to be initialized by calling init. @@ -485,6 +503,11 @@ declare namespace i18next { */ use(module: any): i18n; + /** + * Internal container for all used plugins and implmentation details like languageUtils, pluralResolvers, etc. + */ + services: Services; + /** * Please have a look at the translation functions like interpolation, formatting and plurals for more details on using it. */ diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts index 25b166e10d..b776165c55 100644 --- a/types/intercom-client/index.d.ts +++ b/types/intercom-client/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/intercom/intercom-node // Definitions by: Jinesh Shah , Josef Hornych // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /// import { List as UserList, User, UserIdentifier } from './User'; diff --git a/types/intercom-client/tslint.json b/types/intercom-client/tslint.json index 3db14f85ea..3d2339d469 100644 --- a/types/intercom-client/tslint.json +++ b/types/intercom-client/tslint.json @@ -1 +1,15 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "comment-format": false, + "eofline": false, + "no-consecutive-blank-lines": false, + "no-padding": false, + "no-trailing-whitespace": false, + "semicolon": false, + "strict-export-declare-modifiers": false, + "trim-file": false + } +} diff --git a/types/is-docker/index.d.ts b/types/is-docker/index.d.ts new file mode 100644 index 0000000000..12b3f6b797 --- /dev/null +++ b/types/is-docker/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-docker 1.1 +// Project: https://github.com/sindresorhus/is-docker#readme +// Definitions by: Yash Kulshrestha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +declare function isDocker(): boolean; +export = isDocker; diff --git a/types/is-docker/is-docker-tests.ts b/types/is-docker/is-docker-tests.ts new file mode 100644 index 0000000000..00274a35e0 --- /dev/null +++ b/types/is-docker/is-docker-tests.ts @@ -0,0 +1,3 @@ +import isDocker from "is-docker"; + +isDocker(); // $ExpectType boolean diff --git a/types/is-docker/tsconfig.json b/types/is-docker/tsconfig.json new file mode 100644 index 0000000000..4c065b1b55 --- /dev/null +++ b/types/is-docker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "esModuleInterop": true + }, + "files": ["index.d.ts", "is-docker-tests.ts"] +} diff --git a/types/is-docker/tslint.json b/types/is-docker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-docker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jest-cli/index.d.ts b/types/jest-cli/index.d.ts new file mode 100644 index 0000000000..64a0f96193 --- /dev/null +++ b/types/jest-cli/index.d.ts @@ -0,0 +1,254 @@ +// Type definitions for jest-cli 23.6 +// Project: https://jestjs.io/ +// Definitions by: Aaron Reisman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export interface UncheckedSnapshot { + filePath: string; + keys: string[]; +} + +export interface SnapshotSummary { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + uncheckedKeysByFile: UncheckedSnapshot[]; + unmatched: number; + updated: number; +} +export type LogMessage = string; + +export interface LogEntry { + message: LogMessage; + origin: string; + type: LogType; +} + +export interface LogCounters { + [label: string]: number; +} + +export interface LogTimers { + [label: string]: Date; +} + +export type LogType = + | "assert" + | "count" + | "debug" + | "dir" + | "dirxml" + | "error" + | "group" + | "groupCollapsed" + | "info" + | "log" + | "time" + | "warn"; + +export type ConsoleBuffer = LogEntry[]; + +export interface Callsite { + column: number; + line: number; +} + +export type Status = "passed" | "failed" | "skipped" | "pending"; + +export interface AssertionResult { + ancestorTitles: string[]; + duration?: number; + failureMessages: string[]; + fullName: string; + location?: Callsite; + numPassingAsserts: number; + status: Status; + title: string; +} + +export interface SerializableError { + code?: any; + message: string; + stack?: string; + type?: string; +} + +export interface TestResult { + console?: ConsoleBuffer; + coverage?: RawCoverage; + displayName?: string; + failureMessage?: string; + leaks: boolean; + memoryUsage?: number; + numFailingTests: number; + numPassingTests: number; + numPendingTests: number; + openHandles: Error[]; + perfStats: { + end: number; + start: number; + }; + skipped: boolean; + snapshot: { + added: number; + fileDeleted: boolean; + matched: number; + unchecked: number; + uncheckedKeys: string[]; + unmatched: number; + updated: number; + }; + sourceMaps: { [sourcePath: string]: string }; + testExecError?: SerializableError; + testFilePath: string; + testResults: AssertionResult[]; +} + +export type ReporterConfig = [string, object]; + +export interface FileCoverageTotal { + total: number; + covered: number; + skipped: number; + pct: number; +} + +export interface CoverageSummary { + lines: FileCoverageTotal; + statements: FileCoverageTotal; + branches: FileCoverageTotal; + functions: FileCoverageTotal; + merge: (other: CoverageSummary) => void; +} + +export interface FileCoverage { + getLineCoverage: () => object; + getUncoveredLines: () => number[]; + getBranchCoverageByLine: () => object; + toJSON: () => object; + merge: (other: object) => void; + computeSimpleTotals: (property: string) => FileCoverageTotal; + computeBranchTotals: () => FileCoverageTotal; + resetHits: () => void; + toSummary: () => CoverageSummary; +} + +export type SnapshotUpdateState = "all" | "new" | "none"; + +export interface RawFileCoverage { + path: string; + s: { [statementId: number]: number }; + b: { [branchId: number]: number }; + f: { [functionId: number]: number }; + l: { [lineId: number]: number }; + fnMap: { [functionId: number]: any }; + statementMap: { [statementId: number]: any }; + branchMap: { [branchId: number]: any }; + inputSourceMap?: object; +} + +export interface RawCoverage { + [filePath: string]: RawFileCoverage; +} + +export interface AggregatedResultWithoutCoverage { + numFailedTests: number; + numFailedTestSuites: number; + numPassedTests: number; + numPassedTestSuites: number; + numPendingTests: number; + numTodoTests: number; + numPendingTestSuites: number; + numRuntimeErrorTestSuites: number; + numTotalTests: number; + numTotalTestSuites: number; + openHandles: Error[]; + snapshot: SnapshotSummary; + startTime: number; + success: boolean; + testResults: TestResult[]; + wasInterrupted: boolean; +} + +export interface CoverageMap { + merge(data: { [index: string]: any }): void; + getCoverageSummary(): FileCoverage; + data: RawCoverage; + addFileCoverage(fileCoverage: RawFileCoverage): void; + files(): string[]; + fileCoverageFor(file: string): FileCoverage; +} + +export interface AggregatedResult extends AggregatedResultWithoutCoverage { + coverageMap?: CoverageMap; +} + +export interface GlobalConfig { + bail: boolean; + changedSince: string; + changedFilesWithAncestor: boolean; + collectCoverage: boolean; + collectCoverageFrom: string[]; + collectCoverageOnlyFrom?: { [key: string]: boolean }; + coverageDirectory: string; + coveragePathIgnorePatterns?: string[]; + coverageReporters: string[]; + coverageThreshold: { global: { [key: string]: number } }; + detectLeaks: boolean; + detectOpenHandles: boolean; + enabledTestsMap?: { [key: string]: { [key: string]: boolean } }; + expand: boolean; + filter?: string; + findRelatedTests: boolean; + forceExit: boolean; + json: boolean; + globalSetup?: string; + globalTeardown?: string; + lastCommit: boolean; + logHeapUsage: boolean; + listTests: boolean; + maxWorkers: number; + noStackTrace: boolean; + nonFlagArgs: string[]; + noSCM?: boolean; + notify: boolean; + notifyMode: string; + outputFile?: string; + onlyChanged: boolean; + onlyFailures: boolean; + passWithNoTests: boolean; + projects: string[]; + replname?: string; + reporters: Array; + runTestsByPath: boolean; + rootDir: string; + silent: boolean; + skipFilter: boolean; + errorOnDeprecated: boolean; + testFailureExitCode: number; + testNamePattern: string; + testPathPattern: string; + testResultsProcessor?: string; + updateSnapshot: SnapshotUpdateState; + useStderr: boolean; + verbose?: boolean; + watch: boolean; + watchAll: boolean; + watchman: boolean; + watchPlugins?: Array<{ path: string; config: { [index: string]: any } }>; +} + +export function run(maybeArgv?: string[], project?: string): Promise; + +export function runCLI( + argv: string[], + projects: string[] +): Promise<{ results: AggregatedResult; globalConfig: GlobalConfig }>; diff --git a/types/jest-cli/jest-cli-tests.ts b/types/jest-cli/jest-cli-tests.ts new file mode 100644 index 0000000000..6cb9342fe7 --- /dev/null +++ b/types/jest-cli/jest-cli-tests.ts @@ -0,0 +1,4 @@ +import * as jest from "jest-cli"; + +// $ExpectType Promise +jest.run(["--config", JSON.stringify({})]); diff --git a/types/jest-cli/tsconfig.json b/types/jest-cli/tsconfig.json new file mode 100644 index 0000000000..dac2e8adb9 --- /dev/null +++ b/types/jest-cli/tsconfig.json @@ -0,0 +1,16 @@ +{ + "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", "jest-cli-tests.ts"] +} diff --git a/types/jest-cli/tslint.json b/types/jest-cli/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jest-cli/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jest-environment-puppeteer/tsconfig.json b/types/jest-environment-puppeteer/tsconfig.json index ed53d60edd..0e9ded7993 100644 --- a/types/jest-environment-puppeteer/tsconfig.json +++ b/types/jest-environment-puppeteer/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index feba5d4e3e..624e86ba90 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -665,7 +665,7 @@ declare namespace jest { * This ensures that a value matches the most recent snapshot with property matchers. * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ - toMatchSnapshot(propertyMatchers: Partial, snapshotName?: string): R; + toMatchSnapshot(propertyMatchers: Partial, snapshotName?: string): R; /** * This ensures that a value matches the most recent snapshot. * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. @@ -676,7 +676,7 @@ declare namespace jest { * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ - toMatchInlineSnapshot(propertyMatchers: Partial, snapshot?: string): R; + toMatchInlineSnapshot(propertyMatchers: Partial, snapshot?: string): R; /** * This ensures that a value matches the most recent snapshot with property matchers. * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 63f1ec8ad9..4082bd9e31 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -628,8 +628,16 @@ describe("", () => { expect({ one: 1, two: "2", + three: 3, + four: { four: 3 }, date: new Date(), - }).toMatchSnapshot({ one: expect.any(Number), date: expect.any(Date) }); + }).toMatchSnapshot({ + one: expect.any(Number), + // Leave 'two' to the auto-generated snapshot + three: 3, + four: { four: expect.any(Number) }, + date: expect.any(Date), + }); expect({}).toMatchInlineSnapshot(); expect({}).toMatchInlineSnapshot("snapshot"); @@ -637,8 +645,16 @@ describe("", () => { expect({ one: 1, two: "2", + three: 3, + four: { four: 3 }, date: new Date(), - }).toMatchInlineSnapshot({ one: expect.any(Number), date: expect.any(Date) }); + }).toMatchInlineSnapshot({ + one: expect.any(Number), + // leave out two + three: 3, + four: { four: expect.any(Number) }, + date: expect.any(Date), + }); expect(jest.fn()).toReturn(); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 2dd5c7f9e7..f3432036cf 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1073,7 +1073,7 @@ export function func(): FunctionSchema; export function number(): NumberSchema; /** - * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects). */ export function object(schema?: SchemaMap): ObjectSchema; diff --git a/types/joi/v10/index.d.ts b/types/joi/v10/index.d.ts index 8e0026a5fe..83b9a51df6 100644 --- a/types/joi/v10/index.d.ts +++ b/types/joi/v10/index.d.ts @@ -981,7 +981,7 @@ export function func(): FunctionSchema; export function number(): NumberSchema; /** - * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects). */ export function object(schema?: SchemaMap): ObjectSchema; diff --git a/types/joi/v6/index.d.ts b/types/joi/v6/index.d.ts index 5f5fb5625d..aad00e2b45 100644 --- a/types/joi/v6/index.d.ts +++ b/types/joi/v6/index.d.ts @@ -731,7 +731,7 @@ export function func(): FunctionSchema; export function number(): NumberSchema; /** - * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects). */ export function object(schema?: SchemaMap): ObjectSchema; diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index b504656014..3b06f50ceb 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -51,6 +51,7 @@ interface JQueryStatic { * @deprecated ​ Deprecated. Use \`{@link ajaxSetup }\`. */ ajaxSettings: JQuery.AjaxSettings; + Animation: JQuery.AnimationStatic; Callbacks: JQuery.CallbacksStatic; /** * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize @@ -72,6 +73,10 @@ interface JQueryStatic { Deferred: JQuery.DeferredStatic; easing: JQuery.Easings; Event: JQuery.EventStatic; + /** + * @see \`{@link https://learn.jquery.com/events/event-extensions/ }\` + */ + event: JQuery.EventExtensions; expr: JQuery.Selectors; // Set to HTMLElement to minimize breaks but should probably be Element. readonly fn: JQuery; @@ -111,6 +116,8 @@ $.when( * @deprecated ​ Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. */ support: JQuery.PlainObject; + timers: Array>; + Tween: JQuery.TweenStatic; // Set to HTMLElement to minimize breaks but should probably be Element. valHooks: JQuery.PlainObject>; // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. @@ -119,10 +126,14 @@ $.when( /** * Creates DOM elements on the fly from the provided string of raw HTML. * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * A string defining a single, standalone, HTML element (e.g.
or
). - * @param ownerDocument_attributes A document in which the new elements will be created. - * An object of attributes, events, and methods to call on the newly-created element. + * @param html _@param_ `html` + *
+ * * `html (ownerDocument)` — A string of HTML to create on the fly. Note that this parses HTML, not XML.
+ * * `html (attributes)` — A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>). + * @param ownerDocument_attributes _@param_ `ownerDocument_attributes` + *
+ * * `ownerDocument` — A document in which the new elements will be created.
+ * * `attributes` — An object of attributes, events, and methods to call on the newly-created element. * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 * @since 1.4 @@ -180,6 +191,7 @@ $( "input:radio", document.forms[ 0 ] ); ```javascript $( "div", xml.responseXML ); ``` +​ */ // tslint:disable-next-line:no-unnecessary-generics (selector: JQuery.Selector, context?: Element | Document | JQuery): JQuery; @@ -1601,8 +1613,8 @@ $( "#log" ).append( "
settings -- " + JSON.stringify( settings ) + "< * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. + * @param success A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 @@ -1615,8 +1627,8 @@ $( "#log" ).append( "
settings -- " + JSON.stringify( settings ) + "< * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. + * @param success A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 @@ -1636,9 +1648,11 @@ $.get( "test.php", function( data ) { * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * A plain object or string that is sent to the server with the request. + * @param success_data _@param_ `success_data` + *
+ * * `success` — A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder.
+ * * `data` — A plain object or string that is sent to the server with the request. * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). @@ -1668,10 +1682,12 @@ $.get( "test.cgi", { name: "John", time: "2pm" } ) /** * Load data from the server using a HTTP GET request. * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. The type option will automatically be set to GET. + * @param url_settings _@param_ `url_settings` + *
+ * * `url` — A string containing the URL to which the request is sent.
+ * * `settings` — A set of key/value pairs that configure the Ajax request. All properties except for `url` are + * optional. A default can be set for any option with \`{@link ajaxSetup $.ajaxSetup()}\`. See \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings jQuery.ajax( settings )}\` + * for a complete list of all settings. The type option will automatically be set to `GET`. * @see \`{@link https://api.jquery.com/jQuery.get/ }\` * @since 1.0 * @since 1.12 @@ -1698,8 +1714,10 @@ $.get( "test.php" ); * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. - * A plain object or string that is sent to the server with the request. + * @param success_data _@param_ `url_settings` + *
+ * * `success` — A callback function that is executed if the request succeeds.
+ * * `data` — A plain object or string that is sent to the server with the request. * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` * @since 1.0 * @example ​ ````Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API. @@ -2620,8 +2638,10 @@ $.param({ a: { b: 1, c: 2 }, d: [ 3, 4, { e: 5 } ] }); * Parses a string into an array of DOM nodes. * * @param data HTML string to be parsed - * @param context_keepScripts Document element to serve as the context in which the HTML fragment will be created - * A Boolean indicating whether to include scripts passed in the HTML string + * @param context_keepScripts _@param_ `context_keepScripts` + *
+ * * `context` — Document element to serve as the context in which the HTML fragment will be created
+ * * `keepScripts` — A Boolean indicating whether to include scripts passed in the HTML string * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` * @since 1.8 * @example ​ ````Create an array of DOM nodes using an HTML string and insert it into a div. @@ -2763,9 +2783,11 @@ $.post( "test.php", { func: "getNameAndTime" }, function( data ) { * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * A plain object or string that is sent to the server with the request. + * @param success_data _@param_ `success_data` + *
+ * * `success` — A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but can be `null` in that case.
+ * * `data` — A plain object or string that is sent to the server with the request. * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). @@ -2843,10 +2865,12 @@ $( "#searchForm" ).submit(function( event ) { /** * Load data from the server using a HTTP POST request. * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. Type will automatically be set to POST. + * @param url_settings _@param_ `url_settings` + *
+ * * `url` — A string containing the URL to which the request is sent.
+ * * `settings` — A set of key/value pairs that configure the Ajax request. All properties except for `url` are optional. + * A default can be set for any option with \`{@link ajaxSetup $.ajaxSetup()}\`. See \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings jQuery.ajax( settings )}\` + * for a complete list of all settings. Type will automatically be set to `POST`. * @see \`{@link https://api.jquery.com/jQuery.post/ }\` * @since 1.0 * @since 1.12 @@ -12960,8 +12984,10 @@ $( "span:eq(3)" ).text( "" + jQuery.data( div, "test2" ) ); * Creates an object containing a set of properties ready to be used in the definition of custom animations. * * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. + * @param easing_complete _@param_ `easing_complete` + *
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` * @since 1.0 * @since 1.1 @@ -12971,8 +12997,11 @@ $( "span:eq(3)" ).text( "" + jQuery.data( div, "test2" ) ); /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * - * @param duration_complete_settings A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. + * @param duration_complete_settings _@param_ `duration_complete_settings` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `settings` — * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` * @since 1.0 * @since 1.1 @@ -13023,7 +13052,7 @@ $.trim(" hello, how are you? "); * @param obj Object to get the internal JavaScript [[Class]] of. * @see \`{@link https://api.jquery.com/jQuery.type/ }\` * @since 1.4.3 - * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/jquery/issues/3605 }`. + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/jquery/issues/3605 }\`. * @example ​ ````Find out if the parameter is a RegExp. ```html @@ -13952,8 +13981,10 @@ $( "p" ).animate({ * Perform a custom animation of a set of CSS properties. * * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/animate/ }\` * @since 1.0 @@ -16703,8 +16734,10 @@ $( "input[type='checkbox']" ).check(); /** * Display the matched elements by fading them to opaque. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/fadeIn/ }\` * @since 1.0 @@ -16768,10 +16801,12 @@ $( "a" ).click(function() { /** * Display the matched elements by fading them to opaque. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/fadeIn/ }\` * @since 1.0 * @since 1.4.3 @@ -16889,8 +16924,10 @@ $( "#btn2" ).click(function() { /** * Hide the matched elements by fading them to transparent. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/fadeOut/ }\` * @since 1.0 @@ -16948,10 +16985,12 @@ $( "span" ).hover(function() { /** * Hide the matched elements by fading them to transparent. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/fadeOut/ }\` * @since 1.0 * @since 1.4.3 @@ -17201,8 +17240,10 @@ $( "button:last" ).click(function() { /** * Display or hide the matched elements by animating their opacity. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/fadeToggle/ }\` * @since 1.0 @@ -17243,10 +17284,12 @@ $( "button:last" ).click(function() { /** * Display or hide the matched elements by animating their opacity. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/fadeToggle/ }\` * @since 1.0 * @since 1.4.3 @@ -18108,8 +18151,10 @@ $( "#getw" ).click(function() { * Hide the matched elements. * * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. + * @param easing_complete _@param_ `easing_complete` + *
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/hide/ }\` * @since 1.0 * @since 1.4.3 @@ -18195,9 +18240,11 @@ $( "div" ).click(function() { /** * Hide the matched elements. * - * @param duration_complete_options A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_complete_options _@param_ `duration_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/hide/ }\` * @since 1.0 * @example ​ ````Hides all paragraphs then the link on click. @@ -19514,8 +19561,10 @@ $( "#feeds" ).load( "feeds.php", { limit: 25 }, function() { * Load data from the server and place the returned HTML into the matched element. * * @param url A string containing the URL to which the request is sent. - * @param complete_data A callback function that is executed when the request completes. - * A plain object or string that is sent to the server with the request. + * @param complete_data _@param_ `complete_data` + *
+ * * `complete` — A callback function that is executed when the request completes.
+ * * `data` — A plain object or string that is sent to the server with the request. * @see \`{@link https://api.jquery.com/load/ }\` * @since 1.0 * @example ​ ````Load another page's list items into an ordered list. @@ -20652,8 +20701,10 @@ $( "body" ).off( "click", "p", foo ); * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as * "click", "keydown.myPlugin", or ".myPlugin". - * @param selector_handler A selector which should match the one originally passed to .on() when attaching event handlers. - * A function to execute each time the event is triggered. + * @param selector_handler _@param_ `selector_handler` + *
+ * * `selector` — A selector which should match the one originally passed to `.on()` when attaching event handlers.
+ * * `handler` — A handler function previously attached for the event(s), or the special value `false`. * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 * @example ​ ````Remove all delegated click handlers from all paragraphs: @@ -23773,8 +23824,10 @@ $( "input" ).select(); * Display the matched elements. * * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. + * @param easing_complete _@param_ `easing_complete` + *
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/show/ }\` * @since 1.0 * @since 1.4.3 @@ -23881,9 +23934,11 @@ $( "form" ).submit(function( event ) { /** * Display the matched elements. * - * @param duration_complete_options A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_complete_options _@param_ `duration_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/show/ }\` * @since 1.0 * @example ​ ````Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. @@ -24116,8 +24171,10 @@ $( "p" ).slice( -1 ).wrapInner( "" ); /** * Display the matched elements with a sliding motion. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/slideDown/ }\` * @since 1.0 @@ -24182,10 +24239,12 @@ $( "div" ).click(function() { /** * Display the matched elements with a sliding motion. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/slideDown/ }\` * @since 1.0 * @since 1.4.3 @@ -24243,8 +24302,10 @@ $( document.body ).click(function () { /** * Display or hide the matched elements with a sliding motion. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/slideToggle/ }\` * @since 1.0 @@ -24312,10 +24373,12 @@ $( "#aa" ).click(function() { /** * Display or hide the matched elements with a sliding motion. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/slideToggle/ }\` * @since 1.0 * @since 1.4.3 @@ -24366,8 +24429,10 @@ $( "button" ).click(function() { /** * Hide the matched elements with a sliding motion. * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. + * @param duration_easing _@param_ `duration_easing` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition. * @param complete A function to call once the animation is complete, called once per matched element. * @see \`{@link https://api.jquery.com/slideUp/ }\` * @since 1.0 @@ -24421,10 +24486,12 @@ $( "button" ).click(function() { /** * Hide the matched elements with a sliding motion. * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `easing` — A string indicating which easing function to use for the transition.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method. * @see \`{@link https://api.jquery.com/slideUp/ }\` * @since 1.0 * @since 1.4.3 @@ -24797,10 +24864,12 @@ disp( $( "div" ).toArray().reverse() ); /** * Display or hide the matched elements. * - * @param duration_complete_options_display A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * Use true to show the element or false to hide it. + * @param duration_complete_options_display _@param_ `duration_complete_options_display` + *
+ * * `duration` — A string or number determining how long the animation will run.
+ * * `complete` — A function to call once the animation is complete, called once per matched element.
+ * * `options` — A map of additional options to pass to the method.
+ * * `display` — Use true to show the element or false to hide it. * @see \`{@link https://api.jquery.com/toggle/ }\` * @since 1.0 * @since 1.3 @@ -29925,6 +29994,353 @@ $.get( "test.php" ) // region Effects // #region Effects + type Duration = number | 'fast' | 'slow'; + + /** + * @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\` + */ + interface EffectsOptions extends PlainObject { + /** + * A function to be called when the animation on an element completes or stops without completing (its + * Promise object is either resolved or rejected). + */ + always?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A function that is called once the animation on an element is complete. + */ + complete?(this: TElement): void; + /** + * A function to be called when the animation on an element completes (its Promise object is resolved). + */ + done?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A string or number determining how long the animation will run. + */ + duration?: Duration; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to be called when the animation on an element fails to complete (its Promise object is rejected). + */ + fail?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A function to be called after each step of the animation, only once per animated element regardless + * of the number of animated properties. + */ + progress?(this: TElement, animation: Animation, progress: number, remainingMs: number): void; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation + * will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case + * the animation is added to the queue represented by that string. When a custom queue name is used the + * animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: boolean | string; + /** + * An object containing one or more of the CSS properties defined by the properties argument and their + * corresponding easing functions. + */ + specialEasing?: PlainObject; + /** + * A function to call when the animation on an element begins. + */ + start?(this: TElement, animation: Animation): void; + /** + * A function to be called for each animated property of each animated element. This function provides + * an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?(this: TElement, now: number, tween: Tween): void; + } + + // region Animation + // #region Animation + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + interface AnimationStatic { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + (element: TElement, props: PlainObject, opts: EffectsOptions): Animation; + /** + * During the initial setup, `jQuery.Animation` will call any callbacks that have been registered through `jQuery.Animation.prefilter( function( element, props, opts ) )`. + * + * @param callback The prefilter will have `this` set to an animation object, and you can modify any of the `props` or + * `opts` however you need. The prefilter _may_ return its own promise which also implements `stop()`, + * in which case, processing of prefilters stops. If the prefilter is not trying to override the animation + * entirely, it should return `undefined` or some other falsy value. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#prefilters }\` + * @since 1.8 + */ + prefilter( + callback: (this: Animation, element: TElement, props: PlainObject, opts: EffectsOptions) => Animation | _Falsy | void, + prepend?: boolean + ): void; + /** + * A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property. + * + * You can override the default process for creating a tween in order to provide your own tween object by using `jQuery.Animation.tweener( props, callback( prop, value ) )`. + * + * @param props A space separated list of properties to be passed to your tweener, or `"*"` if it should be called + * for all properties. + * @param callback The callback will be called with `this` being an `Animation` object. The tweener function will + * generally start with `var tween = this.createTween( prop, value );`, but doesn't nessecarily need to + * use the `jQuery.Tween()` factory. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\` + * @since 1.8 + */ + tweener(props: string, callback: Tweener): void; + } + + /** + * The promise will be resolved when the animation reaches its end, and rejected when terminated early. The context of callbacks attached to the promise will be the element, and the arguments will be the `Animation` object and a boolean `jumpedToEnd` which when true means the animation was stopped with `gotoEnd`, when `undefined` the animation completed naturally. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + interface Animation extends Promise3< + Animation, Animation, Animation, + true | undefined, false, number, + never, never, number + > { + /** + * The duration specified in ms + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + duration: number; + /** + * The element being animatied + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + elem: TElement; + /** + * The final value of each property animating + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + props: PlainObject; + /** + * The animation options + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + opts: EffectsOptions; + /** + * The original properties before being filtered + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + originalProps: PlainObject; + /** + * The original options before being filtered + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + originalOpts: EffectsOptions; + /** + * The numeric value of `new Date()` when the animation began + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + startTime: number; + /** + * The animations tweens. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + tweens: Array>; + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + createTween(propName: string, finalValue: number): Tween; + /** + * Stops the animation early, optionally going to the end. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + stop(gotoEnd: boolean): this; + } + + /** + * A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\` + * @since 1.8 + */ + type Tweener = (this: Animation, propName: string, finalValue: number) => Tween; + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + interface TweenStatic { + /** + * `jQuery.Tween.propHooks[ prop ]` is a hook point that replaces `jQuery.fx.step[ prop ]` (which is being deprecated.) These hooks are used by the tween to get and set values on elements. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + * @example +```javascript +jQuery.Tween.propHooks[ property ] = { + get: function( tween ) { + // get tween.prop from tween.elem and return it + }, + set: function( tween ) { + // set tween.prop on tween.elem to tween.now + tween.unit + } +} +``` + */ + propHooks: PropHooks; + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + (elem: TElement, options: EffectsOptions, prop: string, end: number, easing?: string, unit?: string): Tween; + } + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + // This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery. + interface Tween { + /** + * The easing used + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + easing: string; + /** + * The element being animated + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + elem: TElement; + /** + * The ending value of the tween + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + end: number; + /** + * The current value of the tween + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + now: number; + /** + * A reference to the animation options + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + options: EffectsOptions; + // Undocumented. Is this intended to be public? + pos?: number; + /** + * The property being animated + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + prop: string; + /** + * The starting value of the tween + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + start: number; + /** + * The CSS unit for the tween + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + unit: string; + /** + * Reads the current value for property from the element + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + cur(): any; + /** + * Updates the value for the property on the animated elemd. + * + * @param progress A number from 0 to 1. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + run(progress: number): this; + } + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type PropHook = { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + get(tween: Tween): any; + } | { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + set(tween: Tween): void; + } | { + [key: string]: never; + }; + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + interface PropHooks { + [property: string]: PropHook; + } + + // #endregion + + // region Easing + // #region Easing + + type EasingMethod = (percent: number) => number; + + interface Easings { + [name: string]: EasingMethod; + } + + // #endregion + + // region Effects (fx) + // #region Effects (fx) + interface Effects { /** * The rate (in milliseconds) at which animations fire. @@ -30014,10 +30430,65 @@ $( "input" ).click(function() { ``` */ off: boolean; + /** + * @deprecated ​ Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`. + * + * `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook. + */ step: PlainObject>; + /** + * _overridable_ Clears up the `setInterval` + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + stop(): void; + /** + * Calls `.run()` on each object in the `jQuery.timers` array, removing it from the array if `.run()` returns a falsy value. Calls `jQuery.fx.stop()` whenever there are no timers remaining. + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + tick(): void; + /** + * _overridable_ Creates a `setInterval` if one doesn't already exist, and pushes `tickFunction` to the `jQuery.timers` array. `tickFunction` should also have `anim`, `elem`, and `queue` properties that reference the animation object, animated element, and queue option to facilitate `jQuery.fn.stop()` + * + * By overriding `fx.timer` and `fx.stop` you should be able to implement any animation tick behaviour you desire. (like using `requestAnimationFrame` instead of `setTimeout`.) + * + * There is an example of overriding the timer loop in \`{@link https://github.com/gnarf37/jquery-requestAnimationFrame jquery.requestAnimationFrame}\` + * + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + timer(tickFunction: TickFunction): void; } - type Duration = number | 'fast' | 'slow'; + /** + * @deprecated ​ Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`. + * + * `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook. + */ + interface AnimationHook { + /** + * @deprecated ​ Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`. + * + * `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook. + */ + (fx: Tween): void; + } + + interface TickFunction { + anim: Animation; + elem: TElement; + queue: boolean | string; + (): any; + } + + // #endregion + + // region Queue + // #region Queue + // TODO: Is the first element always a string or is that specific to the 'fx' queue? type Queue = { 0: string; } & Array>; @@ -30025,128 +30496,32 @@ $( "input" ).click(function() { (this: TElement, next: () => void): void; } - /** - * @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\` - */ - interface EffectsOptions { - /** - * A function to be called when the animation on an element completes or stops without completing (its - * Promise object is either resolved or rejected). - */ - always?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A function that is called once the animation on an element is complete. - */ - complete?(this: TElement): void; - /** - * A function to be called when the animation on an element completes (its Promise object is resolved). - */ - done?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A string or number determining how long the animation will run. - */ - duration?: Duration; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to be called when the animation on an element fails to complete (its Promise object is rejected). - */ - fail?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A function to be called after each step of the animation, only once per animated element regardless - * of the number of animated properties. - */ - progress?(this: TElement, animation: Promise, progress: number, remainingMs: number): void; - /** - * A Boolean indicating whether to place the animation in the effects queue. If false, the animation - * will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case - * the animation is added to the queue represented by that string. When a custom queue name is used the - * animation does not automatically start; you must call .dequeue("queuename") to start it. - */ - queue?: boolean | string; - /** - * An object containing one or more of the CSS properties defined by the properties argument and their - * corresponding easing functions. - */ - specialEasing?: PlainObject; - /** - * A function to call when the animation on an element begins. - */ - start?(this: TElement, animation: Promise): void; - /** - * A function to be called for each animated property of each animated element. This function provides - * an opportunity to modify the Tween object to change the value of the property before it is set. - */ - step?(this: TElement, now: number, tween: Tween): void; - } + // #endregion - interface SpeedSettings { + // region Speed + // #region Speed + + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type SpeedSettings = { /** * A string or number determining how long the animation will run. */ - duration?: Duration; + duration: Duration; + } | { /** * A string indicating which easing function to use for the transition. */ - easing?: string; + easing: string; + } | { /** * A function to call once the animation is complete. */ - complete?(this: TElement): void; - } + complete(this: TElement): void; + } | { + [key: string]: never; + }; - // This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery. - // Undocumented - // https://github.com/jquery/api.jquery.com/issues/391 - // https://github.com/jquery/api.jquery.com/issues/61 - interface Tween { - easing: string; - elem: TElement; - end: number; - now: number; - options: EffectsOptions; - pos: number; - prop: string; - start: number; - unit: string; - } - - interface AnimationHook { - (fx: Tween): void; - } - - /** - * @deprecated ​ Deprecated. - * - * **Cause**: Additional arguments for `jQuery.easing` methods were never documented and are redundant since the same behavior can be easily achieved without them. When Migrate detects this case, the specified easing function is not used and `"linear"` easing is used instead for the animation. - * - * **Solution**: Rewrite the easing function to only use one argument. If you are using the \`{@link http://gsgd.co.uk/sandbox/jquery/easing jQuery Easing plugin}\`, upgrade to \`{@link https://github.com/gdsmith/jquery.easing/releases version 1.4.0 or higher}\`. - * - * For example, to implement \`{@link https://en.wikipedia.org/wiki/Cubic_function Cubic easing}\`, the old function might be: - * -```js -jQuery.easing.easeInCubic = function ( p, t, b, c, d ) { - return c * ( t /= d ) * t * t + b; -} -``` - * - * You can achive same effect with this: - * -```js -jQuery.easing.easeInCubic = function ( p ) { - return Math.pow( p, 3 ); -} -``` - * - * See jQuery-ui \`{@link https://github.com/jquery/jquery-ui/commit/c0093b599fcd58b6ad122ab425c4cc1a4da4a520#diff-9cd789a170c765edcf0f4854db386e1a commit}\` for other possible cases. - */ - type EasingMethod = (p: number, t: number, b: number, c: number, d: number) => number; - - interface Easings { - [name: string]: EasingMethod; - } + // #endregion // #endregion @@ -30737,8 +31112,10 @@ $( "p" ).click(function( event ) { } // Generic members - interface Event { + interface Event< + TTarget = EventTarget, + TData = null + > { /** * The current DOM element within the event bubbling phase. * @@ -30918,6 +31295,317 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); (this: TContext, t: T, ...args: any[]): void | false | any; } + // region Event extensions + // #region Event extensions + + interface EventExtensions { + /** + * jQuery defines an \`{@link https://api.jquery.com/category/events/event-object/ Event object}\` that + * represents a cross-browser subset of the information available when an event occurs. The `jQuery.event.props` + * property is an array of string names for properties that are always copied when jQuery processes a + * native browser event. (Events fired in code by `.trigger()` do not use this list, since the code can + * construct a `jQuery.Event` object with the needed values and trigger using that object.) + * + * To add a property name to this list, use `jQuery.event.props.push( "newPropertyName" )`. However, be + * aware that every event processed by jQuery will now attempt to copy this property name from the native + * browser event to jQuery's constructed event. If the property does not exist for that event type, it + * will get an undefined value. Adding many properties to this list can significantly reduce event + * delivery performance, so for infrequently-needed properties it is more efficient to use the value + * directly from `event.originalEvent` instead. If properties must be copied, you are strongly advised + * to use `jQuery.event.fixHooks` as of version 1.7. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-props-array }\` + */ + props: string[]; + /** + * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that + * jQuery creates when it processes a _native_ browser event. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` + */ + fixHooks: FixHooks; + /** + * The jQuery special event hooks are a set of per-event-name functions and properties that allow code + * to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in + * that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the + * name of the special event. Event names are case sensitive. + * + * As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated + * pieces of code want to process the same event name. Special event authors who need to modify events + * with existing hooks will need to take precautions to avoid introducing unwanted side-effects by + * clobbering those hooks. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\` + */ + special: SpecialEventHooks; + } + + interface FixHook { + /** + * Strings representing properties that should be copied from the browser's event object to the jQuery + * event object. If omitted, no additional properties are copied beyond the standard ones that jQuery + * copies and normalizes (e.g. `event.target` and `event.relatedTarget`). + */ + props?: string[]; + /** + * jQuery calls this function after it constructs the `jQuery.Event` object, copies standard properties + * from `jQuery.event.props`, and copies the `fixHooks`-specific props (if any) specified above. The + * function can create new properties on the event object or modify existing ones. The second argument + * is the browser's native event object, which is also available in `event.originalEvent`. + * + * Note that for all events, the browser's native event object is available in `event.originalEvent`; + * if the jQuery event handler examines the properties there instead of jQuery's normalized `event` + * object, there is no need to create a `fixHooks` entry to copy or modify the properties. + * + * @example ​ ````For example, to set a hook for the "drop" event that copies the `dataTransfer` property, assign an object to `jQuery.event.fixHooks.drop`: +```javascript +jQuery.event.fixHooks.drop = { + props: [ "dataTransfer" ] +}; +``` + +Since fixHooks is an advanced feature and rarely used externally, jQuery does not include code or +interfaces to deal with conflict resolution. If there is a chance that some other code may be assigning +`fixHooks` to the same events, the code should check for an existing hook and take appropriate measures. +A simple solution might look like this: + +```javascript +if ( jQuery.event.fixHooks.drop ) { + throw new Error( "Someone else took the jQuery.event.fixHooks.drop hook!" ); +} + +jQuery.event.fixHooks.drop = { + props: [ "dataTransfer" ] +}; +``` + +When there are known cases of different plugins wanting to attach to the drop hook, this solution might be more appropriate: + +```javascript +var existingHook = jQuery.event.fixHooks.drop; + +if ( !existingHook ) { + jQuery.event.fixHooks.drop = { + props: [ "dataTransfer" ] + }; +} else { + if ( existingHook.props ) { + existingHook.props.push( "dataTransfer" ); + } else { + existingHook.props = [ "dataTransfer" ]; + } +} +``` + */ + filter?(event: Event, originalEvent: _Event): void; + } + + /** + * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that + * jQuery creates when it processes a _native_ browser event. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` + */ + interface FixHooks { + [event: string]: FixHook; + } + + // region Special event hooks + // #region Special event hooks + + /** + * The jQuery special event hooks are a set of per-event-name functions and properties that allow code + * to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in + * that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the + * name of the special event. Event names are case sensitive. + * + * As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated + * pieces of code want to process the same event name. Special event authors who need to modify events + * with existing hooks will need to take precautions to avoid introducing unwanted side-effects by + * clobbering those hooks. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\` + */ + interface SpecialEventHook { + /** + * Indicates whether this event type should be bubbled when the `.trigger()` method is called; by + * default it is `false`, meaning that a triggered event will bubble to the element's parents up to the + * document (if attached to a document) and then to the window. Note that defining `noBubble` on an + * event will effectively prevent that event from being used for delegated events with `.trigger()`. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#nobubble-boolean }\` + */ + noBubble?: boolean; + /** + * When defined, these string properties specify that a special event should be handled like another + * event type until the event is delivered. The `bindType` is used if the event is attached directly, + * and the `delegateType` is used for delegated events. These types are generally DOM event types, + * and _should not_ be a special event themselves. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\` + */ + bindType?: string; + /** + * When defined, these string properties specify that a special event should be handled like another + * event type until the event is delivered. The `bindType` is used if the event is attached directly, + * and the `delegateType` is used for delegated events. These types are generally DOM event types, + * and _should not_ be a special event themselves. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\` + */ + delegateType?: string; + /** + * The setup hook is called the first time an event of a particular type is attached to an element; + * this provides the hook an opportunity to do processing that will apply to all events of this type on + * this element. The `this` keyword will be a reference to the element where the event is being attached + * and `eventHandle` is jQuery's event handler function. In most cases the `namespaces` argument should + * not be used, since it only represents the namespaces of the _first_ event being attached; subsequent + * events may not have this same namespaces. + * + * This hook can perform whatever processing it desires, including attaching its own event handlers to + * the element or to other elements and recording setup information on the element using the `jQuery.data()` + * method. If the setup hook wants jQuery to add a browser event (via `addEventListener` or `attachEvent`, + * depending on browser) it should return `false`. In all other cases, jQuery will not add the browser + * event, but will continue all its other bookkeeping for the event. This would be appropriate, for + * example, if the event was never fired by the browser but invoked by `.trigger()`. To attach the jQuery + * event handler in the setup hook, use the `eventHandle` argument. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#setup-function-data-object-namespaces-eventhandle-function }\` + */ + setup?(this: TTarget, data: TData, namespaces: string, eventHandle: EventHandler): void | false; + /** + * The teardown hook is called when the final event of a particular type is removed from an element. + * The `this` keyword will be a reference to the element where the event is being cleaned up. This hook + * should return `false` if it wants jQuery to remove the event from the browser's event system (via + * `removeEventListener` or `detachEvent`). In most cases, the setup and teardown hooks should return + * the same value. + * + * If the setup hook attached event handlers or added data to an element through a mechanism such as + * `jQuery.data()`, the teardown hook should reverse the process and remove them. jQuery will generally + * remove the data and events when an element is totally removed from the document, but failing to + * remove data or events on teardown will cause a memory leak if the element stays in the document. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#teardown-function }\` + */ + teardown?(this: TTarget): void | false; + /** + * Each time an event handler is added to an element through an API such as `.on()`, jQuery calls this + * hook. The `this` keyword will be the element to which the event handler is being added, and the + * `handleObj` argument is as described in the section above. The return value of this hook is ignored. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#add-function-handleobj }\` + */ + add?(this: TTarget, handleObj: HandleObject): void; + /** + * When an event handler is removed from an element using an API such as `.off()`, this hook is called. + * The `this` keyword will be the element where the handler is being removed, and the `handleObj` + * argument is as described in the section above. The return value of this hook is ignored. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#remove-function-handleobj }\` + */ + remove?(this: TTarget, handleObj: HandleObject): void; + /** + * Called when the `.trigger()` or `.triggerHandler()` methods are used to trigger an event for the + * special type from code, as opposed to events that originate from within the browser. The `this` + * keyword will be the element being triggered, and the event argument will be a `jQuery.Event` object + * constructed from the caller's input. At minimum, the event type, data, namespace, and target + * properties are set on the event. The data argument represents additional data passed by `.trigger()` + * if present. + * + * The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` + * object is constructed and before any handlers have been called. It can process the triggered event + * in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before + * returning. If the hook returns `false`, jQuery does not perform any further event triggering actions + * and returns immediately. Otherwise, it performs the normal trigger processing, calling any event + * handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` + * was specified for the special event) to call event handlers attached to parent elements. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\` + */ + trigger?(this: TTarget, event: Event, data: TData): void | false; + /** + * When the `.trigger()` method finishes running all the event handlers for an event, it also looks for + * and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. + * So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a + * `_default` hook is specified, the hook is called just prior to checking for and executing the element's + * default method. If this hook returns the value `false` the element's default method will be called; + * otherwise it is not. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\` + */ + _default?(event: Event, data: TData): void | false; + /** + * jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event + * handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it + * _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was + * not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` + * property has the detailed event information. + * + * Based in the information it has, the handle hook should decide whether to call the original handler + * function which is in `event.handleObj.handler`. It can modify information in the event object before + * calling the original handler, but _must restore_ that data before returning or subsequent unrelated + * event handlers may act unpredictably. In most cases, the handle hook should return the result of the + * original handler, but that is at the discretion of the hook. The handle hook is unique in that it is + * the only special event function hook that is called under its original special event name when the + * type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to + * have anything other than a handle hook present if the special event defines a `bindType` and + * `delegateType`, since those other hooks will never be called. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\` + */ + handle?(this: TTarget, event: Event & { handleObj: HandleObject; }, ...data: TData[]): void; + } + + interface SpecialEventHooks { + [event: string]: SpecialEventHook; + } + + /** + * Many of the special event hook functions below are passed a `handleObj` object that provides more + * information about the event, how it was attached, and its current state. This object and its contents + * should be treated as read-only data, and only the properties below are documented for use by special + * event handlers. + * + * @see \`{@link https://learn.jquery.com/events/event-extensions/#the-handleobj-object }\` + */ + interface HandleObject { + /** + * The type of event, such as `"click"`. When special event mapping is used via `bindType` or + * `delegateType`, this will be the mapped type. + */ + readonly type: string; + /** + * The original type name regardless of whether it was mapped via `bindType` or `delegateType`. So when + * a "pushy" event is mapped to "click" its `origType` would be "pushy". + */ + readonly origType: string; + /** + * Namespace(s), if any, provided when the event was attached, such as `"myPlugin"`. When multiple + * namespaces are given, they are separated by periods and sorted in ascending alphabetical order. If + * no namespaces are provided, this property is an empty string. + */ + readonly namespace: string; + /** + * For delegated events, this is the selector used to filter descendant elements and determine if the + * handler should be called. For directly bound events, this property is `null`. + */ + readonly selector: string | undefined | null; + /** + * The data, if any, passed to jQuery during event binding, e.g. `{ myData: 42 }`. If the data argument + * was omitted or `undefined`, this property is `undefined` as well. + */ + readonly data: TData; + /** + * Event handler function passed to jQuery during event binding. If `false` was passed during event + * binding, the handler refers to a single shared function that simply returns `false`. + */ + readonly handler: EventHandler; + } + + // #endregion + + // #endregion + // #endregion interface NameValuePair { @@ -30940,6 +31628,8 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); get?(elem: TElement): any; set?(elem: TElement, value: any): any; } + + type _Falsy = false | null | undefined | 0 | '' | typeof document.all; } // region Legacy types diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index bfb58a3e60..37ddc27c56 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -8,6 +8,11 @@ function JQueryStatic() { $.ajaxSettings; } + function Animation() { + // $ExpectType AnimationStatic + $.Animation; + } + function Callbacks() { // $ExpectType CallbacksStatic $.Callbacks; @@ -38,6 +43,11 @@ function JQueryStatic() { $.Event; } + function event() { + // $ExpectType EventExtensions + $.event; + } + function expr() { // $ExpectType Selectors $.expr; @@ -63,6 +73,16 @@ function JQueryStatic() { $.support; } + function timers() { + // $ExpectType TickFunction[] + $.timers; + } + + function Tween() { + // $ExpectType TweenStatic + $.Tween; + } + function valHooks() { // $ExpectType PlainObject> $.valHooks; @@ -1786,6 +1806,10 @@ function JQueryStatic() { } }); + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + $.speed(false); + // $ExpectType EffectsOptions $.speed(); } @@ -7819,6 +7843,197 @@ function JQuery_Deferred() { } } +function JQuery_EffectsOptions() { + $('p').show({ + always(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + complete() { + // $ExpectType HTMLElement + this; + }, + done(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + duration: 5000, + easing: 'linear', + fail(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + progress(animation, progress, remainingMs) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType number + progress; + // $ExpectType number + remainingMs; + }, + queue: true, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + start(animation) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + }, + step(now, tween) { + // $ExpectType HTMLElement + this; + // $ExpectType number + now; + // $ExpectType Tween + tween; + } + }); +} + +function JQuery_AnimationStatic() { + function call_signature() { + // $ExpectType Animation + $.Animation({} as HTMLElement, {}, {}); + } + + function prefilter() { + // https://github.com/jquery/api.jquery.com/issues/256 -> http://jsfiddle.net/y4L35/ + { + // $ExpectType void + $.Animation.prefilter(function(element: HTMLElement, properties, options) { + // $ExpectType Animation + this; + // $ExpectType HTMLElement + element; + // $ExpectType PlainObject + properties; + // $ExpectType EffectsOptions + options; + // $ExpectType any + options.removeAfter; + + if (options.removeAfter) { + this.done(() => { + $(element).remove(); + }); + } + }); + + $("#element").hide({ + duration: 500, + removeAfter: true, + complete() { + // 0, because the prefilter done happens first! + console.log($(this).parent().length); + } + }); + } + } + + function tweener() { + // $ExpectType void + $.Animation.tweener('*', function(propName, finalValue) { + // $ExpectType Animation + this; + // $ExpectType string + propName; + // $ExpectType number + finalValue; + + return this.createTween(propName, finalValue); + }); + } +} + +function JQuery_Animation() { + const animation = $.Animation({} as Element, {}, {}); + + animation.done((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType true | undefined + jumpedToEnd; + }); + + animation.fail((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType false + jumpedToEnd; + }); + + animation.always((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType boolean | undefined + jumpedToEnd; + }); + + animation.progress((anim, progress, remainingMs) => { + // $ExpectType Animation + anim; + // $ExpectType number + progress; + // $ExpectType number + remainingMs; + }); +} + +function JQuery_TweenStatic() { + function propHooks() { + $.Tween.propHooks['myProp'] = { + get(tween) { + // $ExpectType Tween + tween; + + return tween.elem[tween.prop as keyof typeof tween.elem]; + }, + set(tween) { + // $ExpectType Tween + tween; + }, + }; + + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + $.Tween.propHooks['myProp'] = 1; + } + + function call_signature() { + // $ExpectType Tween + $.Tween({} as HTMLElement, {}, 'myProp', 1, 'myEasing', 'myUnit'); + + // $ExpectType Tween + $.Tween({} as HTMLElement, {}, 'myProp', 1, 'myEasing'); + + // $ExpectType Tween + $.Tween({} as HTMLElement, {}, 'myProp', 1); + } +} + +function JQuery_Easings() { + jQuery.easing.easeInCubic = (p) => { + return Math.pow(p, 3); + }; +} + function JQuery_Effects() { function interval() { // $ExpectType number @@ -7834,80 +8049,39 @@ function JQuery_Effects() { // $ExpectType PlainObject> $.fx.step; } -} -function JQuery_EffectsOptions() { - $('p').show({ - always(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - complete() { - // $ExpectType HTMLElement - this; - }, - done(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - duration: 5000, - easing: 'linear', - fail(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - progress(animation, progress, remainingMs) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType number - progress; - // $ExpectType number - remainingMs; - }, - queue: true, - specialEasing: { - width: 'linear', - height: 'easeOutBounce' - }, - start(animation) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - }, - step(now, tween) { - // $ExpectType HTMLElement - this; - // $ExpectType number - now; - // $ExpectType Tween - tween; + function stop() { + // $ExpectType () => void + $.fx.stop; + + function override() { + let animating: boolean; + + jQuery.fx.stop = () => { + animating = false; + }; } - }); -} + } -function JQuery_Easings() { - jQuery.easing.easeInCubic = (p: number, t: number, b: number, c: number, d: number) => { - return c * (t /= d) * t * t + b; - }; + function timer() { + // $ExpectType (tickFunction: TickFunction) => void + $.fx.timer; - jQuery.easing.easeInCubic = (p: number) => { - return Math.pow(p, 3); - }; + function override() { + let animating: boolean; + const raf: () => void = {} as any; + + jQuery.fx.timer = (timer) => { + // $ExpectType TickFunction + timer; + + if (timer() && jQuery.timers.push(timer) && !animating) { + animating = true; + raf(); + } + }; + } + } } function JQuery_Event() { diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index ef52084da5..338ae7c8ba 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -7,7 +7,7 @@ interface JQuery { } interface GreenifyPlugin { - (this: JQuery): void; + (this: JQuery): void; } jQuery.fn.greenify = function() { @@ -15,3 +15,63 @@ jQuery.fn.greenify = function() { }; jQuery("a").greenify(); // Makes all the links green. + +// https://learn.jquery.com/events/event-extensions/ + +// Events + +function fixHooks() { + function setHook() { + jQuery.event.fixHooks.drop = { + props: ["dataTransfer"] + }; + } + + function conflictResolution() { + if (jQuery.event.fixHooks.drop) { + throw new Error("Someone else took the jQuery.event.fixHooks.drop hook!"); + } + + jQuery.event.fixHooks.drop = { + props: ["dataTransfer"] + }; + } +} + +function special() { + function defineSpecialEvent() { + jQuery.event.special.pushy = { + bindType: "click", + delegateType: "click" + }; + } + + function handleObj() { + jQuery.event.special.multiclick = { + delegateType: "click", + bindType: "click", + handle(event) { + const handleObj = event.handleObj; + const targetData = jQuery.data(event.target); + let ret = null; + + // If a multiple of the click count, run the handler + targetData.clicks = (targetData.clicks || 0) + 1; + + if (targetData.clicks % event.data.clicks === 0) { + event.type = handleObj.origType; + ret = handleObj.handler.apply(this, arguments); + event.type = handleObj.type; + return ret; + } + } + }; + + // Sample usage + $("p").on("multiclick", { + clicks: 3 + }, () => { + alert("clicked 3 times"); + }); + } +} diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index 7092de2d06..cc164360c0 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -1857,7 +1857,9 @@ interface JQuery { tabs(): JQuery; tabs(methodName: 'destroy'): void; tabs(methodName: 'disable'): void; + tabs(methodName: 'disable', index: number): void; tabs(methodName: 'enable'): void; + tabs(methodName: 'enable', index: number): void; tabs(methodName: 'load', index: number): void; tabs(methodName: 'refresh'): void; tabs(methodName: 'widget'): JQuery; diff --git a/types/jschannel/index.d.ts b/types/jschannel/index.d.ts index 42145531ea..ba1ce6f61d 100644 --- a/types/jschannel/index.d.ts +++ b/types/jschannel/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for jschannel 1.0 // Project: https://github.com/yochannah/jschannel // Definitions by: Yitzchok Gottlieb +// McFlat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -25,7 +26,7 @@ export interface Message { } export interface ChannelConfiguration { - window: any; + window: Window; origin: string; scope: string; debugOutput?: boolean; diff --git a/types/jschannel/jschannel-tests.ts b/types/jschannel/jschannel-tests.ts index eabd150bf2..c618eea253 100644 --- a/types/jschannel/jschannel-tests.ts +++ b/types/jschannel/jschannel-tests.ts @@ -1,3 +1,3 @@ import { build } from 'jschannel'; -build({ window: null, origin: "*", scope: "testScope"}); +build({ window, origin: "*", scope: "testScope"}); diff --git a/types/jschannel/tsconfig.json b/types/jschannel/tsconfig.json index 58b8ca059e..e8988e8fe1 100644 --- a/types/jschannel/tsconfig.json +++ b/types/jschannel/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +21,4 @@ "index.d.ts", "jschannel-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index 3b1f082eb2..43829466b8 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -2,9 +2,19 @@ "extends": "dtslint/dt.json", "rules": { // TODOs + "array-type": false, "ban-types": false, + "eofline": false, + "max-line-length": false, "no-any-union": false, + "no-empty-interface": false, + "no-redundant-undefined": false, "no-unnecessary-class": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "semicolon": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false, + "whitespace": false } } diff --git a/types/json2csv/tslint.json b/types/json2csv/tslint.json index 3db14f85ea..389fc5f08e 100644 --- a/types/json2csv/tslint.json +++ b/types/json2csv/tslint.json @@ -1 +1,15 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "ban-types": false, + "callable-types": false, + "jsdoc-format": false, + "member-access": false, + "no-duplicate-imports": false, + "no-redundant-jsdoc-2": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false + } +} diff --git a/types/koa-pino-logger/index.d.ts b/types/koa-pino-logger/index.d.ts index 0994e7584a..24f59b8925 100644 --- a/types/koa-pino-logger/index.d.ts +++ b/types/koa-pino-logger/index.d.ts @@ -26,3 +26,9 @@ declare namespace logger { stream?: stream.Writable | stream.Duplex | stream.Transform; } } + +declare module 'koa' { + interface Context { + log: Logger; + } +} diff --git a/types/koa-pino-logger/koa-pino-logger-tests.ts b/types/koa-pino-logger/koa-pino-logger-tests.ts index bec6f887d2..5315ee5baa 100644 --- a/types/koa-pino-logger/koa-pino-logger-tests.ts +++ b/types/koa-pino-logger/koa-pino-logger-tests.ts @@ -3,3 +3,8 @@ import logger = require('koa-pino-logger'); const app = new koa(); app.use(logger()); + +app.use((ctx) => { + ctx.log.info('something else'); + ctx.body = 'hello world'; +}); diff --git a/types/leaflet-polylinedecorator/index.d.ts b/types/leaflet-polylinedecorator/index.d.ts index b3603e9f29..b66fbc58cc 100644 --- a/types/leaflet-polylinedecorator/index.d.ts +++ b/types/leaflet-polylinedecorator/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for leaflet-polylinedecorator 1.1 // Project: https://github.com/bbecquet/Leaflet.PolylineDecorator#readme // Definitions by: Viktor Soucek +// Michael Faisst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -45,9 +46,9 @@ declare module 'leaflet' { } interface Pattern { - offset?: number; - endOffset?: number; - repeat: number; + offset?: number | string; + endOffset?: number | string; + repeat: number | string; symbol: Symbol.Dash | Symbol.ArrowHead | Symbol.Marker; } diff --git a/types/leaflet-polylinedecorator/leaflet-polylinedecorator-tests.ts b/types/leaflet-polylinedecorator/leaflet-polylinedecorator-tests.ts index 7a9c5ee946..66a02cd376 100644 --- a/types/leaflet-polylinedecorator/leaflet-polylinedecorator-tests.ts +++ b/types/leaflet-polylinedecorator/leaflet-polylinedecorator-tests.ts @@ -53,3 +53,44 @@ L.polylineDecorator(polyline, { })} ] }).addTo(map); + +L.polylineDecorator(polyline, { + patterns: [ + { + offset: "10%", + repeat: 0, + symbol: L.Symbol.arrowHead({ + polygon: true, + headAngle: 45, + pixelSize: 12, + pathOptions: {} + })} + ] +}).addTo(map); + +L.polylineDecorator(polyline, { + patterns: [ + { + endOffset: "20%", + repeat: 0, + symbol: L.Symbol.arrowHead({ + polygon: true, + headAngle: 45, + pixelSize: 12, + pathOptions: {} + })} + ] +}).addTo(map); + +L.polylineDecorator(polyline, { + patterns: [ + { + repeat: "5%", + symbol: L.Symbol.arrowHead({ + polygon: true, + headAngle: 45, + pixelSize: 12, + pathOptions: {} + })} + ] +}).addTo(map); diff --git a/types/ltx/tslint.json b/types/ltx/tslint.json index 3db14f85ea..5bb1e8735d 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1 +1,9 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "jsdoc-format": false, + "no-consecutive-blank-lines": false, + "strict-export-declare-modifiers": false + } +} diff --git a/types/markdown-it-anchor/index.d.ts b/types/markdown-it-anchor/index.d.ts index 045082abf1..fc4cead6d4 100644 --- a/types/markdown-it-anchor/index.d.ts +++ b/types/markdown-it-anchor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/valeriangalliat/markdown-it-anchor // Definitions by: Josh Toft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { MarkdownIt, Core, Token } from 'markdown-it'; diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts index f2d3722a3d..b0913972fa 100644 --- a/types/markdown-it-container/index.d.ts +++ b/types/markdown-it-container/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/markdown-it/markdown-it-container // Definitions by: Vyacheslav Demot // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { MarkdownIt, Token, Renderer } from 'markdown-it'; diff --git a/types/markdown-it-lazy-headers/index.d.ts b/types/markdown-it-lazy-headers/index.d.ts index 9eb8a54cf1..0579118f80 100644 --- a/types/markdown-it-lazy-headers/index.d.ts +++ b/types/markdown-it-lazy-headers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Galadirith/markdown-it-lazy-headers // Definitions by: Knom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { MarkdownIt } from 'markdown-it'; diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 24513c3e56..0948a6d353 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/markdown-it/markdown-it // Definitions by: York Yao , Robert Coie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 interface MarkdownItStatic { new (): MarkdownIt.MarkdownIt; @@ -22,7 +23,19 @@ declare module MarkdownIt { renderInline(md: string, env?: any): string; parse(src: string, env: any): Token[]; parseInline(src: string, env: any): Token[]; - use(plugin: any, ...params: any[]): MarkdownIt; + + /* + // 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; @@ -40,6 +53,7 @@ declare module MarkdownIt { 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; @@ -74,6 +88,7 @@ declare module MarkdownIt { 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; @@ -96,24 +111,30 @@ declare module MarkdownIt { type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; - interface Rule { - (state: any, silent?: boolean): void; + interface Rule { + (state: S, silent?: boolean): boolean | void; } - 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; + 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; + 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: Ruler; + ruler: RulerBlock; } interface Core { @@ -123,7 +144,95 @@ declare module MarkdownIt { interface ParserInline { parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: Ruler; - ruler2: Ruler; + 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/mozilla-readability/index.d.ts b/types/mozilla-readability/index.d.ts index a30925fb0b..7a7c26fdb8 100644 --- a/types/mozilla-readability/index.d.ts +++ b/types/mozilla-readability/index.d.ts @@ -7,21 +7,13 @@ export = Readability; declare class Readability { - constructor(uri: Readability.Uri, doc: Document, options?: Readability.Options); + constructor(doc: Document, options?: Readability.Options); parse(): Readability.ParseResult; isProbablyReaderable(helperIsVisible?: (node: any) => boolean): boolean; } declare namespace Readability { - interface Uri { - spec: string; - host: string; - prePath: string; - scheme: string; - pathBase: string; - } - interface Options { debug?: boolean; maxElemsToParse?: number; @@ -31,7 +23,6 @@ declare namespace Readability { } interface ParseResult { - uri: Uri; title: string; byline: string; dir: string; diff --git a/types/mozilla-readability/mozilla-readability-tests.ts b/types/mozilla-readability/mozilla-readability-tests.ts index e5431dd14e..0dec719559 100644 --- a/types/mozilla-readability/mozilla-readability-tests.ts +++ b/types/mozilla-readability/mozilla-readability-tests.ts @@ -5,42 +5,25 @@ import { JSDOM } from 'jsdom'; // because issue https://github.com/mozilla/readability/issues/346 // requires global variable `Node` when using nodejs. -const fakeUri: Readability.Uri = { - spec: "http://fakehost/test/page.html", - host: "fakehost", - prePath: "http://fakehost", - scheme: "http", - pathBase: "http://fakehost/test/" -}; - function test_basic_usage() { const dom = new JSDOM(`

Hello

Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; - const reader = new Readability(fakeUri, dom.window.document); + const reader = new Readability(dom.window.document); const article = reader.parse(); } function test_readability_with_options() { const dom = new JSDOM(`

Hello

Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; const options: Readability.Options = { debug: true, maxElemsToParse: 100, }; - const article = new Readability(fakeUri, dom.window.document, options).parse(); + const article = new Readability(dom.window.document, options).parse(); } function test_is_probably_readerable() { const dom = new JSDOM(`

Hello

Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; - const isReadable = new Readability(fakeUri, dom.window.document).isProbablyReaderable(); + const isReadable = new Readability(dom.window.document).isProbablyReaderable(); } diff --git a/types/mutexify/index.d.ts b/types/mutexify/index.d.ts new file mode 100644 index 0000000000..4fa1dffe2a --- /dev/null +++ b/types/mutexify/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for mutexify 1.2 +// Project: https://github.com/mafintosh/mutexify +// Definitions by: Gustav Bylund +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Lock { + (fn: Release): number; + locked: boolean; +} + +type Release = ( + cb: (err?: any, value?: any) => any, + err: any, + value: any +) => void; + +declare function mutexify(): Lock; + +export = mutexify; +export as namespace mutexify; diff --git a/types/mutexify/mutexify-tests.ts b/types/mutexify/mutexify-tests.ts new file mode 100644 index 0000000000..dc921cb246 --- /dev/null +++ b/types/mutexify/mutexify-tests.ts @@ -0,0 +1,6 @@ +import mutexify = require("mutexify"); +const lock = mutexify(); + +lock(release => { + release(); +}); diff --git a/types/mutexify/tsconfig.json b/types/mutexify/tsconfig.json new file mode 100644 index 0000000000..4c1ee302d0 --- /dev/null +++ b/types/mutexify/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mutexify-tests.ts"] +} diff --git a/types/mutexify/tslint.json b/types/mutexify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mutexify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/newrelic/index.d.ts b/types/newrelic/index.d.ts index f6c54f5a4b..0c674e4646 100644 --- a/types/newrelic/index.d.ts +++ b/types/newrelic/index.d.ts @@ -4,348 +4,343 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // https://docs.newrelic.com/docs/agents/nodejs-agent/api-guides/nodejs-agent-api -declare namespace newrelic { - interface NewRelicAPI { - /** - * Give the current transaction a custom name. - * - * Overrides any New Relic naming rules set in configuration or from New Relic's servers. - * - * IMPORTANT: this function must be called when a transaction is active. New - * Relic transactions are tied to web requests, so this method may be called - * from within HTTP or HTTPS listener functions, Express routes, or other - * contexts where a web request or response object are in scope. - * - * The `name` will be prefixed with 'Custom/' when sent. - */ - setTransactionName(name: string): void; - /** - * Returns a handle on the currently executing transaction. - * - * This handle can then be used to end or ignore a given transaction safely from any context. - * It is best used with newrelic.startWebTransaction() and newrelic.startBackgroundTransaction(). - */ - getTransaction(): TransactionHandle; +/** + * Give the current transaction a custom name. + * + * Overrides any New Relic naming rules set in configuration or from New Relic's servers. + * + * IMPORTANT: this function must be called when a transaction is active. New + * Relic transactions are tied to web requests, so this method may be called + * from within HTTP or HTTPS listener functions, Express routes, or other + * contexts where a web request or response object are in scope. + * + * The `name` will be prefixed with 'Custom/' when sent. + */ +export function setTransactionName(name: string): void; - /** - * Specify the `Dispatcher` and `Dispatcher Version` environment values. - * - * A dispatcher is typically the service responsible for brokering - * the request with the process responsible for responding to the - * request. For example Node's `http` module would be the dispatcher - * for incoming HTTP requests. - */ - setDispatcher(name: string, version?: string): void; +/** + * Returns a handle on the currently executing transaction. + * + * This handle can then be used to end or ignore a given transaction safely from any context. + * It is best used with newrelic.startWebTransaction() and newrelic.startBackgroundTransaction(). + */ +export function getTransaction(): TransactionHandle; - /** - * Give the current transaction a name based on your own idea of what - * constitutes a controller in your Node application. Also allows you to - * optionally specify the action being invoked on the controller. If the action - * is omitted, then the API will default to using the HTTP method used in the - * request (e.g. GET, POST, DELETE). Overrides any New Relic naming rules set - * in configuration or from New Relic's servers. - * - * IMPORTANT: this function must be called when a transaction is active. New - * Relic transactions are tied to web requests, so this method may be called - * from within HTTP or HTTPS listener functions, Express routes, or other - * contexts where a web request or response object are in scope. - * - * The `name` will be prefixed with 'Controller/' when sent. - * The `action` defaults to the HTTP method used for the request. - */ - setControllerName(name: string, action: string): void; +/** + * Specify the `Dispatcher` and `Dispatcher Version` environment values. + * + * A dispatcher is typically the service responsible for brokering + * the request with the process responsible for responding to the + * request. For example Node's `http` module would be the dispatcher + * for incoming HTTP requests. + */ +export function setDispatcher(name: string, version?: string): void; - /** - * Add a custom attribute to the current transaction. - * - * Some attributes are reserved (see CUSTOM_BLACKLIST in the docs for the current, very short list), and - * as with most API methods, this must be called in the context of an - * active transaction. - * - * Most recently set value wins. - */ - addCustomAttribute(key: string, value: string): void; +/** + * Give the current transaction a name based on your own idea of what + * constitutes a controller in your Node application. Also allows you to + * optionally specify the action being invoked on the controller. If the action + * is omitted, then the API will default to using the HTTP method used in the + * request (e.g. GET, POST, DELETE). Overrides any New Relic naming rules set + * in configuration or from New Relic's servers. + * + * IMPORTANT: this function must be called when a transaction is active. New + * Relic transactions are tied to web requests, so this method may be called + * from within HTTP or HTTPS listener functions, Express routes, or other + * contexts where a web request or response object are in scope. + * + * The `name` will be prefixed with 'Controller/' when sent. + * The `action` defaults to the HTTP method used for the request. + */ +export function setControllerName(name: string, action: string): void; - /** - * Adds all custom attributes in an object to the current transaction. - * - * See documentation for `addCustomAttribute` for more information on setting custom attributes. - */ - addCustomAttributes(atts: { [key: string]: string }): void; +/** + * Add a custom attribute to the current transaction. + * + * Some attributes are reserved (see CUSTOM_BLACKLIST in the docs for the current, very short list), and + * as with most API methods, this must be called in the context of an + * active transaction. + * + * Most recently set value wins. + */ +export function addCustomAttribute(key: string, value: string): void; - /** - * Tell the tracer whether to ignore the current transaction. - * - * The most common use for this will be to mark a transaction as ignored (maybe it's handling - * a websocket polling channel, or maybe it's an external call you don't care - * is slow), but it's also useful when you want a transaction that would - * otherwise be ignored due to URL or transaction name normalization rules - * to *not* be ignored. - */ - setIgnoreTransaction(ignored: boolean): void; +/** + * Adds all custom attributes in an object to the current transaction. + * + * See documentation for `addCustomAttribute` for more information on setting custom attributes. + */ +export function addCustomAttributes(atts: { [key: string]: string }): void; - /** - * Send errors to New Relic that you've already handled yourself. - * - * NOTE: Errors that are recorded using this method do _not_ obey the `ignore_status_codes` configuration. - * - * Optional. Any custom attributes to be displayed in the New Relic UI. - */ - noticeError(error: Error, customAttributes?: { [key: string]: string }): void; +/** + * Tell the tracer whether to ignore the current transaction. + * + * The most common use for this will be to mark a transaction as ignored (maybe it's handling + * a websocket polling channel, or maybe it's an external call you don't care + * is slow), but it's also useful when you want a transaction that would + * otherwise be ignored due to URL or transaction name normalization rules + * to *not* be ignored. + */ +export function setIgnoreTransaction(ignored: boolean): void; - /** - * If the URL for a transaction matches the provided pattern, name the - * transaction with the provided name. - * - * If there are capture groups in the pattern (which is a standard JavaScript regular expression, - * and can be passed as either a RegExp or a string), then the substring matches ($1, $2, - * etc.) are replaced in the name string. BE CAREFUL WHEN USING SUBSTITUTION. - * If the replacement substrings are highly variable (i.e. are identifiers, - * GUIDs, or timestamps), the rule will generate too many metrics and - * potentially get your application blacklisted by New Relic. - * - * An example of a good rule with replacements: - * - * newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)', 'CommerceAPI/$1/$2') - * - * An example of a bad rule with replacements: - * - * newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1') - * - * Keep in mind that the original URL and any query parameters will be sent - * along with the request, so slow transactions will still be identifiable. - * - * Naming rules can not be removed once added. They can also be added via the - * agent's configuration. See configuration documentation for details. - */ - addNamingRule(pattern: RegExp | string, name: string): void; +/** + * Send errors to New Relic that you've already handled yourself. + * + * NOTE: Errors that are recorded using this method do _not_ obey the `ignore_status_codes` configuration. + * + * Optional. Any custom attributes to be displayed in the New Relic UI. + */ +export function noticeError(error: Error, customAttributes?: { [key: string]: string }): void; - /** - * If the URL for a transaction matches the provided pattern, ignore the transaction attached to that URL. - * - * Useful for filtering socket.io connections and other long-polling requests out of your agents to keep - * them from distorting an app's apdex or mean response time. - * - * Example: - * - * newrelic.addIgnoringRule('^/socket\\.io/') - */ - addIgnoringRule(pattern: RegExp | string): void; +/** + * If the URL for a transaction matches the provided pattern, name the + * transaction with the provided name. + * + * If there are capture groups in the pattern (which is a standard JavaScript regular expression, + * and can be passed as either a RegExp or a string), then the substring matches ($1, $2, + * etc.) are replaced in the name string. BE CAREFUL WHEN USING SUBSTITUTION. + * If the replacement substrings are highly variable (i.e. are identifiers, + * GUIDs, or timestamps), the rule will generate too many metrics and + * potentially get your application blacklisted by New Relic. + * + * An example of a good rule with replacements: + * + * newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)', 'CommerceAPI/$1/$2') + * + * An example of a bad rule with replacements: + * + * newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1') + * + * Keep in mind that the original URL and any query parameters will be sent + * along with the request, so slow transactions will still be identifiable. + * + * Naming rules can not be removed once added. They can also be added via the + * agent's configuration. See configuration documentation for details. + */ +export function addNamingRule(pattern: RegExp | string, name: string): void; - /** - * Get the header necessary for Browser Monitoring. - * - * This script must be manually injected into your templates, as high as possible - * in the header, but _after_ any X-UA-COMPATIBLE HTTP-EQUIV meta tags. - * Otherwise you may hurt IE! - * - * This method must be called _during_ a transaction, and must be called every - * time you want to generate the headers. - * - * Do *not* reuse the headers between users, or even between requests. - */ - getBrowserTimingHeader(): string; +/** + * If the URL for a transaction matches the provided pattern, ignore the transaction attached to that URL. + * + * Useful for filtering socket.io connections and other long-polling requests out of your agents to keep + * them from distorting an app's apdex or mean response time. + * + * Example: + * + * newrelic.addIgnoringRule('^/socket\\.io/') + */ +export function addIgnoringRule(pattern: RegExp | string): void; - /** - * Instrument a particular method to improve visibility into a transaction, - * or optionally turn it into a metric. - * - * The name defines a name for the segment. This name will be visible in transaction traces and - * as a new metric in the New Relic UI. - * The record flag defines whether the segment should be recorded as a metric. - * The handler is the function you want to track as a segment. - * The optional callback is a function passed to the handler to fire after its work is done. - * - * The agent begins timing the segment when startSegment is called. - * The segment is ended when either the handler finishes executing, or callback is fired, if it is provided. - * If a promise is returned from the handler, the segment's ending will be tied to that promise resolving or rejecting. - */ - startSegment>(name: string, record: boolean, handler: T): T; - startSegment any>(name: string, record: boolean, handler: (cb?: C) => T, callback?: C): T; +/** + * Get the header necessary for Browser Monitoring. + * + * This script must be manually injected into your templates, as high as possible + * in the header, but _after_ any X-UA-COMPATIBLE HTTP-EQUIV meta tags. + * Otherwise you may hurt IE! + * + * This method must be called _during_ a transaction, and must be called every + * time you want to generate the headers. + * + * Do *not* reuse the headers between users, or even between requests. + */ +export function getBrowserTimingHeader(): string; - /** - * Instrument a particular callback to improve visibility into a transaction. - * - * Use this API call to improve instrumentation of a particular method, or to track work across asynchronous - * boundaries by calling createTracer() in both the target function and its parent asynchronous function. - * - * The name will be visible in transaction traces and as a new metric in the New Relic UI. - * - * The agent begins timing the segment when createTracer is called, and ends the segment when the callback - * defined by the callback argument finishes executing. - * - * @deprecated - * This method has been deprecated in favor of newrelic.startSegment() - */ - createTracer any>(name: string, handle: T): T; +/** + * Instrument a particular method to improve visibility into a transaction, + * or optionally turn it into a metric. + * + * The name defines a name for the segment. This name will be visible in transaction traces and + * as a new metric in the New Relic UI. + * The record flag defines whether the segment should be recorded as a metric. + * The handler is the function you want to track as a segment. + * The optional callback is a function passed to the handler to fire after its work is done. + * + * The agent begins timing the segment when startSegment is called. + * The segment is ended when either the handler finishes executing, or callback is fired, if it is provided. + * If a promise is returned from the handler, the segment's ending will be tied to that promise resolving or rejecting. + */ +export function startSegment>(name: string, record: boolean, handler: T): T; +export function startSegment any>(name: string, record: boolean, handler: (cb?: C) => T, callback?: C): T; - /** - * Creates and starts a web transaction to record work done in the handle supplied. - * - * This transaction will run until the handle - * synchronously returns UNLESS: - * 1. The handle function returns a promise, where the end of the - * transaction will be tied to the end of the promise returned. - * 2. `getTransaction` is called in the handle, flagging the - * transaction as externally handled. In this case the transaction - * will be ended when `TransactionHandle#end` is called in the user's code. - * - * @example - * var newrelic = require('newrelic') - * newrelic.startWebTransaction('/some/url/path', function() { - * var transaction = newrelic.getTransaction() - * setTimeout(function() { - * // do some work - * transaction.end() - * }, 100) - * }) - * - * The `url` is used to name and group related transactions in APM, - * so it should be a generic name and not include any variable parameters. - */ - startWebTransaction(url: string, handle: (...args: any[]) => any): any; +/** + * Instrument a particular callback to improve visibility into a transaction. + * + * Use this API call to improve instrumentation of a particular method, or to track work across asynchronous + * boundaries by calling createTracer() in both the target function and its parent asynchronous function. + * + * The name will be visible in transaction traces and as a new metric in the New Relic UI. + * + * The agent begins timing the segment when createTracer is called, and ends the segment when the callback + * defined by the callback argument finishes executing. + * + * @deprecated + * This method has been deprecated in favor of newrelic.startSegment() + */ +export function createTracer any>(name: string, handle: T): T; - /** - * Creates and starts a background transaction to record work done in the handle supplied. - * - * This transaction will run until the handle - * synchronously returns UNLESS: - * 1. The handle function returns a promise, where the end of the - * transaction will be tied to the end of the promise returned. - * 2. `API#getTransaction` is called in the handle, flagging the - * transaction as externally handled. In this case the transaction - * will be ended when `TransactionHandle#end` is called in the user's code. - * - * @example - * var newrelic = require('newrelic') - * newrelic.startBackgroundTransaction('Red October', 'Subs', function() { - * var transaction = newrelic.getTransaction() - * setTimeout(function() { - * // do some work - * transaction.end() - * }, 100) - * }) - * - * The `url` is used to name and group related transactions in APM, - * so it should be a generic name and not include any variable parameters. - * - * The optional `group can be used for grouping background transactions in APM. - * For more information see: - * https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown - */ - startBackgroundTransaction(name: string, handle: (...args: any[]) => any): any; - startBackgroundTransaction(name: string, group: string, handle: (...args: any[]) => any): any; +/** + * Creates and starts a web transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startWebTransaction('/some/url/path', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + */ +export function startWebTransaction(url: string, handle: (...args: any[]) => any): any; - /** - * End the current web or background custom transaction. - * - * This method requires being in the correct transaction context when called. - */ - endTransaction(): void; +/** + * Creates and starts a background transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `API#getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startBackgroundTransaction('Red October', 'Subs', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + * + * The optional `group can be used for grouping background transactions in APM. + * For more information see: + * https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown + */ +export function startBackgroundTransaction(name: string, handle: (...args: any[]) => any): any; +export function startBackgroundTransaction(name: string, group: string, handle: (...args: any[]) => any): any; - /** - * Record an event-based metric, usually associated with a particular duration. - * - * The `name` must be a string following standard metric naming rules. The `value` will - * usually be a number, but it can also be an object. - * * When `value` is a numeric value, it should represent the magnitude of a measurement - * associated with an event; for example, the duration for a particular method call. - * * When `value` is an object, it must contain count, total, min, max, and sumOfSquares - * keys, all with number values. This form is useful to aggregate metrics on your own - * and report them periodically; for example, from a setInterval. These values will - * be aggregated with any previously collected values for the same metric. The names - * of these keys match the names of the keys used by the platform API. - */ - recordMetric(name: string, value: number | Metric): void; +/** + * End the current web or background custom transaction. + * + * This method requires being in the correct transaction context when called. + */ +export function endTransaction(): void; - /** - * Update a metric that acts as a simple counter. - * - * The count of the selected metric will be incremented by the specified amount, defaulting to 1. - */ - incrementMetric(name: string, value?: number): void; +/** + * Record an event-based metric, usually associated with a particular duration. + * + * The `name` must be a string following standard metric naming rules. The `value` will + * usually be a number, but it can also be an object. + * * When `value` is a numeric value, it should represent the magnitude of a measurement + * associated with an event; for example, the duration for a particular method call. + * * When `value` is an object, it must contain count, total, min, max, and sumOfSquares + * keys, all with number values. This form is useful to aggregate metrics on your own + * and report them periodically; for example, from a setInterval. These values will + * be aggregated with any previously collected values for the same metric. The names + * of these keys match the names of the keys used by the platform API. + */ +export function recordMetric(name: string, value: number | Metric): void; - /** - * Record an event-based metric, usually associated with a particular duration. - * - * `eventType` must be an alphanumeric string less than 255 characters. - * The keys of `attributes` must be shorter than 255 characters. - */ - recordCustomEvent(eventType: string, attributes: { [keys: string]: boolean | number | string }): void; +/** + * Update a metric that acts as a simple counter. + * + * The count of the selected metric will be incremented by the specified amount, defaulting to 1. + */ +export function incrementMetric(name: string, value?: number): void; - /** - * Registers an instrumentation function. - * - * The provided onRequire callback will be fired when the given module is loaded with require. - * The moduleName parameter should be the string that will be passed to require; - * for example, 'express' or 'amqplib/callback_api'. - * - * The optional onError callback is called if the onRequire parameters throws an error. - * This is useful for debugging your instrumentation. - * - * Use this method to: - * - Add instrumentation for modules not currently instrumented by New Relic. - * - Instrument your own code. - * - Replace the Node.js agent's built-in instrumentation with your own. - */ - instrument: Instrument; +/** + * Record an event-based metric, usually associated with a particular duration. + * + * `eventType` must be an alphanumeric string less than 255 characters. + * The keys of `attributes` must be shorter than 255 characters. + */ +export function recordCustomEvent(eventType: string, attributes: { [keys: string]: boolean | number | string }): void; - /** - * Sets an instrumentation callback for a datastore module. - * - * This method is just like `instrument`, except it provides a datastore-service-specialized shim. - */ - instrumentDatastore: Instrument; +/** + * Registers an instrumentation function. + * + * The provided onRequire callback will be fired when the given module is loaded with require. + * The moduleName parameter should be the string that will be passed to require; + * for example, 'express' or 'amqplib/callback_api'. + * + * The optional onError callback is called if the onRequire parameters throws an error. + * This is useful for debugging your instrumentation. + * + * Use this method to: + * - Add instrumentation for modules not currently instrumented by New Relic. + * - Instrument your own code. + * - Replace the Node.js agent's built-in instrumentation with your own. + */ +export const instrument: Instrument; - /** - * Sets an instrumentation callback for a web framework module. - * - * This method is just like `instrument`, except it provides a web-framework-specialized shim. - */ - instrumentWebframework: Instrument; +/** + * Sets an instrumentation callback for a datastore module. + * + * This method is just like `instrument`, except it provides a datastore-service-specialized shim. + */ +export const instrumentDatastore: Instrument; - /** - * Sets an instrumentation callback for a message service client module. - * - * This method is just like `instrument`, except it provides a message-service-specialized shim. - */ - instrumentMessages: Instrument; +/** + * Sets an instrumentation callback for a web framework module. + * + * This method is just like `instrument`, except it provides a web-framework-specialized shim. + */ +export const instrumentWebframework: Instrument; - /** - * Gracefully shuts down the agent. - * - * If `collectPendingData` is true, the agent will send any pending data to the collector - * before shutting down. Defaults to `false`. - */ - shutdown(cb?: (error?: Error) => void): void; - shutdown(options?: { collectPendingData?: boolean, timeout?: number }, cb?: (error?: Error) => void): void; - } +/** + * Sets an instrumentation callback for a message service client module. + * + * This method is just like `instrument`, except it provides a message-service-specialized shim. + */ +export const instrumentMessages: Instrument; - interface Instrument { - (opts: { moduleName: string, onRequire: () => void, onError?: (err: Error) => void }): void; - (moduleName: string, onRequire: () => void, onError?: (err: Error) => void): void; - } +/** + * Gracefully shuts down the agent. + * + * If `collectPendingData` is true, the agent will send any pending data to the collector + * before shutting down. Defaults to `false`. + */ +export function shutdown(cb?: (error?: Error) => void): void; +export function shutdown(options?: { collectPendingData?: boolean, timeout?: number }, cb?: (error?: Error) => void): void; - interface Metric { - count: number; - total: number; - min: number; - max: number; - sumOfSquares: number; - } +export interface Instrument { + (opts: { moduleName: string, onRequire: () => void, onError?: (err: Error) => void }): void; + (moduleName: string, onRequire: () => void, onError?: (err: Error) => void): void; +} - interface TransactionHandle { - /** - * End the transaction. - */ - end(callback?: () => any): void; +export interface Metric { + count: number; + total: number; + min: number; + max: number; + sumOfSquares: number; +} - /** - * Mark the transaction to be ignored. - */ - ignore(): void; - } +export interface TransactionHandle { + /** + * End the transaction. + */ + end(callback?: () => any): void; + + /** + * Mark the transaction to be ignored. + */ + ignore(): void; } -declare const api: newrelic.NewRelicAPI; -export = api; diff --git a/types/next/constants.d.ts b/types/next/constants.d.ts new file mode 100644 index 0000000000..d2dc74dad0 --- /dev/null +++ b/types/next/constants.d.ts @@ -0,0 +1,23 @@ +export const PHASE_EXPORT: string; +export const PHASE_PRODUCTION_BUILD: string; +export const PHASE_PRODUCTION_SERVER: string; +export const PHASE_DEVELOPMENT_SERVER: string; +export const PAGES_MANIFEST: string; +export const BUILD_MANIFEST: string; +export const REACT_LOADABLE_MANIFEST: string; +export const SERVER_DIRECTORY: string; +export const CONFIG_FILE: string; +export const BUILD_ID_FILE: string; +export const BLOCKED_PAGES: string[]; + +export const CLIENT_STATIC_FILES_PATH: string; +export const CLIENT_STATIC_FILES_RUNTIME: string; +export const CLIENT_STATIC_FILES_RUNTIME_PATH: string; +/** static/runtime/main.js */ +export const CLIENT_STATIC_FILES_RUNTIME_MAIN: string; +/** static/runtime/webpack.js */ +export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK: string; +/** matches static//pages/.js */ +export const IS_BUNDLED_PAGE_REGEX: RegExp; +/** matches static//pages/:page*.js */ +export const ROUTE_NAME_REGEX: RegExp; diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 3d238f6c6f..eed52766b3 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -37,7 +37,7 @@ export interface NextDocumentContext exte * https://github.com/zeit/next.js/blob/7.0.0/server/document.js#L16 */ export interface DefaultDocumentIProps extends RenderPageResponse { - styles?: Array>; + styles?: React.ReactNode; } /** @@ -104,5 +104,7 @@ export class NextScript extends React.Component {} export default class Document

extends React.Component< P & DefaultDocumentIProps & DocumentProps > { - static getInitialProps(context: NextDocumentContext): DefaultDocumentIProps | Promise; + static getInitialProps( + context: NextDocumentContext + ): DefaultDocumentIProps | Promise; } diff --git a/types/next/test/next-constants-tests.ts b/types/next/test/next-constants-tests.ts new file mode 100644 index 0000000000..64413ea97c --- /dev/null +++ b/types/next/test/next-constants-tests.ts @@ -0,0 +1,30 @@ +import { + PHASE_DEVELOPMENT_SERVER, + IS_BUNDLED_PAGE_REGEX +} from "next/constants"; + +const isIndexPage = IS_BUNDLED_PAGE_REGEX.test( + "static/CjW0mFnyG80HdP4eSUiy7/pages/index.js" +); + +// Example taken from: https://github.com/cyrilwanner/next-compose-plugins/blob/a25b313899638912cc9defc0be072f4fe4a1e855/README.md +const config = (nextConfig: any = {}) => { + return { + ...nextConfig, + + // define in which phases this plugin should get applied. + // you can also use multiple phases or negate them. + // however, users can still overwrite them in their configuration if they really want to. + phases: [PHASE_DEVELOPMENT_SERVER], + + webpack(config: any, options: any) { + // do something here which only gets applied during development server phase + + if (typeof nextConfig.webpack === "function") { + return nextConfig.webpack(config, options); + } + + return config; + } + }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index d25b340e64..6ba291be0d 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -12,6 +12,27 @@ interface WithUrlProps { url: string; } +class MyDocumentDefault extends Document { + static async getInitialProps(ctx: NextDocumentContext) { + const initialProps = await Document.getInitialProps(ctx); + return { ...initialProps }; + } + + render() { + return ( + + + + + +

+ + + + ); + } +} + class MyDoc extends Document { static getInitialProps({ req, renderPage }: NextDocumentContext) { // without callback diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json index 125953fcd6..9981affbd3 100644 --- a/types/next/tsconfig.json +++ b/types/next/tsconfig.json @@ -20,6 +20,7 @@ }, "files": [ "index.d.ts", + "constants.d.ts", "app.d.ts", "document.d.ts", "dynamic.d.ts", @@ -29,6 +30,7 @@ "router.d.ts", "config.d.ts", "test/next-tests.ts", + "test/next-constants-tests.ts", "test/next-app-tests.tsx", "test/next-error-tests.tsx", "test/next-head-tests.tsx", diff --git a/types/node-crate/index.d.ts b/types/node-crate/index.d.ts index 8fa75581e0..971c71db24 100644 --- a/types/node-crate/index.d.ts +++ b/types/node-crate/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for node-crate 2.0 -// Project: https://github.com/arobson/rabbot +// Project: https://github.com/megastef/node-crate // Definitions by: Greg Jednaszewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -30,6 +30,10 @@ declare namespace crate { * Creates a table with the given schema. */ create: (schema: object) => Promise; + /** + * Creates a table if it doesn't already exist. + */ + createIfNotExists: (schema: object) => Promise; /** * Drops a table. */ diff --git a/types/node-crate/node-crate-tests.ts b/types/node-crate/node-crate-tests.ts index d98f8c2694..117fdcbcdf 100644 --- a/types/node-crate/node-crate-tests.ts +++ b/types/node-crate/node-crate-tests.ts @@ -10,6 +10,8 @@ crate.insert('users', {id: 'test', password: 'password'}); crate.create({users: {id: 'string primary key', password: 'string'}}); +crate.createIfNotExists({users: {id: 'string primary key', password: 'string'}}); + crate.drop('users'); crate.update('users', {password: 'newPassword'}, "id = 'test'"); diff --git a/types/node-cron/index.d.ts b/types/node-cron/index.d.ts index 75ddaefdde..8c6b70ec1c 100644 --- a/types/node-cron/index.d.ts +++ b/types/node-cron/index.d.ts @@ -1,15 +1,28 @@ -// Type definitions for node-cron 1.2 -// Project: http://merencia.com/node-cron/ -// Definitions by: morsic +// Type definitions for node-cron 2.0 +// Project: https://github.com/node-cron/node-cron +// Definitions by: morsic , +// burtek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// immediateStart - default true -export function schedule(a: string, func: () => void, immediateStart?: boolean): ScheduledTask; +export function schedule(cronExpression: string, func: () => void, options?: ScheduleOptions): ScheduledTask; -export function validate(a: string): boolean; +export function validate(cronExpression: string): boolean; export interface ScheduledTask { start: () => this; stop: () => this; destroy: () => void; } + +export interface ScheduleOptions { + /** + * A boolean to set if the created task is scheduled. + * + * Defaults to `true` + */ + scheduled?: boolean; + /** + * The timezone that is used for job scheduling + */ + timezone?: string; +} diff --git a/types/node-cron/node-cron-tests.ts b/types/node-cron/node-cron-tests.ts index c670924d27..17350b6427 100644 --- a/types/node-cron/node-cron-tests.ts +++ b/types/node-cron/node-cron-tests.ts @@ -17,7 +17,7 @@ cron.schedule('1-5 * * * *', () => { const task = cron.schedule('* * * * *', () => { log('immediately started'); // because of manual call start method -}, false); +}, { scheduled: false }); task.start(); diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index e30a217ddc..99d3f5b45d 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -5,6 +5,7 @@ // Aakash Goenka // Rafal2228 // Beeno Tung +// Joe Flateau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -410,6 +411,26 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } + namespace pkcs7 { + interface PkcsSignedData { + content?: string | util.ByteBuffer; + contentInfo?: { value: any[] }; + + addCertificate(certificate: pki.Certificate): void; + addSigner(options: { + key: string; + certificate: pki.Certificate; + digestAlgorithm: string; + authenticatedAttributes: { type: string; value?: string }[]; + }): void; + sign(options?:{ + detached?: boolean + }): void; + toAsn1(): asn1.Asn1; + } + + function createSignedData(): PkcsSignedData; + } namespace md { diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 73558e4a8f..48d8340522 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 10.11 +// Type definitions for Node.js 10.12 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -493,6 +493,7 @@ declare namespace NodeJS { maxArrayLength?: number | null; breakLength?: number; compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); } interface ConsoleConstructor { @@ -691,6 +692,8 @@ declare namespace NodeJS { "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; type DisconnectListener = () => void; type ExitListener = (code: number) => void; @@ -702,6 +705,7 @@ declare namespace NodeJS { type SignalsListener = (signal: Signals) => void; type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; interface Socket extends ReadWriteStream { isTTY?: true; @@ -845,6 +849,7 @@ declare namespace NodeJS { addListener(event: Signals, listener: SignalsListener): this; addListener(event: "newListener", listener: NewListenerListener): this; addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; emit(event: "beforeExit", code: number): boolean; emit(event: "disconnect"): boolean; @@ -857,6 +862,7 @@ declare namespace NodeJS { emit(event: Signals, signal: Signals): boolean; emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: "beforeExit", listener: BeforeExitListener): this; on(event: "disconnect", listener: DisconnectListener): this; @@ -869,6 +875,7 @@ declare namespace NodeJS { on(event: Signals, listener: SignalsListener): this; on(event: "newListener", listener: NewListenerListener): this; on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; once(event: "beforeExit", listener: BeforeExitListener): this; once(event: "disconnect", listener: DisconnectListener): this; @@ -881,6 +888,7 @@ declare namespace NodeJS { once(event: Signals, listener: SignalsListener): this; once(event: "newListener", listener: NewListenerListener): this; once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; prependListener(event: "beforeExit", listener: BeforeExitListener): this; prependListener(event: "disconnect", listener: DisconnectListener): this; @@ -893,6 +901,7 @@ declare namespace NodeJS { prependListener(event: Signals, listener: SignalsListener): this; prependListener(event: "newListener", listener: NewListenerListener): this; prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; prependOnceListener(event: "disconnect", listener: DisconnectListener): this; @@ -905,6 +914,7 @@ declare namespace NodeJS { prependOnceListener(event: Signals, listener: SignalsListener): this; prependOnceListener(event: "newListener", listener: NewListenerListener): this; prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; listeners(event: "beforeExit"): BeforeExitListener[]; listeners(event: "disconnect"): DisconnectListener[]; @@ -917,6 +927,7 @@ declare namespace NodeJS { listeners(event: Signals): SignalsListener[]; listeners(event: "newListener"): NewListenerListener[]; listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; } interface Global { @@ -1006,6 +1017,7 @@ declare namespace NodeJS { class Module { static runMain(): void; static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; static builtinModules: string[]; static Module: typeof Module; @@ -2618,6 +2630,20 @@ declare module "url" { function domainToASCII(domain: string): string; function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + interface URLFormatOptions { auth?: boolean; fragment?: boolean; @@ -3994,12 +4020,25 @@ declare module "fs" { */ function rmdirSync(path: PathLike): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function mkdir(path: PathLike, mode: number | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + function mkdir(path: PathLike, mode: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. @@ -4014,7 +4053,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function __promisify__(path: PathLike, mode?: number | string | null): Promise; + function __promisify__(path: PathLike, mode?: number | string | MakeDirectoryOptions | null): Promise; } /** @@ -4022,7 +4061,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function mkdirSync(path: PathLike, mode?: number | string | null): void; + function mkdirSync(path: PathLike, mode?: number | string | MakeDirectoryOptions | null): void; /** * Asynchronously creates a unique temporary directory. @@ -6349,6 +6388,88 @@ declare module "crypto" { function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + ciper: string; + passphrase: string; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; } declare module "stream" { @@ -7665,6 +7786,7 @@ declare module "http2" { addListener(event: "localSettings", listener: (settings: Settings) => void): this; addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; @@ -7674,6 +7796,7 @@ declare module "http2" { emit(event: "localSettings", settings: Settings): boolean; emit(event: "remoteSettings", settings: Settings): boolean; emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; @@ -7683,6 +7806,7 @@ declare module "http2" { on(event: "localSettings", listener: (settings: Settings) => void): this; on(event: "remoteSettings", listener: (settings: Settings) => void): this; on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; @@ -7692,6 +7816,7 @@ declare module "http2" { once(event: "localSettings", listener: (settings: Settings) => void): this; once(event: "remoteSettings", listener: (settings: Settings) => void): this; once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; @@ -7701,6 +7826,7 @@ declare module "http2" { prependListener(event: "localSettings", listener: (settings: Settings) => void): this; prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; @@ -7710,6 +7836,7 @@ declare module "http2" { prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; } export interface ClientHttp2Session extends Http2Session { diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 15d139d2f0..f243aa649e 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -414,6 +414,19 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff const cf = util.promisify(fs.copyFile); cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); } + + { + fs.mkdir('some/test/path', { + recursive: true, + mode: 0o777, + }, () => { + }); + + fs.mkdirSync('some/test/path', { + recursive: true, + mode: 0o777, + }); + } } /////////////////////////////////////////////////////// @@ -763,6 +776,15 @@ function bufferTests() { ]); assert.equal(params.toString(), 'user=abc&query=first&query=second'); } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } } ///////////////////////////////////////////////////// @@ -781,7 +803,10 @@ function bufferTests() { showProxy: true, maxArrayLength: 10, breakLength: 20, - compact: true + compact: true, + sorted(a, b) { + return b.localeCompare(a); + }, }); util.inspect(["This is nice"], { colors: true, @@ -790,7 +815,8 @@ function bufferTests() { showProxy: true, maxArrayLength: null, breakLength: Infinity, - compact: false + compact: false, + sorted: true, }); assert(typeof util.inspect.custom === 'symbol'); @@ -1475,6 +1501,60 @@ async function asyncStreamPipelineFinished() { ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "compressed"); ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "hybrid"); } + + { + const rsaRes: { + publicKey: Buffer; + privateKey: string; + } = crypto.generateKeyPairSync('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + ciper: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const dsaRes: { + publicKey: string; + privateKey: Buffer; + } = crypto.generateKeyPairSync('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + ciper: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const ecRes: { + publicKey: string; + privateKey: string; + } = crypto.generateKeyPairSync('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + ciper: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + } } ////////////////////////////////////////////////// @@ -3087,6 +3167,7 @@ import * as p from "process"; process.prependOnceListener("SIGBREAK", () => { }); process.on("newListener", (event: string | symbol, listener: Function) => { }); process.once("removeListener", (event: string | symbol, listener: Function) => { }); + process.on("multipleResolves", (type: NodeJS.MultipleResolveType, prom: Promise, value: any) => {}); const listeners = process.listeners('uncaughtException'); const oldHandler = listeners[listeners.length - 1]; @@ -3863,6 +3944,7 @@ import * as constants from 'constants'; http2Session.on('remoteSettings', (settings: http2.Settings) => {}); http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); http2Session.on('timeout', () => {}); + http2Session.on('ping', () => {}); http2Session.destroy(); @@ -4440,6 +4522,7 @@ import * as constants from 'constants'; //////////////////////////////////////////////////// /// module tests : http://nodejs.org/api/modules.html //////////////////////////////////////////////////// +import moduleModule = require('module'); { require.extensions[".ts"] = () => ""; @@ -4452,6 +4535,8 @@ import * as constants from 'constants'; const b: string[] = Module.builtinModules; let paths: string[] = module.paths; paths = m1.paths; + + moduleModule.createRequireFromPath('./test')('test'); } //////////////////////////////////////////////////// diff --git a/types/oauth/index.d.ts b/types/oauth/index.d.ts index 21b74369e9..9f747e8b84 100644 --- a/types/oauth/index.d.ts +++ b/types/oauth/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for oauth 0.9 // Project: https://github.com/ciaranj/node-oauth#readme // Definitions by: nonAlgebraic +// Eduardo AC // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -25,8 +26,8 @@ export type oauth2tokenCallback = ( export type dataCallback = ( err: {statusCode: number, data?: any}, - result: string | Buffer, - response: IncomingMessage + result?: string | Buffer, + response?: IncomingMessage ) => any; export class OAuth { @@ -285,7 +286,7 @@ export class OAuth2 { get(url: string, access_token: string, - callback: string + callback: dataCallback ): void; protected _getAccessTokenUrl(): string; diff --git a/types/onoff/index.d.ts b/types/onoff/index.d.ts index 72c25d11f5..55701976a9 100644 --- a/types/onoff/index.d.ts +++ b/types/onoff/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for onoff +// Type definitions for onoff v3.2 // Project: https://github.com/fivdi/onoff // Definitions by: Marcel Ernst +// Kallu609 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,47 +9,54 @@ export = __ONOFF; declare namespace __ONOFF { - - var version:string; - + var version: string; + interface GpioOptions { - debounceTimeout?:number; - activeLow?:boolean; + debounceTimeout?: number; + activeLow?: boolean; } - + + type Direction = 'in' | 'out' | 'high' | 'low'; + type Edge = 'none' | 'falling' | 'rising' | 'both'; + class Gpio { - constructor(gpio:number, direction:string); - constructor(gpio:number, direction:string, edge:string); - constructor(gpio:number, direction:string, edge:string, options:GpioOptions); - constructor(gpio:number, direction:string, options:GpioOptions); - - gpio:number - gpioPath:string; - opts:GpioOptions; - readBuffer:Buffer; - listeners:Array<(error:Error, value:number) => void>; - valueFd:number; - - read(cb:(err:Error, value:number) => void):void; - readSync():number; - - write(value:number, cb:(err:Error, value:number) => void):void; - writeSync(value:number):void; - - watch(cb:(error:Error, value:number) => void):void; - unwatch():void; - unwatch(cb:(error:Error, value:number) => void):void; - unwatchAll():void; - - direction():string; - setDirection(value:string):void; - - edge():string; - setEdge(value:string):void; - - options():GpioOptions; - - unexport():void; + constructor(gpio: number, direction: Direction, options?: GpioOptions); + constructor( + gpio: number, + direction: Direction, + edge?: Edge, + options?: GpioOptions + ); + + gpio: number; + gpioPath: string; + opts: GpioOptions; + readBuffer: Buffer; + listeners: Array<(err: Error, value: number) => void>; + _valueFd: number; + + read(cb: (err: Error, value: number) => void): void; + readSync(): number; + + write(value: number, cb: (err: Error, value: number) => void): void; + writeSync(value: number): void; + + watch(cb: (err: Error, value: number) => void): void; + unwatch(): void; + unwatch(cb: (err: Error, value: number) => void): void; + unwatchAll(): void; + + direction(): Direction; + setDirection(value: Direction): void; + + edge(): Edge; + setEdge(value: Edge): void; + + activeLow(): boolean; + setActiveLow(invert?: boolean): void; + + options(): GpioOptions; + + unexport(): void; } - } diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts new file mode 100644 index 0000000000..bcdc262d99 --- /dev/null +++ b/types/opossum/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for opossum 1.8 +// Project: https://github.com/bucharest-gold/opossum +// Definitions by: Quinn Langille +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import * as stream from "stream"; + +export type Action = () => any; + +export class CircuitBreaker { + promisify(action: Action): Promise; + stats(): stream.Transform; +} + +export interface CircuitBreakerOptions { + timeout?: number; + maxFailures?: number; + resetTimeout?: number; + rollingCountTimeout?: number; + rollingCountBuckets?: number; + name?: string; + rollingPercentilesEnabled?: boolean; + capacity?: number; + errorThresholdPercentage?: number; + enabled?: boolean; + allowWarmUp?: boolean; +} + +export default function circuitBreaker( + action: Action, + options?: CircuitBreakerOptions +): CircuitBreaker; diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts new file mode 100644 index 0000000000..22778147e5 --- /dev/null +++ b/types/opossum/opossum-tests.ts @@ -0,0 +1,24 @@ +import { Transform } from "stream"; +import circuitBreaker, { CircuitBreaker, CircuitBreakerOptions } from "opossum"; + +const _blank = () => {}; + +const testNoOptions: CircuitBreaker = circuitBreaker(_blank); + +const options: CircuitBreakerOptions = { + timeout: 1, + maxFailures: 1, + resetTimeout: 1, + rollingCountTimeout: 1, + rollingCountBuckets: 1, + name: "testing", + rollingPercentilesEnabled: true, + capacity: 1, + errorThresholdPercentage: 1, + enabled: true, + allowWarmUp: true +}; + +const testWithOptions: CircuitBreaker = circuitBreaker(_blank, options); +const shouldBeAPromise: Promise = testWithOptions.promisify(_blank); +const shouldBeATransformStream: Transform = testWithOptions.stats(); diff --git a/types/opossum/tsconfig.json b/types/opossum/tsconfig.json new file mode 100644 index 0000000000..7ddf39bf63 --- /dev/null +++ b/types/opossum/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", + "opossum-tests.ts" + ] +} diff --git a/types/opossum/tslint.json b/types/opossum/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/opossum/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/optics-agent/index.d.ts b/types/optics-agent/index.d.ts index 2c8ae46283..0d08646a4b 100644 --- a/types/optics-agent/index.d.ts +++ b/types/optics-agent/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apollostack/optics-agent-js#readme // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.6 import { GraphQLSchema } from "graphql"; import { Request, Response } from "express"; diff --git a/types/optics-agent/tsconfig.json b/types/optics-agent/tsconfig.json index 046bfaad81..fe309dafd3 100644 --- a/types/optics-agent/tsconfig.json +++ b/types/optics-agent/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts index 4c03388047..8d9f640f8b 100644 --- a/types/osmosis/index.d.ts +++ b/types/osmosis/index.d.ts @@ -56,8 +56,33 @@ interface Osmosis { * result data, osmosis finished */ data(callback: (param: any) => any): Osmosis; - } - declare const osmosis: Osmosis; + /** + * Set configuration options for the **preceeding** command on down the chain. + */ + config(option: string | { [key: string]: any }, value?: any): Osmosis; - export = osmosis; + /** + * Set a cookie. Short for `.config({ cookies: ... })`. Note: Setting a cookie to `null` will delete the cookie. + */ + cookie(name: string, value: string | null): Osmosis; + + /** + * Set an HTTP header. Short for `.config({ headers: ... })` + */ + header(name: string, value: string): Osmosis; + + /** + * Set multiple HTTP headers. Short for `.config({ headers: ... })`. + */ + headers(headers: { [key: string]: string }): Osmosis; + + /** + * Call a callback when the Osmosis instance has completely finished. + */ + done(callback: () => any): Osmosis; +} + +declare const osmosis: Osmosis; + +export = osmosis; diff --git a/types/osmosis/osmosis-tests.ts b/types/osmosis/osmosis-tests.ts index f0c39d4312..94f08db15e 100644 --- a/types/osmosis/osmosis-tests.ts +++ b/types/osmosis/osmosis-tests.ts @@ -12,9 +12,15 @@ const errorFunction = (error: string) => { const myError = error; }; -// example is from https://github.com/rchipka/node-osmosis#example +const doneFunction = () => {}; + +// modified example from https://github.com/rchipka/node-osmosis#example osmosis + .config({ headers: { 'test-header-name': 'test-header-value' } }) + .headers({ 'test-header-name': 'test-header-value' }) + .header('test-header-name', 'test-header-value') + .cookie('test-cookie-name', 'test-cookie-value') .get('www.craigslist.org/about/sites') .find('h1 + div a') .set('location') @@ -39,4 +45,5 @@ osmosis }) .log(logFunction) .error(errorFunction) - .debug(debugFunction); + .debug(debugFunction) + .done(doneFunction); diff --git a/types/parcel-bundler/index.d.ts b/types/parcel-bundler/index.d.ts index 2122bed672..c661d105cd 100644 --- a/types/parcel-bundler/index.d.ts +++ b/types/parcel-bundler/index.d.ts @@ -168,6 +168,10 @@ declare class ParcelBundler { options?: ParcelBundler.ParcelOptions ); + addAssetType(extension: string, path: string): void; + + addPackager(type: string, packager: string): void; + bundle(): Promise; } diff --git a/types/parcel-bundler/parcel-bundler-tests.ts b/types/parcel-bundler/parcel-bundler-tests.ts index 06a0b5a604..5833b8527b 100644 --- a/types/parcel-bundler/parcel-bundler-tests.ts +++ b/types/parcel-bundler/parcel-bundler-tests.ts @@ -6,4 +6,8 @@ const files = ["./index.d.ts"]; const bundler = new ParcelBundler(files, parcelOption); +bundler.addAssetType('md', 'markdown-asset'); + +bundler.addPackager('md', 'markdown-packager'); + bundler.bundle().then(bundle => bundle.name); diff --git a/types/passport-azure-ad/tslint.json b/types/passport-azure-ad/tslint.json index 3db14f85ea..95d5bcf169 100644 --- a/types/passport-azure-ad/tslint.json +++ b/types/passport-azure-ad/tslint.json @@ -1 +1,13 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "array-type": false, + "ban-types": false, + "callable-types": false, + "eofline": false, + "interface-name": false, + "jsdoc-format": false, + "no-trailing-whitespace": false + } +} diff --git a/types/passport-oauth2/index.d.ts b/types/passport-oauth2/index.d.ts index 7d7f3de21d..d985852bd6 100644 --- a/types/passport-oauth2/index.d.ts +++ b/types/passport-oauth2/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jaredhanson/passport-oauth2#readme // Definitions by: Pasi Eronen // Wang Zishi +// Eduardo AC // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-oauth2/passport-oauth2-tests.ts b/types/passport-oauth2/passport-oauth2-tests.ts index 6a5d09ef27..864b2cb9d6 100644 --- a/types/passport-oauth2/passport-oauth2-tests.ts +++ b/types/passport-oauth2/passport-oauth2-tests.ts @@ -51,6 +51,8 @@ const err3 = new InternalOAuthError('Hello', {}); class MyStrategy extends OAuth2Strategy { useProtectedProperty() { - this._oauth2.get('http://www.example.com/profile', 'token', 'http://www.example.com/callback'); + this._oauth2.get('http://www.example.com/profile', 'token', err => err.statusCode); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result) => result); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); } } diff --git a/types/passport-windowsauth/index.d.ts b/types/passport-windowsauth/index.d.ts new file mode 100644 index 0000000000..dd425a1f59 --- /dev/null +++ b/types/passport-windowsauth/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for passport-windowsauth 3.0 +// Project: https://github.com/auth0/passport-windowsauth#readme +// Definitions by: Emily Marigold Klassen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as express from 'express'; +import * as passport from 'passport'; +import * as ldapjs from 'ldapjs'; +import { TlsOptions } from 'tls'; + +declare namespace windowsauth { + interface Options { + ldap?: { + url?: string + maxConnections?: number + base?: string + bindDN?: string + bindCredentials?: string + tlsOptions?: TlsOptions; + reconnect?: boolean | { + initialDelay?: number, + maxDelay?: number, + failAfter?: number + }; + timeout?: number; + connectTimeout?: number; + idleTimeout?: number; + binder?: ldapjs.Client + client?: ldapjs.Client + }; + integrated?: boolean; + getUserNameFromHeader?(req: express.Request): string; + passReqToCallback?: boolean; + usernameField?: string; + passwordField?: string; + } + type Verified = (err: Error | undefined | null, user?: object, info?: object) => void; + type Verify = (profile: passport.Profile, done: Verified) => void; + type VerifyWithReq = (req: express.Request, profile: passport.Profile, done: Verified) => void; +} + +declare class windowsauth extends passport.Strategy { + constructor(options: windowsauth.Options & {passReqToCallback: true}, verify: windowsauth.VerifyWithReq); + constructor(options: windowsauth.Options, verify: windowsauth.Verify); + constructor(verify: windowsauth.Verify); +} + +export = windowsauth; diff --git a/types/passport-windowsauth/passport-windowsauth-tests.ts b/types/passport-windowsauth/passport-windowsauth-tests.ts new file mode 100644 index 0000000000..cca632ed60 --- /dev/null +++ b/types/passport-windowsauth/passport-windowsauth-tests.ts @@ -0,0 +1,28 @@ +import * as passport from 'passport'; +import * as WindowsStrategy from 'passport-windowsauth'; + +const auth = new passport.Authenticator(); +auth.use(new WindowsStrategy({integrated: true}, (profile, done) => { + console.log(profile); + done(null, profile); +})); + +passport.use(new WindowsStrategy({ + ldap: { + url: 'ldap://wellscordoba.wellscordobabank.com/DC=wellscordobabank,DC=com', + base: 'DC=wellscordobabank,DC=com', + bindDN: 'someAccount', + bindCredentials: 'andItsPass' + } +}, (profile, done) => { + console.log('logged in', profile.id); + done(null, profile); +})); + +passport.use(new WindowsStrategy({ + integrated: true, + passReqToCallback: true +}, (req, profile, done) => { + console.log('logged in', req, profile.id); + done(null, profile); +})); diff --git a/types/passport-windowsauth/tsconfig.json b/types/passport-windowsauth/tsconfig.json new file mode 100644 index 0000000000..070b3d98ed --- /dev/null +++ b/types/passport-windowsauth/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", + "passport-windowsauth-tests.ts" + ] +} diff --git a/types/passport-windowsauth/tslint.json b/types/passport-windowsauth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-windowsauth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pino-http/index.d.ts b/types/pino-http/index.d.ts new file mode 100644 index 0000000000..a93abf406f --- /dev/null +++ b/types/pino-http/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for pino-http 4.0 +// Project: https://github.com/pinojs/pino-http#readme +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { IncomingMessage, ServerResponse } from 'http'; +import { Level, Logger, LoggerOptions } from 'pino'; + +export = PinoHttp; + +declare function PinoHttp(opts?: PinoHttp.Options): PinoHttp.HttpLogger; + +declare namespace PinoHttp { + type HttpLogger = (req: IncomingMessage, res: ServerResponse) => void; + + interface Options extends LoggerOptions { + logger?: Logger; + genReqId?: (req: IncomingMessage) => number; + useLevel?: Level; + } +} + +declare module 'http' { + interface IncomingMessage { + log: Logger; + } +} diff --git a/types/pino-http/pino-http-tests.ts b/types/pino-http/pino-http-tests.ts new file mode 100644 index 0000000000..96207c8d9d --- /dev/null +++ b/types/pino-http/pino-http-tests.ts @@ -0,0 +1,16 @@ +import http = require('http'); +import pino = require('pino'); +import pinoHttp = require('pino-http'); + +const logger = pino(); +const httpLogger = pinoHttp(); + +function handle(req: http.IncomingMessage, res: http.ServerResponse) { + httpLogger(req, res); + req.log.info('something else'); +} + +pinoHttp({ logger }); +pinoHttp({ genReqId: (req) => req.statusCode || 200 }); +pinoHttp({ useLevel: 'error' }); +pinoHttp({ prettyPrint: true }); diff --git a/types/pino-http/tsconfig.json b/types/pino-http/tsconfig.json new file mode 100644 index 0000000000..3adac9b376 --- /dev/null +++ b/types/pino-http/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", + "pino-http-tests.ts" + ] +} diff --git a/types/pino-http/tslint.json b/types/pino-http/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pino-http/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 71cb957643..75f045af01 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -150,6 +150,10 @@ declare namespace P { * Outputs the level as a string instead of integer. Default: `false`. */ useLevelLabels?: boolean; + /** + * Changes the property `level` to any string value you pass in. Default: 'level' + */ + changeLevelName?: string; /** * Use this option to define additional logging levels. * The keys of the object correspond the namespace of the log level, and the values should be the numerical value of the level. diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 356f84da30..cec8f658fb 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -50,7 +50,7 @@ pino({ }); pino({ base: null }); -pino({ base: { foo: 'bar' } }); +pino({ base: { foo: 'bar' } , changeLevelName: 'severity' }); if ('pino' in log) console.log(`pino version: ${log.pino}`); diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 121001b49b..adf853af72 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -13,7 +13,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// +import * as _d3 from "d3"; export as namespace Plotly; export interface StaticPlots { @@ -189,7 +189,7 @@ export function plot(root: Root, data: Data[], layout?: Partial, config? export function relayout(root: Root, layout: Partial): Promise; export function redraw(root: Root): Promise; export function purge(root: Root): void; -export const d3: any; +export const d3: typeof _d3; export function restyle(root: Root, aobj: Data, traces?: number[] | number): Promise; export function update(root: Root, traceUpdate: Data, layoutUpdate: Partial, traces?: number[] | number): Promise; export function addTraces(root: Root, traces: Data | Data[], newIndices?: number[] | number): Promise; diff --git a/types/plotly.js/tsconfig.json b/types/plotly.js/tsconfig.json index dd21321c49..fe2dfd96bd 100644 --- a/types/plotly.js/tsconfig.json +++ b/types/plotly.js/tsconfig.json @@ -13,6 +13,9 @@ "typeRoots": [ "../" ], + "paths": { + "d3": [ "d3/v3" ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/query-string/index.d.ts b/types/query-string/index.d.ts index 8a2f4a30ea..6e560f57e9 100644 --- a/types/query-string/index.d.ts +++ b/types/query-string/index.d.ts @@ -13,13 +13,21 @@ export interface ParseOptions { decode?: boolean; } +export interface InputParams { + [key: string]: any; +} + +export interface OutputParams { + [key: string]: string | string[] | undefined; +} + /** * Parse a query string into an object. * Leading ? or # are ignored, so you can pass location.search or location.hash directly. */ -export function parse(str: string, options?: ParseOptions): any; +export function parse(str: string, options?: ParseOptions): OutputParams; -export function parseUrl(str: string, options?: ParseOptions): {url: string, query: any}; +export function parseUrl(str: string, options?: ParseOptions): {url: string, query: OutputParams}; export interface StringifyOptions { strict?: boolean; @@ -30,7 +38,7 @@ export interface StringifyOptions { /** * Stringify an object into a query string, sorting the keys. */ -export function stringify(obj: object, options?: StringifyOptions): string; +export function stringify(obj: InputParams, options?: StringifyOptions): string; /** * Extract a query string from a URL that can be passed into .parse(). diff --git a/types/query-string/query-string-tests.ts b/types/query-string/query-string-tests.ts index 69c70655ed..33152ce445 100644 --- a/types/query-string/query-string-tests.ts +++ b/types/query-string/query-string-tests.ts @@ -19,20 +19,26 @@ import * as queryString from 'query-string'; result = queryString.stringify({ foo: 'bar' }, { strict: false, encode: false }); } +// For each section below, the second line ensures the real answer is of the declared +// type. You can find the real answer by running the first line of each section. + // parse { - let fooBar: { foo: 'bar' }; - fooBar = queryString.parse('?foo=bar'); - fooBar = queryString.parse('#foo=bar'); - fooBar = queryString.parse('?foo=bar%20baz', { decode: true }); + let fooBar = queryString.parse('?foo=bar'); + fooBar = {foo: "bar"}; - let fooBarBaz: { foo: ['bar', 'baz'] }; - fooBarBaz = queryString.parse('&foo=bar&foo=baz'); + let fooBarBaz1 = queryString.parse('&foo=bar&foo=baz'); + fooBarBaz1 = { foo: [ 'bar', 'baz' ] }; + + let fooBarBaz2 = queryString.parse('&foo[]=bar&foo[]=baz', {arrayFormat: 'bracket'}); + fooBarBaz2 = { foo: [ 'bar', 'baz' ] }; } // extract { - let result: string; - result = queryString.extract('http://foo.bar/?abc=def&hij=klm'); - result = queryString.extract('http://foo.bar/?foo=bar'); + let result1 = queryString.extract('http://foo.bar/?abc=def&hij=klm'); + result1 = 'abc=def&hij=klm'; + + let result2 = queryString.extract('http://foo.bar/?foo=bar'); + result2 = 'foo=bar'; } diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 93c58da4b7..0b4de9932b 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -52,7 +52,7 @@ export interface ClipboardStatic { } export interface QuillOptionsStatic { - debug?: string; + debug?: string | boolean; modules?: StringMap; placeholder?: string; readOnly?: boolean; diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index fe4ebefaf2..b2dcfac727 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -12,6 +12,17 @@ function test_quill() { }); } +function test_quill_opts() { + const quillEditor = new Quill('#editor', { + modules: + { + toolbar: { container: "#toolbar" } + }, + theme: 'snow', + debug: true, + }); +} + function test_scroll() { const quillEditor = new Quill('#editor'); const blot: Blot = quillEditor.scroll; diff --git a/types/react-bootstrap/lib/Dropdown.d.ts b/types/react-bootstrap/lib/Dropdown.d.ts index 1568e6cfb5..a3f8220da7 100644 --- a/types/react-bootstrap/lib/Dropdown.d.ts +++ b/types/react-bootstrap/lib/Dropdown.d.ts @@ -1,7 +1,7 @@ import * as React from 'react'; import { SelectCallback } from 'react-bootstrap'; -import * as DropdownToggle from './DropdownToggle'; -import * as DropdownMenu from './DropdownMenu'; +import DropdownToggle = require('./DropdownToggle'); +import DropdownMenu = require('./DropdownMenu'); declare namespace Dropdown { export interface DropdownBaseProps { @@ -26,5 +26,3 @@ declare class Dropdown extends React.Component { public static Toggle: typeof DropdownToggle; } export = Dropdown; - - diff --git a/types/react-bootstrap/lib/index.d.ts b/types/react-bootstrap/lib/index.d.ts index 1b59d08457..4a3c27a59c 100644 --- a/types/react-bootstrap/lib/index.d.ts +++ b/types/react-bootstrap/lib/index.d.ts @@ -208,8 +208,6 @@ export { ButtonToolbarProps, Carousel, CarouselProps, - CarouselCaption, - CarouselCaptionProps, CarouselItem, CarouselItemProps, Checkbox, @@ -226,20 +224,12 @@ export { DropdownProps, DropdownButton, DropdownButtonProps, - DropdownMenu, - DropdownMenuProps, - DropdownToggle, - DropdownToggleProps, Fade, FadeProps, Form, FormProps, FormControl, FormControlProps, - FormControlFeedback, - FormControlFeedbackProps, - FormControlStatic, - FormControlStaticProps, FormGroup, FormGroupProps, Glyphicon, @@ -252,10 +242,6 @@ export { ImageProps, InputGroup, InputGroupProps, - InputGroupAddon, - InputGroupAddonProps, - InputGroupButton, - InputGroupButtonProps, Jumbotron, JumbotronProps, Label, @@ -266,18 +252,6 @@ export { ListGroupItemProps, Media, MediaProps, - MediaBody, - MediaBodyProps, - MediaHeading, - MediaHeadingProps, - MediaLeft, - MediaLeftProps, - MediaList, - MediaListProps, - MediaListItem, - MediaListItemProps, - MediaRight, - MediaRightProps, MenuItem, MenuItemProps, Modal, @@ -298,12 +272,6 @@ export { NavbarProps, NavbarBrand, NavbarBrandProps, - NavbarCollapse, - NavbarCollapseProps, - NavbarHeader, - NavbarHeaderProps, - NavbarToggle, - NavbarToggleProps, NavDropdown, NavDropdownProps, NavItem, @@ -318,26 +286,10 @@ export { PageItemProps, Pager, PagerProps, - PagerItem, - PagerItemProps, Pagination, PaginationProps, - PaginationItem, - PaginationItemProps, Panel, PanelProps, - PanelHeading, - PanelHeadingProps, - PanelTitle, - PanelTitleProps, - PanelToggle, - PanelToggleProps, - PanelCollapse, - PanelCollapseProps, - PanelBody, - PanelBodyProps, - PanelFooter, - PanelFooterProps, PanelGroup, PanelGroupProps, Popover, @@ -354,8 +306,6 @@ export { SafeAnchorProps, SplitButton, SplitButtonProps, - SplitToggle, - SplitToggleProps, Tab, TabProps, TabContainer, diff --git a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx index 9457cea4a2..c2f1e1e9c8 100644 --- a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx +++ b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx @@ -115,6 +115,7 @@ export class ReactBootstrapIndividualComponentsTest extends React.Component { +